So I've used pre_get_posts
in my functions.php
before and it works like a charm, but for some reason I can't figure out why it's not working for a WooCommerce page archive-product.php
I have.
Directory Structure:
.
├──woocommerce
| ├── archive-product.php
├── functions.php
Inside functions.php
:
function specific_category( $query ) {
if ( $query->is_home() && $query->is_main_query() ) {
$query->set( 'cat', '7815' );
}
}
add_action( 'pre_get_posts', 'specific_category' );
Inside archive-product.php
:
var_dump($wp_query); //this should be the main query variable but doesn't exist.
Then I tried this inside archive-product.php
:
global $wp_query;
foreach($wp_query->posts as $k){
print_r($k);
echo "<br>";
echo "<br>";
}
Which does output posts but the posts aren't relative to the category set in the functions.php
code $query->set( 'cat', '7815' );
Question: Why am I having to declare global $wp_query
(it should be initialize by default) and why aren't the post from the category I selected?
When in a page, the query you're seeing is the category with one page that's basically the page you're seeing. Its not a list of posts as you expected to see on the homepage.
if you have a normal blog-style homepage and you check the query you can see [found_posts] => 4
. but try to set a 'page' as homepage and check your query. You can see [found_posts] => 1
and that one found item (post/page) in your query is the current one.
You can try to add a custom query with Wordpress WP_Query
class in your Page Template and it gives you a lot of options too.
Also, if you're trying to check for a homepage that is showing a page, consider using is_front_page()
.
and for your other question about declaring $wp_query
, unfortunately I don't have an answer.