WordPress.org

Support

Support » How-To and Troubleshooting » [Resolved] How to make this code appear on certain posts and not on others?

[Resolved] How to make this code appear on certain posts and not on others?

  • I use the following code to display related posts based on matching tags:

    `<?php
    //for use in the loop, list 5 post titles related to first tag on current post
    $tags = wp_get_post_tags($post->ID);
    if ($tags) {
    echo ‘Related Posts’;
    $first_tag = $tags[0]->term_id;
    $args=array(
    ‘tag__in’ => array($first_tag),
    ‘post__not_in’ => array($post->ID),
    ‘showposts’=>5,
    ‘caller_get_posts’=>1
    );
    $my_query = new WP_Query($args);
    if( $my_query->have_posts() ) {
    while ($my_query->have_posts()) : $my_query->the_post(); ?>

    <p>” rel=”bookmark” title=”Permanent Link to <?php the_title_attribute(); ?>”><?php the_title(); ?></p>

    <?php
    endwhile;
    }
    }
    ?>`

    It works by checking to see if there are any other posts that match the first tag that the current post is assigned to and then those other posts are displayed under the heading: “Related Posts”.

    The problem is, if there are no similar posts found it still shows the “Related Posts” heading with an empty space underneath it. I really want the entire thing to display only when there is at least one related post and not display at all when there is none. Can someone please alter this code to make that happen?

    Thank you.

Viewing 5 replies - 1 through 5 (of 5 total)
Viewing 5 replies - 1 through 5 (of 5 total)
  • The topic ‘[Resolved] How to make this code appear on certain posts and not on others?’ is closed to new replies.