I have a very simple index.php file in my wordpress myTheme folder where I want to show only the posts with "friends" category using the 'pre_get_posts' hook. But the $query->is_main_query() in the if condition is returning false. That's why it's not working, it's showing all the posts. Here is the code in my index.html file:
<?php
function myCategory( $query ) {
if ( ! is_admin() && $query->is_main_query() && $query->is_search() ) {
$query->set( 'category_name', 'friends' );
}
}
add_action( 'pre_get_posts', 'myCategory' );
$paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;
$wp_query = new WP_Query( 'posts_per_page=2&paged='.$paged );
if ($wp_query->have_posts()) {
while ( $wp_query->have_posts() ) {
$wp_query->the_post();
echo "<h2><a href='".get_the_permalink()."'>".get_the_title()."</a></h2>";
the_content("read more..",false);
}
}
previous_posts_link("<< Previous");
next_posts_link("More >>");
?>
But when I am using the following code just removing the $query->is_main_query() from the if condition inside the myCategory() function, it's working.
<?php
function myCategory( $query ) {
if ( $query->is_home() && ! is_admin() ) {
$query->set( 'category_name', 'friends' );
}
}
add_action( 'pre_get_posts', 'myCategory' );
$paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;
$wp_query = new WP_Query( 'posts_per_page=2&paged='.$paged );
if ($wp_query->have_posts()) {
while ( $wp_query->have_posts() ) {
$wp_query->the_post();
echo "<h2><a href='".get_the_permalink()."'>".get_the_title()."</a></h2>";
the_content("read more..",false);
}
}
previous_posts_link("<< Previous");
next_posts_link("More >>");
?>
Now, I want to know why the $query->is_main_query() is returning false. Could anyone explain please?