Skip to content

Instantly share code, notes, and snippets.

Created March 12, 2015 20:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save anonymous/8bd60d3273ca85cffa27 to your computer and use it in GitHub Desktop.
Save anonymous/8bd60d3273ca85cffa27 to your computer and use it in GitHub Desktop.
Genesis Custom Page Template showing related posts by tag
<?php
/*
template name: Fells
*/
/** Code for custom loop */
function my_custom_loop() {
$tags = wp_get_post_tags($post->ID);
if ($tags) {
$tag_ids = array();
foreach($tags as $individual_tag) $tag_ids[] = $individual_tag->term_id;
echo 'Related Posts';
$args=array(
'tag__in' => $tag_ids,
'post__not_in' => array($post->ID),
'showposts'=>5,
'ignore_sticky_posts'=>1
);
$my_query = new WP_Query($args);
if( $my_query->have_posts() ) {
while ($my_query->have_posts()) : $my_query->the_post(); ?>
<p><a href="<?php the_permalink() ?>" rel="bookmark" title="
<?php the_title_attribute(); ?>">
<?php the_title(); ?></a></p>
<?php
endwhile;
}
}
}
/** Replace the standard loop with our custom loop */
add_action( 'genesis_loop', 'my_custom_loop' );
genesis();
@billerickson
Copy link

A few issues I see:

  1. You haven't instantiated the global $post. If you had debug mode on you'd see errors saying "trying to get the property of a non-object $post" since $post doesn't yet exist in your function. Two ways to solve this:
    a) Add global $post; at the top of your function (before $tags).
    b) Replace all the $post->ID with get_the_ID(). This is the method I usually use so I don't have to worry about whether global $post has been stated yet.
  2. You've added your new loop using the add_action, but you never removed Genesis' default loop. You also need to add remove_action( 'genesis_loop', 'genesis_do_loop' );
  3. You need to add wp_reset_postdata() after your loop so that the main $post object will go back to the main query's when your loop is complete. If you don't, it could mess up other things. For instance, if you had this at the bottom of a post but before the comments, without resetting the post data you'd see the comments for the last post in your custom loop rather than the actual post on the page.

Here's what it would look like if I did it: https://gist.github.com/billerickson/67cf0c77a74f409da652

In addition to fixing the above issues, I cleaned up the code a bit using WP coding standards.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment