Combine relationship posts with existing wp_query

So I am building a query, and I wanted to see if someone can assist me on a special attempt to infuse two queries.

So here is what I’m attempting to do:

  1. Check if we have any relationship posts, which I can return either an array of IDs or an array of WP_Post objects.

  2. I want to showcase the relationship posts first if they are and then showcase the remaining wp_query posts.

Here is what I’m working with:


$  args = [     'post_type' => ['work', Report_Type::CPT_NAME],     'posts_per_page' => 4,     'post_status' => ['publish'], ]; $  query = new WP_Query($  args); 

Then I’m looping through using a template as shown below:

if ($  query->have_posts()) {     ob_start();     get_template_part('template-parts/blocks/work-expertise-filter/work-items-template', null, ['query' => $  query]);     $  content = ob_get_contents();     ob_end_clean();     wp_reset_postdata(); } 

So let’s say, that I have get_field('featured_posts') which returns back an ARRAY of IDs (I can check it to ARRAY of WP_Post objects if needed).
This is our return: array(2) { [0]=> int(14244) [1]=> int(14566) } array(4) {

So I attemped to do something like this:

    $  args = [         'post_type' => ['work', Report_Type::CPT_NAME],         'posts_per_page' => 4,         'post_status' => ['publish'],     ];     $  query = new WP_Query($  args);      $  all_ids = [];     if ($  query->have_posts()) {         while ($  query->have_posts()) {             $  query->the_post();             $  all_ids[] = array_merge($  query->post->ID, get_field('featured_posts'));         }         wp_reset_postdata();     }     $  all_ids = array_unique($  all_ids);     $  args = [         'post__in' => $  all_ids     ];     $  the_query = new WP_Query($  args); 

But I’m getting no response back, it’s basically: object(WP_Query)#1853 (50) { [“query”]=> array(1) { [“post__in”]=> array(1) { [0]=> NULL } } [“query_vars”]=> array(63) { [“post__in”]=> array(1) { [0]=> NULL }

If someone could help me with a query, it would be much appreciated!

How to use WP_Query without breaking the main Query

The WP Query class can be used to make almost any imaginable query to the WP database. It’s amazing.

But it’s also used when WordPress is loaded, to run the main query for the current page request.

A common practice is to use wp_reset_query() and/or wp_reset_postdata()

But it’s unclear when to use one or the other, or if they must be used at all. And I don’t want to use them just in case but only when they are really needed.

So I would like to know what is the correct way to use the power of WP Query without breaking the main query.

How I can change the condition or compare operator for WP_Query in pre_get_posts

So here is my problem I want to show Posts if have same category if not have post then show post of same tag. And to do that I am using "pre_get_posts" action. and setting query like following.

function related_custom_posts($  query){    $  query->set( 'category__in', array(2,3) );    $  query->set( 'tag__in', array(10,13) ); }  add_action( 'pre_get_posts', 'related_custom_posts', 1 ); 

But it create sql like this AND ( wp_term_relationships.term_taxonomy_id IN (2) AND tt1.term_taxonomy_id IN (11) ) but i need this with OR condition AND ( wp_term_relationships.term_taxonomy_id IN (2) OR tt1.term_taxonomy_id IN (11) )

Thanks in advance.

WP_Query: how to search tags in addition to a custom post type?

Below is what I have so far for a custom rest endpoint (‘placesdb/v1/search?term=’) for a custom post type (place). This successfully returns all the places that have the search term in the title or content. However, I also want to return all the tags (tag archive pages) that match the search term (the same result as calling the non-custom ‘/wp/v2/tags?search=’). Is it possible to somehow add the tag results to the place results? I already successfully did the front-end approach of calling the places and tags endpoints separately via ajax, but I would rather get all the data in one swoop. Hence my attempt at making this custom endpoint.

function placesSearch() {   register_rest_route('placesdb/v1', 'search', array(     'methods' => WP_REST_SERVER::READABLE,     'callback' => 'placesSearchResults'   )); } function placesSearchResults($  data) {   $  places = new WP_Query(array(     'post_type' => array('place'),     's' => sanitize_text_field($  data['term'])   ));    $  placesResults = array();    while($  places->have_posts()) {     $  places->the_post();     array_push($  placesResults, array(       'title' => get_the_title(),       'permalink' => get_the_permalink()     ));   }    return $  placesResults; } add_action('rest_api_init', 'placesSearch'); 

How to sort wordpress posts already selected by WP_QUERY

English is not my first language, sorry 🙂

I need differend per paginate page sorting.

For exemple, I created the loop:

 $  qargs = array(                     'posts_per_page' => 15,                     'no_found_rows'  => true,                     'order' => 'DESC',                     'post_type' => 'post',                     'suppress_filters' => false,                     'orderby' => 'post_views', // here I order my posts by views                     'fields' => '',                     'date_query' => array(                         array(                             'after'     => '-7 days',                             'column' => 'post_date',                         ),                     ), posts_query = new WP_Query( $  qargs ); 

And now I can display 15 selected posts sorted by views like this:

if ( $  posts_query->have_posts() ): ?>                 while ( $  posts_query->have_posts() ):                     $  posts_query->the_post(); ....... 

But I need to select 15 most viewed posts and after that to sort them by date.

Is it possible?

Thank you!

Problem with wp_query in Safari

The Query for my custom post type works well for most browsers, but there’s a problem loading the images in Safari for MAC (not iphone), the may appear at first sight but they dissapear constantly


I have modified the Query several times to reduce the quantity of elements charging (the problem seems to be worse when there are more custom post types being shown).

WP_Query Results Issue with ACF

I have the following query set up

$  argsar = array ( 'numberposts'   => 1, 'post_type' => 'auctionroom', 'meta_key'  => 'auctionroom_username', 'compare' => '=', 'value'   => $  auctionroomname ); $  the_queryar = new WP_Query($  argsar); if ($  the_queryar->have_posts()) { $  causercheck = $  the_queryar->found_posts; $  the_queryar->the_post(); $  auctionroom_id = get_the_ID(); } 

It should only return 1 result but it is returning the total number of auctionroom posts when I get

$ causercheck = $ the_queryar->found_posts;

Having numberposts or not gives the same incorrect total

Thanks in anticipation for any clues

Running WordPress Version: 5.5.1 with ACF Version: 5.9.1

filter default wp_query to show just selected level of child pages in wordpress

I’m working on a site that has a fairly large page structure a few levels deep – in some sections there are a lot of pages.

So I want to have functionality if user choose on select box level 1 then only pages in level 1 will show in below list of pages. if he choose level 2 then only level 2 pages, same go to level 3 level 4 level 5 level 6.

it’s working for top level parent pages when I set query_vars[‘post_parent’] = 0; and I want to have same functionality to show list of level 1 child page,level 2 child pages and so on…

I am stuck on it. please I will be great full if anyone can help me for it. Thanks see screenshot link

function level_page_admin_posts_filter( $  query ) {   global $  pagenow;   if ( is_admin() && $  pagenow == 'edit.php' && !empty($  _GET['lavel_pages'])) {       $  level = $  _GET['lavel_pages'];       if($  level == 'parent'){         $  query->query_vars['post_parent'] = 0;       }else        if($  level == 1){                }else       if($  level == 2){        }   } } add_filter( 'parse_query', 'level_page_admin_posts_filter' );  function admin_page_filter_level_pages() {   global $  wpdb;   if (isset($  _GET['post_type']) && $  _GET['post_type'] == 'page') {   $  sql = "SELECT ID, post_title FROM ".$  wpdb->posts." WHERE post_type = 'page' AND post_parent = 0 AND post_status = 'publish' ORDER BY post_title";   $  parent_pages = $  wpdb->get_results($  sql, OBJECT_K);   $  select = '     <select name="lavel_pages">       <option value="parent">Parent Pages</option>       <option value="1">Level 1</option>       <option value="2">Level 2</option>       <option value="3">Level 3</option>       <option value="4">Level 4</option>       ';      $  select .= ' </select>';   echo $  select; } else {   return; } } add_action( 'restrict_manage_posts', 'admin_page_filter_level_pages' ); 

can I extend the WP_Query class to deal with ‘duplicate’ posts created by joining to wp_posts?

Based on the premise that one big database requests is better than many smaller ones, I’ve modified WP_Query for my custom post type ‘word’ and joined three tables to it. The resulting query looks more or less like this and works well.

SELECT wp_posts.*, verbs.*, nouns.*, definitions.* FROM wp_posts   LEFT JOIN verbs ON ( wp_posts.ID = verbs.word_id )   LEFT JOIN nouns ON ( wp_posts.ID = nouns.word_id )   LEFT JOIN definitions ON ( wp_posts.ID = definitions.word_id )   WHERE 1=1   AND wp_posts.post_type = 'word'  AND (wp_posts.post_status = 'publish' OR [...] )   ORDER BY wp_posts.post_title ASC  

I of course now have duplicate posts for each of the words’ respective definitions and I am rolling them back up into one post per word with an array of definitions instead.

But because these results are used in different ways all around the website, I’m having to write similar logic time and time again. Here, for example, I am using the data in an AJAX response.

    $  query = new WP_Query( $  args );      $  posts = $  query->get_posts();      if ( $  query->post_count ) > 0 )     {         $  prev_word = null;         foreach ( $  posts as $  key => &$  row )          {             if ( !property_exists( $  row, 'definitions' ) ) $  row->{'definitions'} = array();              $  definition = array(                 'definition_id' => $  row->definition_id,                 'definition' => $  row->definition,                 'note' => $  row->note,             );              if ( is_object( $  prev_word ) )             {                 if ( $  prev_word->post_id == $  row->post_id )                 {                     // update the previously inserted row                     $  prev_word->definitions[] = $  definition;                      // remove the current row                     unset( $  row );                      continue;                 }             }              $  row->definitions[] = $  definition;             $  prev_word = $  row;         }     }      echo json_encode( array_values( $  posts ) );     die();  

What I would like to do now is extend the WP_Query class to have this done automatically on construction.

class Words_Query extends WP_Query {     function __construct( $  args = array() )     {         $  args = array_merge( $  args, array(             'post_type' => 'word'         ) );          parent::__construct( $  args );          [insert magic here?]     }      public $  definitions = array(); } 

I don’t have any experience with OOP though so I am asking for some help/guidance. Is something like this possible?

Will I have to update a bunch of other properties to reflect the changes…? Like $ post_count

What other things might I need to be aware of?