Created
November 11, 2015 13:54
-
-
Save dstollie/525a01ba93f37aeabc59 to your computer and use it in GitHub Desktop.
Wordpress Snippet: Simple snippet to get the following, previous and related posts of a post of a certain post type
This file contains 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 | |
/** | |
* returns a WP_Query instance which generates a list of news items which have the same theme taxonomy as the given post. | |
* If not post is given the global post will be used | |
* | |
* @param null $postId | |
* @param [] $query | |
* | |
* @return WP_Query | |
*/ | |
public static function getRelatedPosts($postId = null, $query = []) | |
{ | |
$post = get_post($postId); | |
$postsQueryArgs = array_merge([ | |
'post_type' => $post->post_type, | |
'posts_per_page' => 4, | |
'tax_query' => [], | |
'orderby' => 'date', | |
'order' => 'DESC', | |
'post__not_in' => [$post->ID] | |
], $query); | |
// Get all the news themes of the curren post | |
$postNewsThemes = wp_get_post_terms($post->ID, THEME_TAXONOMY); | |
$firstNewsTheme = null; | |
// If the post got a news theme attached | |
if (isset($postNewsThemes[0])) { | |
// Save the first news theme in a seperate variable so it can be used in the view for later purposes | |
$firstNewsTheme = $postNewsThemes[0]; | |
// the '$recentPostsQueryArgs' variable is used to create a query for the recent posts. | |
// We want show all the recent posts which have the same news theme atttached | |
$postsQueryArgs['tax_query'] = [ | |
[ | |
'taxonomy' => $firstNewsTheme->taxonomy, | |
'field' => 'slug', | |
'terms' => [$firstNewsTheme->slug] | |
] | |
]; | |
} | |
return new WP_Query($postsQueryArgs); | |
} | |
public static function getLatestPost($postId = null) | |
{ | |
// Get the latest post using the getRelatedPosts function. But instead of getting a few posts only get the first one | |
$relatedPosts = self::getRelatedPosts($postId, [ | |
'posts_per_page' => 1, | |
]); | |
// If the first key has a value we've found our latest post | |
return isset($relatedPosts->posts[0]) ? $relatedPosts->posts[0] : null; | |
} | |
public static function getFollowingPost() | |
{ | |
$previousPost = get_previous_post(false, '', THEME_TAXONOMY); | |
return !empty($previousPost) ? $previousPost : self::getLatestPost(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment