我需要能夠在帖子標題中插入帖子的 ID。在標題出現的任何地方都應將 id 添加到標題中。它只應添加到具有帖子類型的帖子中post,而不應添加到頁面、自定義帖子類型等中。我已經設法做到這一點:function custom1_shortcode_func() { global $post; ob_start(); echo get_the_title($post->ID); echo " ("; echo get_the_ID(); echo ")" $output = ob_get_clean(); return $output;}add_shortcode('post-id', 'custom1_shortcode_func');在帖子中使用 [post-id] 時返回帖子標題和帖子 ID。但是我需要在我的整個網站上修改帖子標題,所以無論什么地方顯示帖子標題,它后面都會跟著“(post_id)”。我試過了,它確實在帖子標題前顯示了 post_id,但它改變了所有標題,包括菜單:add_filter('the_title', 'wpshout_filter_example');function wpshout_filter_example($title) { return get_the_ID().$title;}
1 回答

瀟湘沐
TA貢獻1816條經驗 獲得超6個贊
您的第二次嘗試已經接近尾聲,但您發現這對每個標題都有效。
您需要做的是先檢查帖子類型是否為 a post,如果是則只添加 id。
add_filter('the_title', 'add_id_to_title', 10, 2);
function add_id_to_title($title, $post_id) {
? ? //use the id to check the post type and only add the id if it has a type of "post"
? ? if(get_post_type($post_id) == "post")
? ? ? ? $title = $post_id.': '.$title;
? ? return $title;
}
這是做什么的:
過濾
the_title
器可以采用 2 個參數:標題(您正在使用的)以及帖子的 ID。使用 id,可以使用內置
get_post_type
函數找出帖子類型。然后我們可以檢查帖子類型是否是
post
,如果是我們將 id 添加到標題。
- 1 回答
- 0 關注
- 151 瀏覽
添加回答
舉報
0/150
提交
取消