Are you modifying the main query/loop on a page or creating a secondary query/loop?
Main Query of a page, i tried to use pre_get_posts, but i didnt had luck
add_action( 'pre_get_posts', 'get_popular_posts' );
function get_popular_posts( $query ) {
if ( ! is_admin() && $query->is_main_query() && $query->get('pagename')=='popular'){
$query->set(
'meta_query',
array(
'relation' => 'AND',
array(
'key' => 'hello_views_count',
)
)
);
$query->set('orderby', 'meta_value_num');
}
return $query;
}
What I need to do is to change the order of the posts, according to the postmeta “hello_views_count”..
Do you know a better way, or how to fix the above code?
Right now all i get is a 404
If this is the main query, why are you using query_posts() in a function instead of in the template file itself?
I wanted to reuse the code inside content.php
And the code inside content.php relies on $posts global variable..
What theme are you using?
Sorry? Do you mean that you are not using a theme or that “None” is the name of the theme?
Is there a way to change easily the post ordering depending on a custom field value, on homepage or inside a page?
haha, no, i am making one, sorry..
Ah! π
So is:
if ( have_posts() ) : while ( have_posts() ) : the_post();
within content.php or in the template that calls content.php?
I know where you are going, you want me to create another WP_QUERY, and yes i could do that, but i dont want to..
Thank a lot for your help btw,..
Is there a way i can populate “$posts” after query_posts(), or get the orderby in “pre_get_posts” filter (above) to work?
..It is in the template file: popular-page.php
NVM, thanks a lot for your help, i realized this was working on homepage:
$query->set('meta_key', 'hello_views_count');
$query->set('order', 'DESC');
$query->set('orderby', 'meta_value_num');
So i’ll add a parameter to the url on homepage and add a condition to retrive the custom sort:
add_action( 'pre_get_posts', 'get_popular_posts' );
function get_popular_posts( $query ) {
if ( ! is_admin() && $query->is_main_query() $query->is_homepage() ){
if(isset($_GET['filter'])){
$query->set('meta_key', 'hello_views_count');
$query->set('order', 'DESC');
$query->set('orderby', 'meta_value_num');
}
}
return $query;
}
Thanks for your time Esmi! π