Sunday, February 13, 2022

[FIXED] Wordpress WP-Query issue when applying filters

Issue

I am trying apply filters to my Wordpress query. I am having issues with getting the author query to work. from my url I pass the name of the author however the filter is not working. I am still getting all post from all authors. Can someone point me in the right direction to query with author

add_filter("wcra_pictures_callback", "wcra_pictures_callback_handler");

function wcra_pictures_callback_handler($param) {
  //$param = All GET/POST values will be received from endpoint
  
  // Get Posts
    $posts = get_posts([
        'post_type' => $param['post_type'],
        'author' => $param['author'],
        'orderby' => $param['orderby'],
        'order'   => $param['order'],
        'posts_per_page' => $param['posts_per_page'],
    ]);
  
  return $posts;
}

Solution

author expects you to pass the author ID, which is an int, and not the author name, if you want to query using author name, you should use author_name in which case you should pass the user_nicename and not the actual name of the author.

Ex.

$posts = get_posts([
  'post_type'      => $param['post_type'],
  'author_name'    => $param['author'], // the name must match the user_nice name in their profile
  'orderby'        => $param['orderby'],
  'order'          => $param['order'],
  'posts_per_page' => $param['posts_per_page'],
]);


Answered By - aghoshx

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.