我在短代码方面遇到了一些麻烦,而且我在Wordpress(4.0)的主页上设置了一个特色图片。出于某种原因,当我在wp-admin>中粘贴我的短代码时页面>编辑>主页的内容,突然我的特色图像停止工作。它一直工作,直到我粘贴短代码并更新页面,但随后图像消失,the_post_thumbnail()返回false。我也试过get_the_post_thumbnail()但没有成功。
这里的代码摘自" front-page.php":
<div class="small-12 medium-6 columns">
<?php while ( have_posts() ) : the_post(); ?>
<h1><?php the_title(); ?></h1>
<?php the_content(); ?>
<?php endwhile; ?>
</div>
<div class="small-12 medium-6 columns">
<?php if (has_post_thumbnail()) {the_post_thumbnail();} ?>
</div>
这是来自&#34; functions.php&#34;的短代码功能:
// [random_testimonial]
function short_code_get_random_testimonial(){
$args = array( 'post_type' => 'testimonial', 'posts_per_page' => 1, 'orderby' => 'rand' );
$query = new WP_Query( $args );
while ( $query->have_posts() ) : $query->the_post();
$random_testimonial = get_the_content();
$author = get_the_title();
$rt = '<p class="quote">' . $random_testimonial;
$rt .= '</p><p class="right">– ' . $author . '</p>';
endwhile;
return $rt;
}
// Register the shortcodes.
add_shortcode( 'random_testimonial', 'short_code_get_random_testimonial' );
// Allow text widgets to contain shortcodes.
add_filter('widget_text', 'do_shortcode');
add_filter('the_content', 'do_shortcode');
非常感谢任何想法。
答案 0 :(得分:0)
我想我可能已经解决了这个问题。这似乎与我使用短代码调用自定义帖子类型的事实有关,因此在调用the_post_thumbnail()时,查询已更改为引用短代码中包含的自定义帖子类型(“testimonial” “)而不是父帖(在本例中是主页)。我修改了我的代码如下,以便在调用短代码之前捕获图像,并且所有代码都再次运行:
<div class="small-12 medium-6 columns">
<?php while ( have_posts() ) : the_post(); ?>
<?php
// go ahead and get the post image in case [random_testimonial]
// shortcode is used in page content which will break the query.
if (has_post_thumbnail()) {$image = get_the_post_thumbnail();} ?>
<h1><?php the_title(); ?></h1>
<?php the_content(); ?>
<?php endwhile; ?>
</div>
<div class="small-12 medium-6 columns">
<?php
// Echo post image from above.
if(isset($image)){echo $image;}
?>
</div>