WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] How to make this code appear on certain posts and not on others? (6 posts)

  1. Benjamin_SP
    Member
    Posted 5 years ago #

    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.

  2. Doodlebee
    Member
    Posted 5 years ago #

    Move your header to right after the "if" statement (before "while").

  3. Benjamin_SP
    Member
    Posted 5 years ago #

    Move your header to right after the "if" statement (before "while").

    See, I have no idea what that means, I only know html/css. Can you please give an example?

  4. Samuel Wood (Otto)
    Tech Ninja
    Posted 5 years ago #

    See where it says echo 'Related Posts';? Move that line to just after the if( $my_query->have_posts() ) { line.

  5. Doodlebee
    Member
    Posted 5 years ago #

    ::points up:: what he said :)

  6. Benjamin_SP
    Member
    Posted 5 years ago #

    Worked! - many thanks to both of you.

Topic Closed

This topic has been closed to new replies.

About this Topic