Skip to content

Instantly share code, notes, and snippets.

@skmohammadi
Last active Aug 1, 2021
Embed
What would you like to do?
Search Post Title OR Meta with WP_Query
/// page.php
$args = array(
'post_type' => 'product',
'post_status' => 'publish',
'_meta_or_title' => 'سامسونگ',
'meta_query' => array(
array(
'key' => 'brand',
'value' => 'سامسونگ',
'compare' => 'LIKE',
),
),
);
$query = new WP_Query($args);
///
/// functions.php
///
add_action( 'pre_get_posts', function( $q ) {
if ( $title = $q->get( '_meta_or_title' ) )
{
add_filter( 'get_meta_sql', function( $sql ) use ( $title )
{
global $wpdb;
// Only run once:
static $nr = 0;
if( 0 != $nr++ ) return $sql;
// Modified WHERE
$sql['where'] = sprintf(
" AND ( %s OR %s ) ",
$wpdb->prepare( "{$wpdb->posts}.post_title like '%%%s%%'", $title),
mb_substr( $sql['where'], 5, mb_strlen( $sql['where'] ) )
);
return $sql;
});
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment