PHP -显示附件标题,如果它为null,则显示帖子标题


PHP - Show attachment title, if it's null, show post title

我想实现下面代码的一个变体。这段代码当前显示一个帖子的附件标题。

我如何修改代码,所以如果没有附件,它显示的帖子标题。

这是提取第一个附件标题的代码。

<?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 } } ?>

像这样?

<?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();
        }
    }
}

最好的方法是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