single.php中的函数无法从自定义字段中获取正确的值

时间:2013-12-13 16:41:44

标签: php wordpress function

我想解决方案又是如此愚蠢容易,我很抱歉,我浪费你的时间来获得它。上周我遇到了同样功能的问题而且它对我没用,因为我没有将$ post设置为全局变量。我修复了它,一切都适用于category.php,但现在我想在我的wp-theme的single.php中调用相同的函数但是现在我遇到了同样的麻烦,就像第一次使用category.php那样的函数不要正确地使用自定义字段(ACF)开始计算。结果总是1

function averageit($posts){
global $post;
$total = 0;
$count = 0;
foreach($posts as $post)
{
    if(get_field('weight'))
    {
        $total += get_field('weight');
        $count++;
    }
}
$Average = $total / $count;
return $Average;

非常感谢您的帮助,并祝周末愉快。

更新

找到了single.php的解决方案,它与上面的完全不同......这里是:

$total = 0;
query_posts('category_name=' . get_option('featured-cat'));
    while (have_posts()) : the_post();
        $total += get_post_meta($post->ID, 'weight', true);
    endwhile;
echo '<p>'.$total.'</p>';

在另一个函数中分离后计数,有足够的可能性在网上找到。感谢您的支持!

1 个答案:

答案 0 :(得分:0)

你想要的是get_post_meta,codex:http://codex.wordpress.org/Function_Reference/get_post_meta

您的代码已修复:

function averageit($posts){
$total = 0;
$count = 0;
foreach($posts as $post)
{
$thisweight = get_post_meta($post->ID, 'weight', TRUE);
    if($thisweight )
    {
        $total += $thisweight;
        $count++;
    }
}
$Average = $total / $count;
return $Average;

一般提示:在检查之前存储该值,这样您就不必在需要时再次调用该函数。节省时钟周期=更有效的代码=节约能源。

问题:为什么在使用$ posts作为$ post覆盖它之前需要全局$ post?

另一个更新:没有抓住ACF(高级自定义字段)部分首先阅读。它们的函数get_field只是get_post_meta的包装器,所以从技术上讲它们都可以工作。