我有一个页面,根据当前用户调用事件标题。我将他们召集到一个表中,并将“积分”与每个事件关联起来。
该表将填充事件和信用。目前,在页面底部,我只是将每个活动的积分相加,但我想将所有相关活动的积分相加。有没有办法做到这一点?
$current_user = get_current_user_id();
?><h2>Completed Courses</h2><?php
$post_args = array(
\'post_type\' => \'tribe_events\',
// \'paged\' => $paged,
\'eventDisplay\' => \'past\',
// \'date_query\' => array( array( \'after\' => \'-1 year\' ) ),
// \'posts_per_page\' => 20,
// \'cat\' => \'7\',
\'tax_query\' => array(
array(
\'taxonomy\' => \'tribe_events_cat\',
\'field\' => \'slug\',
\'terms\' => \'business-skills-personal-and-commercial\',
),
),
\'meta_query\' => array(
array(
\'key\' => \'associated_people\',
\'value\' => $current_user,
\'compare\' => \'LIKE\'
)
)
);
$post_list = new wp_query( $post_args );
?>
<table style="width:100%">
<tr>
<td>Business Skills (Personal and Commercial)</td>
</tr>
<?php
if ( $post_list->have_posts() ) :
while( $post_list->have_posts() ) :
$post_list->the_post();
?>
<tr>
<td><?php the_title(); ?></td>
<td><?php the_field( \'cpd_credits\' ); ?></td>
<td>View Notes</td>
</tr>
<?php
endwhile;
else :
endif;
wp_reset_query();
?>
<tr>
<td>Total</td>
</tr>
</table>
<?php
$post_list = new wp_query( $post_args );
?>
<table style="width:100%">
<?php
if ( $post_list->have_posts() ) :
while( $post_list->have_posts() ) :
$post_list->the_post();
the_field( \'cpd_credits\' );
endwhile;
else :
endif;
wp_reset_query();
?>
<tr>
<td>Total</td>
</tr>
</table>
我试过了,但运气不好:
$post_list = new wp_query( $post_args );
?><table style="width:100%"><?php
if ( $post_list->have_posts() ) :
while( $post_list->have_posts() ) :
$post_list->the_post();
// First declare total and count before the loop
$total = 0;
$count = 0;
foreach( $posts as $post ) {
if ( get_field( \'cpd_credits\' ) ) {
// If we have a value add it to the total and count it
$total += get_field( \'cpd_credits\' );
$count++;
}
}
echo \'Count: \'. $count;
echo \'Total Sum: \'. $total;
endwhile;
else :
endif;
wp_reset_query();
SO网友:luukvhoudt
创建一个函数,遍历所有相关的帖子。迭代时,获取credit字段并将其添加到计数器变量中。你要做的最后一件事是返回计数器变量,它应该存储这些帖子的总信用额。
您的代码可能如下所示
in the file included before your view is included, e.g. functions.php
function get_total_credit($query_args) {
$total = 0;
$posts = get_posts($query_args);
foreach ($posts as $post) {
$total += get_field(\'credit\', $post->ID);
}
return $total;
}
in your view
print get_total_credit(array(\'post_type\'=>\'page\', ...));