Cannot apply category from URL to QueryLoop Block
-
I have custom post type named ‘site’. I created Page ‘sites’ that contains QueryLoop set to show all posts of type ‘site’. That works fine. I can open page at “www.mydomain.com/sites/” and I see all posts.
I tried same thing using custom archive first, but with no result (the same behavior) so I switched to try with page.
Custom Post type uses Categories so I want to be able to show posts filtered by category. Idea is to use url to specify category like: ‘www.mydomain.com/sites/sports’.
I createdadd_action( 'init', 'un_add_sites_rewrite_rule'); function un_add_sites_rewrite_rule() { $rule = '^sites/(.+?)/?$'; $rewrite = 'index.php?pagename=sites&category_name=$matches[1]'; add_rewrite_rule($rule,$rewrite,'top'); };
After that, url https://www.mydomain.com/sites/sports works (no 404 error) but shows all posts, not filtered by category.
For some reason query_var category_name is not taken in consideration by QueryLoop. From what I learned so far QueryLoop should use category_name value if it is set.
I created action to investigate what happens on query:
add_action( 'pre_get_posts', 'un_test_posts_query' ); function un_test_posts_query( $query ) { if ($query->query['post_type'] == 'site') { echo "<pre>"; global $wp; print_r ($wp->query_vars); print_r ($query->query) echo "<pre>"; }
This shows that var_query does contain category_name and it is properly populated as expected. But $query does not follow that.
Array ( [category_name] => sports [pagename] => sites ) Array ( [post_type] => site [order] => ASC [orderby] => title [post__not_in] => Array ( ) [offset] => 0 [posts_per_page] => 24 [tax_query] => Array ( ) [meta_query] => Array ( ) )
I am confused. Why this does not work?
- The topic ‘Cannot apply category from URL to QueryLoop Block’ is closed to new replies.