問題描述

當一個特定的帖子或頁面加載時,我需要運行一個函數。是否有任何鈎子讓我檢查在頁面加載期間是否顯示一條信息?

最佳解決方案

您可以使用 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 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。