Function in single.php doesn't get correct val

2019-08-31 01:49发布

问题:

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

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!

回答1:

What you want is get_post_meta, codex: http://codex.wordpress.org/Function_Reference/get_post_meta

Your code fixed:

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.

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

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.