Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WordPress use wildcard in get_posts

Tags:

php

wordpress

Is it possible to use a wildcard in the get_posts() function?

I have made the query I wanted in SQL already:

select * from wp_posts p
left join wp_postmeta pm on p.id = pm.post_id
where pm.meta_key like 'additional_downloads%' and pm.meta_value = 81 and p.post_status = "publish"

Which gives me the results I want.

Then I tried using to do that with the built-in get_posts() function in WordPress:

get_posts(array('meta_key' => 'additional_downloads%', 'meta_value' => 81))

But that gives me 0 results. The reason I need this wildcard is because a post can have more than 1 additional download, and those are stored in the wp_postmeta table with the meta_keys 'additional_downloads_0', 'additional_downloads_1' etc etc

Any idea how to do this using the wordpress functions?

like image 224
Danny Hobo Avatar asked Apr 20 '26 11:04

Danny Hobo


1 Answers

We can filter the WHERE clause of the query.

THE FILTER

add_filter( 'posts_where', function ( $where, \WP_Query $q )
{ 
    // Check for our custom query var
    if ( true !== $q->get( 'wildcard_on_key' ) )
        return $where;

    // Lets filter the clause
    $where = str_replace( 'meta_key =', 'meta_key LIKE', $where );

    return $where;
}, 10, 2 );

THE QUERY

$args = [
    'suppress_filters' => false,
    'wildcard_on_key' => true,
    'meta_query' = [
        [
            'key' => 'additional_downloads_%',
            'value' => 81
        ]
    ]
];
$q = get_posts( $args );
like image 109
Pieter Goosen Avatar answered Apr 23 '26 02:04

Pieter Goosen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!