wp-ulike icon indicating copy to clipboard operation
wp-ulike copied to clipboard

order by issue

Open mohitYogi opened this issue 5 years ago • 1 comments

I am trying to order my posts by using order by likes, but this does not return posts which have not been voted yet.
There is a list of custom posts, I ordered it by number of likes but it does not returns the newly created posts on which no voting has been done yet.

$query     = array(
	"post_type" => "books",
	'orderby' 	=> 'meta_value_num',
	'meta_key'  => '_liked',
); 
$the_query = new WP_Query( $query );

Error 2: If I use any meta key selector in query args & also use orderby then order by meta key & value replaces other meta key value.

$query     = array(
	"post_type"      => "books",
	"meta_key"	=>"is_read",
	"meta_value"    =>1,
	'orderby' 	=> 'meta_value_num',
	'meta_key'        => '_liked',
);
$the_query = new WP_Query( $query );

SQL: SELECT SQL_CALC_FOUND_ROWS wp_posts.ID FROM wp_posts INNER JOIN wp_postmeta ON ( wp_posts.ID = wp_postmeta.post_id ) WHERE 1=1 AND ( ( wp_postmeta.meta_key = '_liked' AND wp_postmeta.meta_value = '1' ) ) AND wp_posts.post_type = 'books' AND (wp_posts.post_status = 'publish' OR wp_posts.post_status = 'acf-disabled' OR wp_posts.post_author = 4 AND wp_posts.post_status = 'private') GROUP BY wp_posts.ID ORDER BY wp_postmeta.meta_value+0 DESC LIMIT 0, 10

mohitYogi avatar Aug 08 '19 12:08 mohitYogi

I encountered this same issue with needing to orderby likes and having the query exclude posts that had not yet been liked. I've added the following snippet to auto-add post meta with value 0 for all posts when either added or updated. Those posts will then be returned in the query.

add_action( 'save_post', function( $id, $post, $udpate ) {

   if ( ! $update || ! empty( get_post_meta( $id, '_liked' ) ) ) {

      add_post_meta( $id, '_liked', 0, true );

   }

}, 10, 3 );

uamv avatar Oct 01 '19 19:10 uamv