我正试图弄清楚如何从我的主wp_query循环中获得当前post ID,以便在嵌套循环中工作。。
我在下面添加了我的循环,删除了大多数HTML,使其看起来更清晰。
我需要将嵌套循环中表示"$currentID=16;"的"16"替换为主循环中实际的当前post ID。
<?php $related_query = new WP_Query( 'post_type=post&posts_per_page=-1' ); ?>
<?php if( $related_query->have_posts() ): ?>
<?php while ( $related_query->have_posts() ) : $related_query->the_post(); ?>
<?php the_ID(); ?>
<?php the_time('F j, Y'); ?>
<?php the_category(); ?>
<?php echo get_edit_post_link(); ?>
<?php echo get_post_meta(get_the_ID(), 'cf_meta-desc', true); ?>
<?php echo get_post_meta(get_the_ID(), 'cf_xray', true); ?>
<?php the_tags(); ?>
<ul>
<h4>Recommended Articles</h4>
<?php
$related_cfs = get_post_meta( get_the_ID(), 'cf_related' );
foreach($related_cfs as $related_cf) {
echo '<li>';
echo '<span class="related-links__id"><a href="#post-' .$related_cf. '">' .$related_cf. '</a></span>';
echo '<span class="related-links__title"><a target="_blank" href="' .get_permalink($related_cf). '">' .get_the_title($related_cf). '</a></span>';
echo '<span class="related-links__edit"><a target="_blank" href="' .get_edit_post_link($related_cf). '">edit</a></span>';
echo '</li>';
} ?>
</ul>
<?php global $post;$backup=$post; //saves main query data before calling nested query ?>
<!-- BEGIN NESTED LOOP -->
<?php $referral_query = new WP_Query( 'meta_key=cf_related&posts_per_page=-1' ); ?>
<ol>
<h4 class="referring-links__header">Linkbacks (<?php
$meta_key = 'cf_related';
$currentID = 16;
$sql = "SELECT count(DISTINCT pm.post_id)
FROM $wpdb->postmeta pm
JOIN $wpdb->posts p ON (p.ID = pm.post_id)
WHERE pm.meta_key = '$meta_key'
AND pm.meta_value = '$currentID'
";
$count = $wpdb->get_var($sql);
echo "$count";
?>)
</h4>
<?php while ( $referral_query->have_posts() ) : $referral_query->the_post(); ?>
<?php
$currentID = 16;
$arrayCFrelated = get_post_custom_values('cf_related');
if (in_array($currentID, $arrayCFrelated))
{ ?>
<li>
<?php the_ID(); ?>
<?php the_title(); ?>
<?php echo get_edit_post_link(); ?>
</li>
<?php } ?>
<?php endwhile; ?>
</ol>
<!-- END NESTED LOOP -->
<?php $post=$backup; //brings back main query data before called nested query ?>
<?php echo get_post_meta(get_the_ID(), 'cf_img-feature', true); ?>
<?php endwhile; ?>
<?php else: ?>
<p class="center">Nothing found.</p>
<?php endif; ?>
<?php wp_reset_query(); ?>
您发布的代码很难阅读,因为它都是嵌套的,分布在打开和关闭php标记之间。
首先,您应该考虑熟悉函数和对象,作为将所有内容嵌套在同一个循环中的替代方案。这也将帮助其他与您一起工作的开发人员理解您的代码。
至于你的问题。尝试使用其他类型的循环来获取循环中的索引。例如:
for ($i1=0; $i1 < count($yourarray); $i1++) {
// ...
echo "index: $i1 <br />";
echo "value: {$yourarray[$i1]}";
}
或
foreach ($array AS $idx => $value) {
// ...
echo "index: $idx <br />";
echo "value: $value";
}
我知道这个问题很老,但我最近遇到了同样的问题。
如果您有一个主循环,并且希望获得要在嵌套的wp_query中使用的当前post的ID(或任何其他数据),那么请使用全局$post对象。
在嵌套wp_query中使用"get_the_id()"将返回嵌套wp_query中当前帖子的id,而不是主查询
示例:
$post_id = $post->ID;