“Notice: Undefined variable: content” is showing [closed]

Although the actual question is off topic, I would make a few alterations to the code to make it more reliable and a bit faster and less resource intensive:

  • Add $content=""; right at the top of the function, this will take care off the Notice: Undefined variable notice

  • Only get the term id’s from wp_get_post_terms(). This will make this function faster and you will not retrieve info that you are not going to use. Just add array('fields' => 'ids' ) as the third parameter

  • Instead of using the $post global which is not very reliable, use get_queried_object() to get the current post info

  • Removed the counter, I don’t see any need for that

  • WP_Query is just a personal preference as you don’t need to setup postdata and use the $post global

Here is the function rewritten

function pippin_related_posts($taxonomy = '') {

    $current_post = get_queried_object();
    $content="";

    if($taxonomy == '') { $taxonomy = 'post_tag'; }

    $tags = wp_get_post_terms($current_post->ID, $taxonomy, array('fields' => 'ids' ));

    if ($tags) {
        $first_tag  = $tags[0];
        $second_tag = $tags[1];
        $third_tag  = $tags[2];
        $args = array(
            'post_type' => $current_post->post_type,
            'posts_per_page' => 4,
            'tax_query' => array(
                'relation' => 'OR',
                array(
                    'taxonomy' => $taxonomy,
                    'terms' => $second_tag,
                    'field' => 'id',
                    'operator' => 'IN',
                ),
                array(
                    'taxonomy' => $taxonomy,
                    'terms' => $first_tag,
                    'field' => 'id',
                    'operator' => 'IN',
                ),
                array(
                    'taxonomy' => $taxonomy,
                    'terms' => $third_tag,
                    'field' => 'id',
                    'operator' => 'IN',
                )
            )
        );
        $related = new WP_Query($args);

        if( $related->have_posts() ) {
            while($related->have_posts() ) {
                the_post();

                    $content .= '<ul class="related-posts-box">';
                        $content .= '<li><a href="' . get_permalink() . '" title="' . get_the_title() . '">' . get_the_title() . '</a></li>';
                    $content .= '</ul>';

            }
            wp_reset_postdata();
        }
    }

    return $content;
}        


add_action('the_content', 'do_jt_related_posts');
function do_jt_related_posts() {


    if( is_singular('post') ) :
        echo get_the_content();
        echo pippin_related_posts();        
    else : 
        echo get_the_content();
    endif;
}