我想实现下面代码的变体。此代码目前显示帖子的附件标题。
如何修改代码,如果没有附件,则会显示帖子标题。?
这是用于提取第一个附件标题的代码。
<?php $args = array( 'post_type' => 'attachment', 'orderby' => 'menu_order', 'order' => 'ASC', 'post_mime_type' => 'image' ,'post_status' => null, 'numberposts' => 1, 'post_parent' => $post->ID );
$attachments = get_posts($args);
if ($attachments) {
foreach ( $attachments as $attachment ) {
$image_title = $attachment->post_title;?>
<?php echo $image_title; ?><?php } } ?>
答案 0 :(得分:0)
这样的东西?
<?php
$args = array( 'post_type' => 'attachment', 'orderby' => 'menu_order', 'order' => 'ASC', 'post_mime_type' => 'image' ,'post_status' => null, 'numberposts' => 1, 'post_parent' => $post->ID );
$attachments = get_posts($args);
if ($attachments) {
foreach ( $attachments as $attachment ) {
$image_title = $attachment->post_title;
if($image_title) {
echo $image_title;
} else {
the_title();
}
}
}
答案 1 :(得分:0)
执行此操作的最佳方法是empty()
函数和三元表达式
$image_title = ( ! empty( $attachment->post_title) )?
$attachment->post_title: // use the attachment title if it is not empty
$post->post_title; // otherwise use the post title