I am trying to print out a bulleted list of all posts in the current posts category (i.e. “siblings”) except for the current post itself.
I have been able to get the tags of the current bost and print out the list of all posts with the same tags as the current post using the following code. However, I was then trying to add to the loop some logic to compare the name of the current post with the posts as they loop, and only if they don’t match generate the bullet item (I know currently the if statement does nothing, I am trying to debug the loop).
The problem is once the loop starts it seems to erase the variable I assigned the current post’s title to.
<?php
// declare array to hold tags
$current_tags = array();
// get the tags on the current post
$posttags = get_the_tags();
if ($posttags) {
foreach($posttags as $tag) {
// add to tags array
$current_tags[] = $tag->name;
}
}
// convert the array to comma-delimited string
$tags = implode(',', $current_tags);
?>
<ul>
<?php
// get the current page's title
$page_title = the_title();
echo $page_title; // "Spicy Lemon Chicken"
$args = array( 'post_type' => 'recipe', 'tag' => $tags );
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post(); ?>
<?
$t = get_the_title(); // get current title in the loop
echo '$t = '.$t;
echo '$page_title = '. $page_title; // empty string
if ( $t != $page_title) { }; ?>
<li><a href="<? the_permalink(); ?>"><? the_title(); ?></a></li>
<? endwhile; ?>
</ul>
First things first, you have a syntax error:
The
the_title()
template tag echoes, rather than returns, the post title. You will want to useget_the_title()
instead:Second, you can simplify things considerably, simply by excluding the current post from your secondary query, by passing the
post__not_in
post parameter to yourWP_Query()
call.Change this:
…to this:
Then, you’ll have no need to test for it inside your secondary query loop.
I would rewrite your secondary query loop like so: