我试图使用一个快捷码从自定义帖子类型调用一篇帖子,并将其显示在另一个页面的内容中。(基本上,我们有一个名为“推荐信”的自定义帖子类型,我们希望在每个页面上显示一个随机推荐信,但要在页面内容中显示。)我用过this tutorial 作为我的出发点。
这是我的代码:
function cd_random_testimonial($atts) {
// EXAMPLE USAGE:
//[loop the_query="showposts=1&post_type=testimonials&orderby=rand"]
// Defaults
extract(shortcode_atts(array(
"the_query" => \'\'
), $atts));
// de-funkify query
$the_query = preg_replace(\'~�*([0-9a-f]+);~ei\', \'chr(hexdec("\\\\1"))\', $the_query);
$the_query = preg_replace(\'~�*([0-9]+);~e\', \'chr(\\\\1)\', $the_query);
// query is made
query_posts($the_query);
// Reset and setup variables
$output = \'\';
// the loop
if (have_posts()) : while (have_posts()) : the_post();
$testimonial = the_content($post->ID);
$clientname = get_the_title($post->ID);
// output all findings - CUSTOMIZE TO YOUR LIKING
$output .= \'<blockquote><p class="quote">\';
$output .= get_the_content($post->ID);
$output .= \'</p><p class="right">~ \';
$output .= $clientname;
$output .= \'</p></blockquote>\';
endwhile; else:
$output .= \'nothing found.\';
endif;
wp_reset_query();
return $output;
}
add_shortcode("loop", "cd_random_testimonial");
它在输入短代码的地方工作正常,但它也在页面内容上方添加相同的内容。
我如何防止它发布额外的内容,而只是停留在它应该呆的地方?
谢谢
最合适的回答,由SO网友:Krzysiek Dróżdż 整理而成
您的代码中几乎没有错误。下面您可以看到它的外观:
function cd_random_testimonial($atts) {
// EXAMPLE USAGE:
// [loop the_query="showposts=1&post_type=testimonials&orderby=rand"]
// Defaults
extract(shortcode_atts(array(
\'the_query\' => \'\'
), $atts));
// de-funkify query
$the_query = preg_replace(\'~�*([0-9a-f]+);~ei\', \'chr(hexdec("\\\\1"))\', $the_query);
$the_query = preg_replace(\'~�*([0-9]+);~e\', \'chr(\\\\1)\', $the_query);
// query is made
$my_query = new WP_Query( $the_query ); // use custom WP_Query instead of query_posts
// Reset and setup variables
$output = \'\';
// the loop
if ( $my_query->have_posts() ) {
while ( $my_query->have_posts() ) {
$my_query->the_post();
// the_content outputs content and you want to return it; and it doesn\'t take post_id as argument... and you don\'t use this variable, so you can delete this line, I guess
// $testimonial = get_the_content();
$clientname = get_the_title(); // it doesn\'t take post_id as argument
// output all findings - CUSTOMIZE TO YOUR LIKING
$output .= \'<blockquote><p class="quote">\';
$output .= get_the_content(); // doesn\'t take argument
$output .= \'</p><p class="right">~ \';
$output .= $clientname;
$output .= \'</p></blockquote>\';
}
} else {
$output = \'nothing found.\';
}
wp_reset_postdata();
return $output;
}
add_shortcode("loop", "cd_random_testimonial");