Support » Developing with WordPress » Getting related post category

Viewing 4 replies - 1 through 4 (of 4 total)
  • Moderator 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.

    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?

    Try below code to show related post.

    $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 );
        <h1><?php the_title(); ?></h1>

    Let me know your status.

    Tried to put that into the code `function eg_mod_query($query, $grid_id){
    just couldn’t get it to compile.

Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘Getting related post category’ is closed to new replies.