Support » Developing with WordPress » Getting related post category

Viewing 3 replies - 1 through 3 (of 3 total)
  • Moderator bcworkz

    (@bcworkz)

    According to the FAQ link you posted, you don’t as much write your own query as modify the grid query. From their examples there, it appears the passed $query is not the WP_Query object, but the object’s query_vars array. Much of the Codex examples for modifying query objects will not directly apply, some interpretation is required.

    Another problem is a filter callback has limited scope, it is passed only the grid ID and the query_vars array. We don’t know what the current post is in this context, nor its categories. If this essgrid_get_posts filter only fires for single post requests, we can get the current post ID with get_queried_object_id(). With the ID, we can get the post categories with wp_get_post_categories(). Use the ['fields'=>'ids',] arguments parameter to only get an array of category IDs returned, which is all you need for the query categories argument.

    You didn’t specify if you want AND category logic or OR logic. Posts with all the same categories or posts with any of the categories. Depending on what, set either the ‘category__and’ or ‘category__in’ query var to the array of category IDs from the current post using a “essgrid_get_posts” filter callback.

    funsail

    (@funsail)

    I want or logic. Most posts have only 1 category anyway.

    Well I can’t say I understand ‘single post requests’ vs the alternative, but I only have grids at the bottom or single posts so I guess it’s safe to say yes?

    ThemesGrove

    (@themesgrove)

    Hello,
    Try below code to show related post.

    
    <?php
    $args = array(
      'post_type' => 'post',
      'posts_per_page' => 3, 
    'category__in' => wp_get_post_categories(get_the_ID()),  
    'post__not_in' => array( get_the_ID() )
    );
    $post_query = new WP_Query( $args );
    if($post_query->have_posts()):
      while($post_query->have_posts()):
        $post_query->the_post();
        ?>
        <h1><?php the_title(); ?></h1>
        <?php
      endwhile();
      wp_reset_query();
    endif;
    

    Let me know your status.
    Thanks.

Viewing 3 replies - 1 through 3 (of 3 total)
  • You must be logged in to reply to this topic.