Advertisement
salmancreation

"Latest Posts From This Category" wordpress development

Oct 30th, 2015
120
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.10 KB | None | 0 0
  1. Example #2: "Latest Posts From This Category" (Except the Current Post)
  2.  
  3. Let's say that you want to create a loop under each post in their single post pages, and list latest posts from the category that the post is in. Of course, you have to exclude the current post in case it might be one of the latest posts from that category. Here's how you create the query with the 'cat' and 'post__not_in' parameters:
  4.  
  5. <?php
  6.  
  7. // Get the current post id.
  8. $current_post_id = get_the_ID();
  9.  
  10. // Get the current post's category (first one if there's more than one).
  11. $current_post_cats = get_the_category();
  12. $current_post_first_cat_id = $current_post_cats[ 0 ]->term_id;
  13.  
  14. // Setup arguments.
  15. $args = array(
  16.     // Get category's posts.
  17.     'cat' => $current_post_first_cat_id,
  18.     // Exclude current post.
  19.     'post__not_in' => array( $current_post_id )
  20. );
  21.  
  22. // Instantiate new query instance.
  23. $my_query = new WP_Query( $args );
  24.  
  25. ?>
  26.  
  27. For the loop, I suggest creating three or four columns with post thumbnails above post titles. It will look really nice right under the post and before the comments section.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement