我正在尝试在 Wordpress 中为画廊显示当前选择的特色图片 - 如果没有选择特色图片,我希望它选择画廊中的第一张图片并使用该图片。我写了以下内容,它只返回 else 语句中的图像。换句话说,如果我选择了特色图像,则不会显示任何图像。如果我告诉 php 在 if 语句中回显 $image_img_tag 的内容,它会返回图像。但由于某种原因,它不会在 if/else 语句之外显示该图像。我假设 $image_img_tag 的值不是从 if/else 语句中得出的,但不知道为什么。有什么想法吗?
<?php
if ( has_post_thumbnail() ) :
$featuredID = get_post_thumbnail_id();
$image_img_tag = wp_get_attachment_image( $featuredID, 'featured-image');
else :
$images = get_children( array( 'post_parent' => $post->ID, 'post_type' => 'attachment', 'post_mime_type' => 'image', 'orderby' => 'menu_order', 'order' => 'ASC', 'numberposts' => 999 ) );
if ( $images ) :
$total_images = count( $images );
$image = array_shift( $images );
$image_img_tag = wp_get_attachment_image( $image->ID, 'featured-image');
endif;
?>
<figure class="alignright gallery-thumb">
<a href="<?php the_permalink(); ?>"><?php echo $image_img_tag; ?></a>
</figure><!-- .alignright .gallery-thumb -->
这是该区域的完整代码,包括所有 ifs/endifs。这可能有助于解释问题。
<?php if ( is_search() ) : // Only display Excerpts for search pages ?>
<div class="entry-summary">
<?php the_excerpt(); ?>
</div><!-- .entry-summary -->
<?php else : ?>
<div class="entry-content">
<?php if ( post_password_required() ) : ?>
<?php the_content( __( 'Continue reading <span class="meta-nav">→</span>', 'matthewbarker' ) ); ?>
<?php else : ?>
<?php
if ( has_post_thumbnail() ) :
//the_post_thumbnail('featured-image',array('class'=>'alignright'));
$featuredID = get_post_thumbnail_id();
$image_img_tag = wp_get_attachment_image( $featuredID, 'featured-image');
else :
$images = get_children( array( 'post_parent' => $post->ID, 'post_type' => 'attachment', 'post_mime_type' => 'image', 'orderby' => 'menu_order', 'order' => 'ASC', 'numberposts' => 999 ) );
if ( $images ) :
$total_images = count( $images );
$image = array_shift( $images );
$image_img_tag = wp_get_attachment_image( $image->ID, 'featured-image');
endif;
?>
<figure class="alignright gallery-thumb">
<a href="<?php the_permalink(); ?>"><?php echo $image_img_tag; ?></a>
</figure><!-- .alignright .gallery-thumb -->
<p><em><?php printf( _n( 'This gallery contains <a %1$s>%2$s photo</a>.', 'This gallery contains <a %1$s>%2$s photos</a>.', $total_images, 'matthewbarker' ),
'href="' . esc_url( get_permalink() ) . '" title="' . sprintf( esc_attr__( 'Permalink to %s', 'matthewbarker' ), the_title_attribute( 'echo=0' ) ) . '" rel="bookmark"',
number_format_i18n( $total_images )
); ?></em></p>
<?php endif; ?>
<?php the_excerpt(); ?>
<?php endif; ?>
<?php wp_link_pages( array( 'before' => '<div class="page-link"><span>' . __( 'Pages:', 'matthewbarker' ) . '</span>', 'after' => '</div>' ) ); ?>