0

I am executing the following WP_Query on my mysql database:

$products = new WP_Query(array(
    'post_type' => 'posts',
    'meta_query' => array(
        array(
            'key' => 'meta_key',
            'compare' => '=',
            'value' => '_cegg_data_Amazon',
        ),
    ),
));

When I var_dump($product) I am receiving a long wp_Query object. However, I would only like to receive an object/list of the custom post fields. The below SQL query gives me exactly that back within phpmyadmin:

SELECT * FROM `wp_postmeta` where meta_key="_cegg_data_Amazon" ORDER BY `wp_postmeta`.`meta_key` ASC

Any suggestions how to get only the values of the custom fields _cegg_data_Amazon. I appreciate your replies!

1 Answer 1

1

I think the easiest way would be to loop through your WP_Query object and create your array (or new obj) with the desired field:

$products = new WP_Query(array(
    'post_type' => 'posts',
    'meta_query' => array(
        array(
            'key' => 'meta_key',
            'compare' => '=',
            'value' => '_cegg_data_Amazon',
        ),
    ),
));

$cegg_data = array(); // initiate the new array


if( $products->have_posts() ) : 

    while( $products->have_posts() ) : $products->the_post();

        $cegg_data[] = get_post_meta(get_the_ID(), '_cegg_data_Amazon', true); // populate array with the new value

    endwhile;

endif;

wp_reset_query();   

Now, if you var_dump "$cegg_data" it should contain an indexed array with the custom field values.

NB: the code is untested, just a quick draft ;)

Another and solution you can explore would be "posts_fields" filter documented here: https://developer.wordpress.org/reference/hooks/posts_fields/

Hope this helps and good luck ;)

Francesco

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.