Solution: 最终起作用的是添加
global $post;
在查询的顶部,所以之前
$custom_taxterms = ...
Bill Erickson\'s Genesis custom loop 是我最后遵循的模板。
Original question
我希望能在一个让我困惑的问题上得到一些帮助。
我有以下疑问。它工作并输出数据。
$custom_taxterms = wp_get_object_terms( $post->ID, \'region\', array(\'fields\' => \'ids\') );
// arguments
$args = array(
\'post_type\' => \'stay\',
\'post_status\' => \'publish\',
\'posts_per_page\' => 25, // you may edit this number
\'orderby\' => \'rand\',
\'tax_query\' => array(
array(
\'taxonomy\' => \'region\',
\'field\' => \'id\',
\'terms\' => $custom_taxterms
)
),
\'post__not_in\' => array ($post->ID),
);
$related_items = new WP_Query( $args );
// loop over query
if ($related_items->have_posts()) :
echo \'<ul>\';
while ( $related_items->have_posts() ) : $related_items->the_post();
?>
<li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
<?php
endwhile;
echo \'</ul>\';
endif;
// Reset Post Data
wp_reset_postdata();
如果我现在将其放入函数中,它将停止工作。
add_action( \'genesis_loop\', \'related_posts_cpt\' );
function related_posts_cpt (){
// same loop as above
}
需要明确的是,如果我对不同的输出使用相同的函数,它确实会起作用:
add_action( \'genesis_loop\', \'related_posts_cpt\' );
function related_posts_cpt() {
?>
<p>AAAAAAAAHHHHHH</p>
<?php
}
我错过了什么?提前谢谢你。
SO网友:rudtek
函数返回输出。你不想只是附和它。
尝试以下功能:
function mycoolquery() {
$custom_taxterms = wp_get_object_terms( $post->ID, \'region\', array(\'fields\' => \'ids\') );
// arguments
$args = array(
\'post_type\' => \'stay\',
\'post_status\' => \'publish\',
\'posts_per_page\' => 25, // you may edit this number
\'orderby\' => \'rand\',
\'tax_query\' => array(
array(
\'taxonomy\' => \'region\',
\'field\' => \'id\',
\'terms\' => $custom_taxterms
)
),
\'post__not_in\' => array ($post->ID),
);
$related_items = new WP_Query( $args );
// loop over query
if ($related_items->have_posts()) :
$output = \'<ul>\';
while ( $related_items->have_posts() ) : $related_items->the_post();
$output .= \'<li><a href="\'.the_permalink().\'">\'.the_title().\'</a></li>\';
endwhile;
$output .= \'</ul>\';
endif;
// Reset Post Data
wp_reset_postdata();
return $output;
}
然后在需要的位置回显函数:
echo mycoolquery();