[英]How to detect if manual excerpt exists in WordPress?
我需要顯示不同長度的摘錄,所以我使用
function custom_excerpt($length) {
get_the_content();
... clean up and trim
return $excerpt;
}
但是,我想檢測是否輸入了手動摘錄以便使用該摘錄而不是自定義摘錄。 有沒有辦法做到這一點?
我嘗試使用
$wp_excerpt = get_the_excerpt();
但這會返回手動摘錄,如果手動摘錄為空,它將自動生成55個字符的摘錄,這無濟於事,因為它將始終為“ true”(無法檢查是否為空)。
之所以采用這種方式,是因為我在一個頁面上有多個摘錄(不同的長度),並且如果所需的長度比WordPress摘錄(55)長,我想展示我的摘錄, 除非編寫了手動摘錄,在這種情況下,我想證明這一點。
如果我能簡單地做到那將是完美的
if ( manual_excerpt() == true ) {
}
您只需要替換excerp_length wordpress默認函數,只需遵循上面的代碼,即可調用此自定義函數並設置長度:
<?php
// custom excerpt length
function custom_excerpt_length( $length = 20 ) {
return $length;
}
add_filter( 'excerpt_length', 'custom_excerpt_length', 999 );
?>
在函數內部使用:
<?php
function custom_excerpt( $length = 55 ) {
if( $post->post_excerpt ) {
$content = get_the_excerpt();
} else {
$content = get_the_content();
$content = wp_trim_words( $content , $length );
}
return $excerpt;
}
?>
檢查post對象中的post_excerpt
插槽是否為空:
global $post;
if( '' == $post->post_excerpt )
{
// this post does NOT have a manual excerpt
}
要將其轉換為功能:
function so19935351_has_manual_excerpt( $post )
{
if( '' == $post->post_excerpt )
return false;
return true;
}
這是一個老問題,但我一直在尋找這個問題,最終到這里了,在答案中沒有看到以下功能。 要知道帖子是否有自定義摘錄,可以使用has_excerpt函數:
<?php has_excerpt( $id ); ?>
其中$id
是帖子ID。 如果未指定,則將使用當前帖子ID。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.