single.php中的函数没有从自定义字段获得正确的值 [英] Function in single.php doesn't get correct value from custom field

查看:171
本文介绍了single.php中的函数没有从自定义字段获得正确的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想这个解决方案又是如此的简单,而且我很抱歉,我浪费了时间。上周我遇到了同样的问题,它没有为我工作,因为我没有将$ post设置为全局变量。我解决了它,一切工作正常的category.php,但现在我想调用我的wp主题single.php相同的功能,但现在我有同样的麻烦,就像第一次与category.php功能请勿开始正确计算自定义字段(ACF)。结果总是1

I guess the solution is again so stupid easy and I'm sorry in advance that I waste your time with it gain. Last week I had trouble with the same function and it didn't worked for me because I didn't set $post as a global variable. I fixed it and everything works fine for the category.php but now I want to call the same function in single.php of my wp-theme but now I have the same trouble there like the first time with the category.php that the function don't start to calc with the custom fields (ACF) correctly. Result is always 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;

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

Thank you very much for your help in advance and have a nice weekend.

UPDATE

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

Found the solution for single.php and it was totally different to the one above... here it is:

$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>';

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

Seperated the post-count in another function, there were enough possibilities to find on the net. Thanks for your support!

推荐答案

您需要的是get_post_meta,codex: http://codex.wordpress.org/Function_Reference/get_post_meta

What you want is 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;

常规提示:在检查之前存储该值,以便您不必再次调用该函数你需要它。节省时钟周期=更高效的代码=节约能源。

General tip: store the value before checking it so you don't have to call the function again if you need it. Save clock cycles = more efficient code = conservation of energy.

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

Question: Why do you need to global $post before overwriting it with $posts as $post?

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

Another Update: Didn't catch the ACF (Advanced Custom Fields) part first read through. Their function get_field is just a wrapper for get_post_meta, so technically either will work.

这篇关于single.php中的函数没有从自定义字段获得正确的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆