2013-06-11 241 views
0

您好我對wordpress,php和所有這些編輯工具都很陌生。我想在用名稱「xxx」和值「(currentusername)」進行身份驗證時向wordpress添加一個新的cookie。我已經閱讀http://wptheming.com/2011/04/set-a-cookie-in-wordpress/。我將所需的代碼添加到我的代碼的functions.php中,但我不知道如何調用它,以便將當前用戶名登錄添加到cookie中。 在此先感謝將自定義Cookie添加到Wordpress

下面是我在我的functions.php插入

function set_newuser_cookie() { 
if (!isset($_COOKIE['sitename_newvisitor'])) { 
    setcookie('sitename_newvisitor', 1, time()+1209600, COOKIEPATH, COOKIE_DOMAIN, false); 
} 

} ADD_ACTION( '初始化', 'set_newuser_cookie')其他網站上的代碼;

回答

0

碰到這一個 - 我建議不要添加一個新的cookie,而是我會劫持(利用)當前的cookie,讓WP爲你管理它。此外,在WP可用的鉤子允許非常乾淨和嚴格的代碼中使用WP的功能 - 試試下面的代碼片段 - 我把意見和試圖要詳細:

function custom_set_newuser_cookie() { 
    // re: http://codex.wordpress.org/Function_Reference/get_currentuserinfo 
    if(!isset($_COOKIE)){ // cookie should be set, make sure 
     return false; 
    } 
    global $current_user; // gain scope 
    get_currentuserinfo(); // get info on the user 
    if (!$current_user->user_login){ // validate 
     return false; 
    } 
    setcookie('sitename_newvisitor', $current_user->user_login, time()+1209600, COOKIEPATH, COOKIE_DOMAIN, false); // change as needed 
} 
// http://codex.wordpress.org/Plugin_API/Action_Reference/wp_login 
add_action('wp_login', 'custom_set_newuser_cookie'); // will trigger on login w/creation of auth cookie 
/** 
To print this out 
if (isset($_COOKIE['sitename_newvisitor'])) echo 'Hello '.$_COOKIE['sitename_newvisitor'].', how are you?'; 
*/ 

是的,使用的functions.php此代碼。祝你好運。

相關問題