我想在Wordpress簡碼中使用下面的代碼,所以它可以像[推薦]一樣使用,我已經嘗試了很多次,並且慘敗失敗,想法將非常感謝:如何使用此代碼作爲短代碼
<div class="row cols3 testimonials">
<?php $postnum=1; query_posts('post_type=testimonial&showposts=3'); if (have_posts()) $post = $posts[0]; $c=0; while (have_posts()) : the_post();?>
<article class="col<?php if($postnum ==1){echo" first";}elseif($postnum==3){echo" last";}?>">
<p><?php echo get_the_content(); ?></p>
<div class="arrow"><div class="tri"></div></div>
<div class="name"><strong><?php global $post;$text = get_post_meta($post->ID, '_cmb_testominal_author', true);echo $text;?></strong> - <?php global $post;$text = get_post_meta($post->ID, '_cmb_testominal_company', true);echo $text;?></div>
</article>
<?php $postnum++; endwhile; wp_reset_postdata(); ?>
</div><!-- /Testimonials -->
* UPDATE *
下面的代碼工作,我真的不知道怎麼樣,雖然,我不能完全相信使用它,因爲我不明白它是如何工作的。任何幫助將是驚人的:
<?php
function testimonials_shortcode($atts, $content = null) {
$the_query = new WP_Query();
$the_query->query($atts);
if ($the_query->have_posts()) : while ($the_query->have_posts()) :
$the_query->the_post(); ob_start(); ?>
<div class="row cols3 testimonials">
<?php $postnum=1; query_posts('post_type=testimonial&showposts=3'); if (have_posts()) $post = $posts[0]; $c=0; while (have_posts()) : the_post();?>
<article class="col<?php if($postnum ==1){echo" first";}elseif($postnum==3){echo" last";}?>">
<p><?php echo get_the_content(); ?></p>
<div class="arrow"><div class="tri"></div></div>
<div class="name"><strong><?php global $post;$text = get_post_meta($post->ID, '_cmb_testominal_author', true);echo $text;?></strong> - <?php global $post;$text = get_post_meta($post->ID, '_cmb_testominal_company', true);echo $text;?></div>
</article>
<?php $postnum++; endwhile; wp_reset_postdata(); ?>
</div><!-- /Testimonials -->
<?php endwhile; endif; wp_reset_query();
$content = ob_get_contents(); ob_end_clean();
return $content;
}
add_shortcode('testimonials', 'testimonials_shortcode');
?>
在目前的形式下,這個問題可能應該遷移到WP.se. – vzwick 2012-08-13 22:34:44
要理解的最難的部分是'ob_start'等。這些函數使得PHP捕獲通常會輸出的代碼並將其收集到一個對象中,以便稍後「返回」。其餘的只是WordPress循環,用正確的方式編碼,而不是使用'query_posts',這是不好的。有關更多信息,請參閱WP_Query下的Codex。 – Foxinni 2012-08-13 23:15:05