0

There are my arguments for my custom WP_Query.

$args = array(
    'post_type' => 'post',
    'posts_per_page' => '9',
    'name'=>'Products',
    'compare'=>'LIKE'
);
$the_query = new WP_Query( $args );
echo $the_query->request;

which returns the following query:

SELECT wp_posts.* 
FROM wp_posts 
WHERE 1=1 
    AND wp_posts.post_name = 'products' 
    AND wp_posts.post_type = 'post' 
ORDER BY wp_posts.post_date DESC 

As I can see, this is not creating a LIKE query like I'd like to have one.

1
  • 1
    What are you trying to accomplish? The compare parameter can be used in meta/date queries? Check out the WP_Query docs.
    – birgire
    Oct 28, 2013 at 12:55

1 Answer 1

1

What you're trying to achieve is a LIKE query. But you're using the compare arguments that are only present for meta_query arguments. You need to utilize a filter like the following:

add_filter( 'posts_where', 'wpse120358TitleLike', 10, 2 );
function wpse120358TitleLike( $where, &$wp_query )
{
    global $wpdb;
    if (
        'post' === $wp_query->get( 'post_type' )
        AND $wp_query->get( 'name' )
        // add further restriction arguments here:
        // AND ...
        )
    {
        $where .= $wpdb->prepare(
            ' AND %s LIKE %s',
            "{$wpdb->posts}.post_title",
            '%'.like_escape( $wp_query->get( 'name' ) ).'%'
        );
    }

    return $where;
}

Note that this is not a tested script. It's meant as a guideline that can be built upon.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.