Display sticky posts first with WP_Query and category__and

Tags: wordpress
Question!

Trying to display common posts from multiple post categories using WP_Query and category__and. Following is the query:

$query = array(
    'category__and' => array( 'cat-1', 'cat-2'),
    'posts_per_page' => 10,
    'paged' => $paged
    );

$cat_query = new WP_Query($query);

Now in the above case the posts are correctly fetched but the sticky posts are not displayed first.

Following code solves the problem but it doesn't perform "and" of the categories posts.

$query = array(
    'cat' => array( 'cat-1', 'cat-2'),
    'posts_per_page' => 10,
    'paged' => $paged
    );

The above query displays the sticky posts first but doesn't perform "and" on category posts.

Is there any way to satisfy the condition of sticky posts first and common posts from multiple categories?



Answers

you can use these parameters to display the sticky posts-

$query_sticky = array(
  'category__and' => array( 'cat-1', 'cat-2'),
  'posts_per_page' => 10,
  'post__in' => get_option( 'sticky_posts' ),
  'ignore_sticky_posts' => 1,
  'paged' => $paged
);
$query_sticky = new WP_Query($query_sticky);

Once you have these sticky posts you can merge them in the main query-

$query->posts = array_merge($query->posts, $query_sticky->posts);
$query->post = reset($query->posts);
$query->post_count += $query_sticky->post_count;
$query->found_posts += $query_sticky->found_posts;
$query->max_num_pages = $query->found_posts / $query->get('posts_per_page');

the variables like post_count etc. are required to make the wordpress loop work correctly.



This may help you

SELECT date,MIN(Starttime),MAX(Endtime) FROM your_table 
  WHERE CONCAT(date,' ',Starttime) >= CONCAT(?,' ',?) 
   AND CONCAT(date,' ',Starttime) < CONCAT(DATE_ADD(?,INTERVAL 1 DAY),' ',?) 
  GROUP BY date,HOUR(Starttime)

Give your input for '?' like below.

SELECT date,MIN(Starttime),MAX(Endtime) FROM your_table 
  WHERE CONCAT(date,' ',Starttime) >= CONCAT('2016-08-11',' ','06:30:00') 
   AND CONCAT(date,' ',Starttime) < CONCAT(DATE_ADD('2016-08-11',INTERVAL 1 DAY),' 06:30:00') 
  GROUP BY date,HOUR(Starttime)
By : Ponnarasu


There may be a chance of string value in the column RVU.MA. Try out with the below query to find out such descrepancies.

   SELECT *
   FROM RVU
   WHERE ISNUMERIC (RVU.MA)!=1


This video can help you solving your question :)
By: admin