0

I'm not familiar with PHP and i met a problem to filter an object of array.

I have a function (get_post_meta_for_api) who return me an object of array but there're a lot of properties that i don't need ...

So i'd like to filter my object by key who contains "seopress"

function get_post_meta_for_api( $object ) {
    $post_id = $object['id'];
 
    return get_post_meta( $post_id );
}

Thanks in advance for your help :)

Stev0
  • 3
  • 2
  • Does this answer your question? [PHP: How to use array\_filter() to filter array keys?](https://stackoverflow.com/questions/4260086/php-how-to-use-array-filter-to-filter-array-keys) – El_Vanja Dec 22 '20 at 10:15
  • Thanks for your response. However it can be used for filter an array by key and not an object – Stev0 Dec 22 '20 at 10:17
  • I'm a bit lost now. `get_post_meta` returns an array. Do you want to keep the elements that have `seopress` present in any of the keys or do all elements have those keys, but you only want to eliminate the other non-seopress keys from the object? – El_Vanja Dec 22 '20 at 10:25
  • I added the response i wanna filter to my post. I'd like to keep only key who contains "seopress" :) – Stev0 Dec 22 '20 at 10:27

2 Answers2

0

Check get_post_meta for more information about how to use it.

get_post_meta comes with the option to retrieve a single meta value. Here's an example, using the meta value that you want to get.

get_post_meta($post_id, 'seopress', true);

The first argument is the post id, second is the meta key, third is if you want a single value. get_post_meta without true in the third argument will return an array containing the value, with true it will return the value as is.

Buttered_Toast
  • 901
  • 5
  • 13
  • Thanks for your response but i think it works with exact match. In my case, i need the key contains "seopress" and it don't be exact match with it – Stev0 Dec 22 '20 at 10:23
0

As per documentation, get_post_meta returns an array (https://developer.wordpress.org/reference/functions/get_post_meta/), this should work:

function get_post_meta_for_api( $object ) {

    return array_filter(
        get_post_meta($object['id']),
        function ($key) {
            return preg_match('/_seopress_*/', $key) === 1;
        },
        ARRAY_FILTER_USE_KEY
    );
}
Rico Leuthold
  • 1,975
  • 5
  • 34
  • 49