2014-07-18 34 views
0

我想實現下面的代碼的變體。此代碼目前顯示帖子的附件標題。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;?> 
<?php echo $image_title; ?><?php } } ?> 

回答

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

謝謝你的最佳途徑。這是我想要的。 – Recofa

+0

沒問題,樂於幫忙。 – mattcouchman

+0

@Recofa - 如果這是正確的答案,請標記爲正確。 –

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 
+0

剛剛測試過這個代碼,它就像我想要的那樣工作。但爲什麼它是最好的方式?其他代碼與其他代碼一起工作,從技術方面來看,這種方式更優化?無論如何,謝謝 – Recofa

+0

這是執行變量賦值的最簡潔的方式,可以讓您稍後使用該值,而無需在代碼中稍後運行if/else。 – doublesharp

+0

我在不同的網站上檢查過它,不幸的是這並不如我所希望的那樣工作。如果附件不存在,它不會顯示帖子標題。 (只有當它沒有標題集時)如何改變它以使其工作? – Recofa