I am on Archive Page of a custom post type gallery.

I have introduced custom permalink variable - author_id.

Lets say i get the permalink variable in $perm_author_id. I want to compare $perm_author_id and get_the_author_meta(ID) and then display the posts if they are equal.

How can I limit posts displayed on the archive page on to those posts posted by author whose author_id is present in permalink?

  • You've added author ID to which permalinks? Authors already have their own archives, /author/author-name/. – Milo Sep 10 '15 at 17:12
  • i have updated my post – Shahrukh Khan Sep 10 '15 at 18:31
function comment_author_id($query) {
    $author_id = get_query_var( 'hotel_name' );
    if ($author_id) {
      $query->set('author', $author_id);

add_action( 'pre_get_posts', 'comment_author_id' );
  • Dont i have to use some hook? – Shahrukh Khan Sep 10 '15 at 18:33
  • please tell me if pre_get_posts can be used or if i have to use something else – Shahrukh Khan Sep 10 '15 at 18:45
  • I think you have a choice between using a hook (function.php) or make a WP_Query xxxx.php in the archive-file. WP_Query seems easier to do with the previous code. – mirado Sep 10 '15 at 19:06
  • thanks this code works fine....but i want it to be limited it to only gallery post type – Shahrukh Khan Sep 10 '15 at 19:11
  • you can use $query->set('post_type','gallery') if you prefer hook or put post_type as argument with WP_Query – mirado Sep 10 '15 at 19:14

What you want to do is commonly known as modifying the main query. There are a lot of faulty advice out there on topic, guiding to make the modification in template — don't.

The most common approach has following steps:

  1. Use appropriate hook, typically this would be pre_get_posts.
  2. Check that you work with correct instance of query object, using its methods. In your case to verify that it's main query and required archive.
  3. Modify query by adding your custom author argument.

It's a little vague how you have implemented the permalink logic, but some searching and reading up on pre_get_posts should get you started.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.