【问题标题】:Sum of custom field value from all posts所有帖子的自定义字段值的总和
【发布时间】:2020-03-05 12:54:10
【问题描述】:

我参考了前 QA Sum of all custom fields for category,并尝试了以下 2 个代码,但没有返回结果。有人知道这些代码有什么问题吗?

此代码返回 0。

<?php    
$args = array(
'posts_per_page' => -1,
'cat'  => '771',  
);
$wp_query->posts;
$total = 0;
foreach( $numbers as $numbersID ) {
$single = get_post_meta( $numbersID->ID, 'price', true );
$total += $single;
}
echo $total;
?>

此代码也返回 0。

<?php
$total = 0;
foreach( $wp_query->posts as $number ) {
$total += get_post_meta( $number->ID, 'price', true );
}
echo $total;
?>

【问题讨论】:

    标签: wordpress


    【解决方案1】:

    尝试强制get_post_meta返回的值并测试meta是否存在

    if ( metadata_exists( 'post', $number->ID, 'price' ) ) {
        $total += (int)get_post_meta( $number->ID, 'price', true );
    }
    

    【讨论】:

    • 感谢您的建议。看起来什么都没有返回。也许这意味着不存在元数据......谢谢。 @斯科
    猜你喜欢
    • 2018-12-24
    • 1970-01-01
    • 2011-03-09
    • 2015-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-12
    • 1970-01-01
    相关资源
    最近更新 更多