php - How do I query related product post title instead of whole post object array the WordPress query?

one text

Solution:

You could do that by manipulating the sql "WHERE" clause.

  1. Create a custom function that does the filtering for you!
  2. Add the argument that our custom function is looking for
  3. Add the filter right before the custom WP_Query
  4. Remove the filter after WP_Query

  1. So you could write a the custom function in your functions.php like so:
function related_products_title_filter($where, $wp_query)
{
  global $wpdb;
  if ($searched_term = $wp_query->get('my_custom_search_filter_title')) {
    $where .= ' AND ' . $wpdb->posts . '.post_title LIKE \'%' . esc_sql(like_escape($searched_term)) . '%\'';
  }
  return $where;
}
  1. Add a custom argument to the arguments:
$knowledge_args = array(
  'my_custom_search_filter_title' => $product_search, // This is the custom argument that our function is looking for
  'post_type'                     => 'knowledge_hub',
  'fields'                        => 'ids',
  'posts_per_page'                => -1,
  'meta_query'                    => array(
    array(
      'key'       => $related_product,
      'value'     => $product_search,
      'compare'   => 'LIKE' 
    )
  )
);
  1. Add the filter right before the custom WP_Query:
add_filter('posts_where', 'related_products_title_filter', 10, 2);
  1. Remove the filter after WP_Query
remove_filter('posts_where', 'related_products_title_filter', 10, 2);

So your entire code would be something like this:

function related_products_title_filter($where, $wp_query)
{
  global $wpdb;
  if ($searched_term = $wp_query->get('my_custom_search_filter_title')) {
    $where .= ' AND ' . $wpdb->posts . '.post_title LIKE \'%' . esc_sql(like_escape($searched_term)) . '%\'';
  }
  return $where;
}

$product_search = sanitize_text_field($_GET['s']);
$related_product = get_field( 'related_products' );

$knowledge_args = array(
  'my_custom_search_filter_title' => $product_search,
  'post_type'                     => 'knowledge_hub',
  'fields'                        => 'ids',
  'posts_per_page'                => -1,
  'meta_query'                    => array(
    array(
      'key'       => $related_product,
      'value'     => $product_search,
      'compare'   => 'LIKE' 
    )
  )
);

add_filter('posts_where', 'related_products_title_filter', 10, 2);

$relatedProductArticles = new WP_Query($knowledge_args);

remove_filter('posts_where', 'related_products_title_filter', 10, 2);  

Let me know if you were able to get it to work!

Source