問題描述

我想執行自定義 jquery 代碼,如果他點擊一個按鈕並且他沒有登錄,那麼向用户顯示登錄對話框,我該怎麼做?

最佳解決方案

如果您想知道用户當前是否已登錄。其他答案檢查用户是否登錄,當頁面加載的時候,當您運行的 JavaScript 。例如,用户可以在單獨的選項卡中登錄

把它放在你的 javascript 中

var data = {
    action: 'is_user_logged_in'
};

jQuery.post(ajaxurl, data, function(response) {
    if(response == 'yes') {
        // user is logged in, do your stuff here
    } else {
        // user is not logged in, show login form here
    }
});

把它放在你的 functions.php 中

function ajax_check_user_logged_in() {
    echo is_user_logged_in()?'yes':'no';
    die();
}
add_action('wp_ajax_is_user_logged_in', 'ajax_check_user_logged_in');
add_action('wp_ajax_nopriv_is_user_logged_in', 'ajax_check_user_logged_in');

次佳解決方案

檢查 bodyclass 屬性:如果主題正在使用 body_class(),那麼主體對於已登錄的用户,有一個名為 logged-in 的類。請注意,該功能也可以在元素 html 上使用。

您也可以使用 is_user_logged_in()作為條件排隊或打印腳本。

第三種解決方案

請將 body_class() 添加到您的 HTML 體

<body <?php body_class(); ?>>
   //your html code
</body>

這將為記錄的用户添加 logged-in,然後您可以使用以下 jquery 代碼僅對登錄的用户執行自定義 juqery 代碼。

if ($('body').hasClass('logged-in')) {
       //execute your jquery code.
}

第四種方案

另一個例子,如果你想使用它來進行 AJAX 調用。

// Simplified... please note, that all names/vars/etc. in my class got unique names.
// ...the same goes for the script handler.
class wpse69814_example
{
    public $response;

    public function __construct()
    {
        add_action( 'wp_enqueue_scripts', array( $this, 'enqueue' ) );
        add_action( 'wp_enqueue_scripts', array( $this, 'localize' ), 20 );
    }

    public function enqueue()
    {
        wp_enqueue_script(
            'wpse69814_handler',
            plugins_url( 'url/to/file.js', __FILE__ ),
            array( 'jquery' ),
            filemtime( plugins_dir_path( __FILE__ ).'/path/to/file.js' ),
            true
        );
    }

    public function localize()
    {
        wp_localize_script( 'wpse69814_handler, 'wpse69814_object', array(
            'ajaxurl'    => admin_url( 'admin-ajax.php' ),
            'ajax_nonce' => wp_create_nonce( 'wpse69814_nonce' ),
            'action'     => 'wpse69814-handler-action',
            'data'       => array(
               'is_user_logged_in' => is_user_logged_in(),
            )
         )

    }
}

參考文獻

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