使用 wordpress 仅查询自定义字段

Query only custom fields with wordpress

我正在我的 mysql 数据库上执行以下 WP_Query:

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

当我 var_dump($product) 收到一个很长的 wp_Query 对象。但是,我只想收到自定义 post 字段的 object/list。下面的 SQL 查询在 phpmyadmin 中准确地返回给我:

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

关于如何仅获取自定义字段的值的任何建议 _cegg_data_Amazon。感谢您的回复!

我认为最简单的方法是遍历您的 WP_Query 对象并创建具有所需字段的数组(或新对象):

$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();   

现在,如果您 var_dump "$cegg_data" 它应该包含一个带有自定义字段值的索引数组。

注意:代码未经测试,只是草稿 ;)

您可以探索的另一个解决方案是 "posts_fields" 过滤器,记录在此处:https://developer.wordpress.org/reference/hooks/posts_fields/

希望这对您有所帮助,祝您好运 ;)

弗朗切斯科