Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/268.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
single.php中的函数不';无法从自定义字段获取正确的值_Php_Wordpress_Function - Fatal编程技术网

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

single.php中的函数不';无法从自定义字段获取正确的值,php,wordpress,function,Php,Wordpress,Function,我猜这个解决方案又是如此愚蠢简单,我事先很抱歉,我浪费了你的时间。上周,我在使用同一个函数时遇到了问题,但它对我不起作用,因为我没有将$post设置为全局变量。我修复了它,category.php的一切都很好,但是现在我想在wp主题的single.php中调用相同的函数,但是现在我遇到了与category.php相同的问题,就像第一次使用category.php时一样,函数没有正确地开始计算自定义字段(ACF)。结果总是1 function averageit($posts){ global $

我猜这个解决方案又是如此愚蠢简单,我事先很抱歉,我浪费了你的时间。上周,我在使用同一个函数时遇到了问题,但它对我不起作用,因为我没有将$post设置为全局变量。我修复了它,category.php的一切都很好,但是现在我想在wp主题的single.php中调用相同的函数,但是现在我遇到了与category.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>';
$total=0;
查询帖子('category\u name='。获取选项('featured-cat');
while(have_posts()):the_post();
$total+=get_post_meta($post->ID,'weight',true);
结束时;
回显“”.$total.“

”;

在另一个函数中分离帖子数量,就有足够的可能性在网上找到。谢谢你的支持

您想要的是获取post meta,codex:

您的代码已修复:

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;
一般提示:在检查之前存储该值,以便在需要时不必再次调用该函数。节省时钟周期=更高效的代码=节能

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


另一个更新:未捕获先通读的ACF(高级自定义字段)部分。他们的函数get\u字段只是get\u post\u meta的包装器,所以从技术上讲,两者都可以使用。

是否有理由使用
global$post除了允许在循环中覆盖全局$post变量??Hello Mark,如果没有越位测试wordpress,对我来说是不起作用的。所以请原谅,只是我的一个复制错误通过一个错误的来源。。。我仍然在学习每件事,也是一个好的组织。谢谢你的耐心。你好,乔恩,谢谢你的快速帮助。同样的问题。系统对“重量”值的变化作出反应,但计算错误。例如我的测试在一个类别中有3个帖子(计数),2个帖子的“权重”值为1,1个帖子的“权重”值为3(这$total的总和)。。。但平均结果仍然是1,不应该是5/3=1666。这太疯狂了,因为如果我在category.php中调用它,您的函数也会像我的第一个一样工作,但不会在我模板的single.php中工作。请原谅我使用testwise越位wordpress的php文件中的$global thing复制错误。