問題描述

當一個特定的帖子或頁面載入時,我需要執行一個函式。是否有任何鉤子讓我檢查在頁面載入期間是否顯示一條資訊?

最佳解決方案

您可以使用 wp 鉤子並檢查 global $wp_query 物件或任何條件。

add_action( 'wp', 'wpse69369_special_thingy' );
function wpse69369_special_thingy()
{
    if (
        'special_cpt' === get_post_type()
        AND is_singular()
    )
        return print "Yo World!";

    return printf(
        '<p>Nothing to see here! Check the object!<br /></p><pre>%s</pre>',
        var_export( $GLOBALS['wp_query'], true )
    );
}

次佳解決方案

使用 template_redirect,它是渲染模板之前觸發的動作鉤子;

add_action('template_redirect', 'hooker');
function hooker(){
    //I load just before selecting and rendering the template to screen
}

參考文獻

注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。