wordpress WP Query order by views count - php

hello I wanted to order articles post type by views count in wordpress. so I added a custom field to article post type which the name is view and it is a number field. I added it with PODS. I wrote this code in header.php so it it will incremenet automatically by each view:
<?php
if( get_post_type() == 'article' ) {
$postview = intval(get_post_field('views'));
if($postview > 0){
$postview = $postview+1;
}else{
$postview = 1;
}
$postID = $post->ID;
update_post_meta($postID,'views',$postview);
}
?>
it worked. but when I wanted to add a advanced query by elementor it does not work as expected. I added this to functions.php:
add_action( 'elementor/query/popular_articles', function( $query ) {
$query->set('post_type', 'article');
$query->set('meta_key', 'views');
$query->set('orderby', 'meta_value_num');
$query->set('order', 'DESC');
} );
I also tried this:
add_action( 'elementor/query/popular_articles', function( $query ) {
$query->set('orderby', 'views');
} );
none of those work as expected in elementor posts widget and the result is not sorted. when I set the popular_article query. the thing that I want to achieve with Wordpress WP_Query is something like this SQL query:
select post_title ,wp_z9gsc7_postmeta.meta_key,wp_z9gsc7_postmeta.meta_value from wp_z9gsc7_posts INNER JOIN wp_z9gsc7_postmeta ON wp_z9gsc7_posts.ID = wp_z9gsc7_postmeta.post_id where wp_z9gsc7_postmeta.meta_key = 'views' ORDER BY wp_z9gsc7_postmeta.meta_value DESC
thank you for your response in advance

this worked:
add_action( 'elementor/query/popular_articles', function( $query ) {
$query->set('post_type', 'article');
$query->set('meta_key', 'views');
$query->set('orderby', 'meta_value_num');
$query->set('order', 'DESC');
$query->set('offset', 0);
} );

Related

Sort posts by their date in ACF

I have a custom post type Archiv Kursunterlagen with some custom fields such as post_date. I want the posts of that post type to show in descending order by the custom field. I tried looking into other answers and modified the query. But it didn't work.
function my_pre_get_posts( $query ) {
// only modify queries for 'archive' post type
if( isset($query->query_vars['post_type']) && $query->query_vars['post_type'] == 'archiv_kursunterlage' ) {
$query->set('orderby', 'meta_value');
$query->set('meta_key', 'post_date');
$query->set('order', 'DESC');
}
return $query;
}
add_action('pre_get_posts', 'my_pre_get_posts');
I have put this in a snippet and set it to run everywhere. Am I doing it right? or is there any problem with the query itself?
You can simply add the line in your code:
$query->set('order', 'DESC');
Please visit the link for more details:
https://www.advancedcustomfields.com/resources/orde-posts-by-custom-fields/
or
https://developer.wordpress.org/reference/hooks/pre_get_posts/

Elementor Posts Widget Custom Query: found_posts return 0

I am creating a custom query based on some selected posts in Elementor pro Posts Widget. below is code. The query is displaying posts correctly in Posts widget but found_posts always shows zero value. Can some body help me.
function my_fav_by_user($fav_query) {
$fav_query->set( 'post__in', array(2783,2780,2793,2528,2873, 2477,2892,2890));
_e("Total Posts=".$fav_query->found_posts, 'my-text-domain');
}
add_action( 'elementor/query/my_fav_query3', 'my_fav_by_user' );
I'm facing the same issue like I'm fetching the IDs of the selected post from a ACF relationship field.
I'm editing my comment again here.
I just found the solution.
function related_insights_query( $query ) {
$postid = get_the_ID();
$ids = get_post_meta($postid, 'call_rel_insights', true);
if ( $ids ) { $query->set( 'post__in', $ids ); }
}
add_action( 'elementor/query/rel_insights', 'related_insights_query' );
get_field was causing an infinite loop.

Wordpress admin edit-post screen: filter both custom posts and regular posts by category

I have added a filter on pre_get_posts to merge a custom post type with the regular posts in the edit-post screen.
All posts are listed but when I try to filter these posts by category, I got an
"invalid post type" error.
Indeed, the post_type parameter in the query string is set to "(...)&post_type=Array(...)"
Is this possible using some other hook or filter?
// show custom posts in the admin posts list
function Myplugin_posts_add_custom( $query ) {
$screen = get_current_screen();
if ( is_admin() && $screen->base == 'edit' && $screen->id == 'edit-post' && $screen->post_type == 'post' ) :
$post_types = array('post', 'my_custom_post');
$query->set( 'post_type', $post_types );
return $query;
endif;
}
add_filter( 'pre_get_posts', 'Myplugin_posts_add_custom' );
Thanks for you help

WP archives order by custom meta key

in Wordpress template's function.php following code is working well
// Function accepting current query
function my_change_order( $query ) {
// Check if the query is for an archive
if($query->is_archive())
// Query was for archive, then set order
$query->set( 'order' , 'asc' );
// Return the query (else there's no more query, oops!)
return $query;
}
// Runs before the posts are fetched
add_filter( 'pre_get_posts' , 'my_change_order' );
But i need to order articles by custom meta key like _my_meta_vip. Based on this answer i tried following lines, with half success, because only load articles with defined custom meta key, others are missing. How can i solve that?
function my_change_order( $query ) {
if($query->is_archive())
$query->set( 'orderby' , 'meta_value' );
$query->set( 'meta_key' , '_my_meta_vip' );
return $query;
}
add_filter( 'pre_get_posts' , 'my_change_order' );
How can i order my articles by custom meta key properly?
function my_change_order( $query ) {
// Check if the query is for an archive
if($query->is_archive())
// Query was for archive, then set order
$query->set( 'order' , 'asc' );
$query->set( 'meta_query', array(
array(
'key' => '_my_meta_vip'
)
));
// Return the query (else there's no more query, oops!)
return $query;
}
look at the following topic: https://wordpress.stackexchange.com/questions/20237/using-meta-query-how-can-i-filter-by-a-custom-field-and-order-by-another-one may give you a clear idea
Finally can't find any way to list all post with and without _my_meta_VIP defined.
In my solution all _my_meta_VIP was filled with enabled or disabled and the following code do the job:
// Function accepting current query
function my_change_order( $query ) {
// Check if the query is for an archive
if($query->is_archive()) {
// Query was for archive, then set order
$query->set( 'post_type', 'profile' );
$query->set( 'orderby' , 'meta_value' );
$query->set( 'meta_key' , '_my_meta_vip' );
$query->set( 'order', 'DESC' );
} else {
// Return the original query for non-archive pages
return $query;
}
// Return the query
return $query;
}
// Runs before the posts are fetched
add_filter( 'pre_get_posts' , 'my_change_order' );
It looks like the underlying issue here is that the query is doing an inner join on the posts and postmeta tables, which is why posts that don't have that particular post meta entry aren't being returned by the query. What you want is a left join. See this answer for an explanation of the difference.
You should be able to use the posts_join filter to replace the inner join with a left join:
add_filter('posts_join', function($join) {
global $wpdb;
// Replace inner join with left join
$search = 'INNER JOIN ' . $wpdb->postmeta;
$replace = 'LEFT JOIN ' . $wpdb->postmeta;
$join = str_ireplace($search, $replace, $join);
return $join;
});

How to exclude a post by id from the category.php query in wordpress

I have a template where there is a main latest featured post (tagged as featured), and then 8 more below it.
On the homepage, i was able to query for the latest featured post, and then pass its id to a function in the pre_get_posts wordpress filter. it works great there
function mh_exclude_featured_query( $query ) {
if(is_home()){
if ( $query->is_home() ) {
$feat = get_featured_post();
$query->query_vars['post__not_in'] = array($feat->ID);
}
}
}
add_action( 'pre_get_posts', 'mh_exclude_featured_query' );
but i'm also trying to do the same thing in the category.php, where i would show the latest post tagged as featured from that category. and then the remaining posts below with the featured post excluded.
Unfortnately, when i try the same method as above by using the pre_get_posts filter, i get stuck in an infinite loop and run out of memory.
if($query->is_category() && $query->is_main_query()){
$cur_cat_id = get_cat_id( single_cat_title("",false) );
$feat = get_featured_post($cur_cat_id);
$query->query_vars['post__not_in'] = array($feat->ID);
}
not sure what i'm doing differently that leads to a memory exhaustion. the category.php and index.php are near identical in their structure.
use the pre_get_posts filter:
<?php
function excludePostId($query) {
$postIds = array(
24, 10
);
if (is_category() && is_main_query()) {
set_query_var('post__not_in', $postIds);
}
}
add_action('pre_get_posts', 'excludePostId');
is_category() will accept a category slug or ID. You can limit which categories the post will be excluded from.
Add This Code
<?php if(!is_category('category_id')){
echo 'Your Code Here';
}?>

Categories