Last active
July 21, 2021 04:36
-
-
Save Ceekay0/4576077 to your computer and use it in GitHub Desktop.
Wordpress: Show related posts by tag. The tag the snippet is looking for needs to be setup in the WP admin interface using the custom value keyword = your_tag
Output is as unordered list with links.
Snippet is fully i8n compatible You can use this in any Wordpress Template, not just single.php
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** SHOW RELATED POSTS BY TAG, TAG IS INDICATED BY CUSTOM PROPERTY keyword => tag **/ | |
/** check for custom property **/ | |
$key = 'keyword'; | |
$keyword = get_post_meta($post->ID, $key, true); | |
if ($keyword != '') { | |
/** set max number of posts **/ | |
$num_posts = '4'; | |
/** setup the query array **/ | |
$args=array( | |
/** wordpress stores spaces in custom values differently than tags, so replace them with dashes **/ | |
'tag' => str_replace(' ', '-', $keyword), | |
'post__not_in' => array($post->ID), | |
'showposts'=>$num_posts, | |
'ignore_sticky_posts'=>1 | |
); | |
$original_post = $post; | |
/** get tags from current post.. **/ | |
$tags = wp_get_post_tags($post->ID); | |
/** ..and only show it if there are any ; remove the if statement if this should not get checked **/ | |
if ($tags) { | |
/** run the query **/ | |
$my_query = new WP_Query($args); | |
if( $my_query->have_posts() ) { | |
/** change the kubrick to textdomain of your theme **/ | |
/** capitilize all first letters of the tags that we're showing, remove the ucwords if you don't want that... **/ | |
echo '<h4 class="PostRelatedPostsHeader">', _e('Related Posts for Topic ', 'kubrick'), ucwords($keyword) . ' </h4>';?> | |
<div class="PostRelatedPosts"> <ul class="related_posts"> | |
<?php while ($my_query->have_posts()) : $my_query->the_post();?> | |
<li><a href="<?php the_permalink() ?>" rel="bookmark" title="<?php _e('Permanent Link to ', 'kubrick'); the_title_attribute(); ?>"><?php the_title();?></a> | |
</li> | |
<?php endwhile;?> </ul></div> <?php } } | |
/** reset the query **/ | |
$post = $original_post; wp_reset_query(); | |
}?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment