基于Cookie存在的WordPress重定向

时间:2011-08-04 作者:Wok

我有一个棘手的情况。。。。我想看看有没有饼干。如果不存在,则重定向到内部wordpress页面,并设置cookie。然后继续浏览网站。但如果url不存在,我就会陷入循环。这就是我目前所拥有的。。。任何帮助都会很好。

function cookiebasedredirect() {

    // WHEN YOU HAVE FOUND YOUR COOKIE
    if ( !isset($_COOKIE["sevisitor"])) {

        setcookie(\'sevisitor\', 1, time()+1209600, "/", "http://localhost/child/", false);       

        // GRABS THE CURRENT PAGE NAME - THIS IS ALSO KNOWS AS THE PAGE/POST SLUG
        $pagename = get_query_var(\'pagename\');

        // PAGE CHECK SO THAT YOU ARE NOT IN AN INFINITE LOOP
        // IN THIS SAMPLE MEDIA-GALLERIES IS THE PAGE YOU WANT TO BE 
        //  REDIRECTED TO IF A COOKIE IS NOT SET, BUT ONCE YOU GET THERE
        // MAKE SURE WORDPRESS DOESN\'T EXECUTE THE REDIRECT
        if( $pagename != "about-myself") {          
            wp_redirect( get_site_url().\'/about-myself\' ); exit;

        } else {


        }


    } else {

    }}
add_action("template_redirect", "cookiebasedredirect");

2 个回复
最合适的回答,由SO网友:Bainternet 整理而成

为什么不使用init 行动挂钩:

function has_my_cookie()
{
    if (!is_admin()){
        //Check to see if our cookie is set if not redirect to your desired page and set the cookie
        if ( !isset($_COOKIE["sevisitor"])) {
            //setcookie
            setcookie(\'sevisitor\', 1, time()+1209600, "/", "http://localhost/child/", false);
             //Redirect 
            wp_redirect( get_site_url().\'/about-myself\' ); exit;
        }
    }
}
add_action(\'init\', \'has_my_cookie\');

SO网友:Wok

我的最终解决方案。。。

function cookie_redirect() {

    // THE PAGE SLUG, YOU WANT TO BE REDIRECTED TO, WHEN THERE IS NO COOKIE
    $pageslug = "about-myself";

    // THE COOKIE NAME
    $cookie_name = "thecookiemonster";

    // CHECK IF YOUR COOKIE IS SET
    if (!isset($_COOKIE[$cookie_name])) {

       // SINCE THERE IS NO COOKIE, THEN SET IT
       setcookie( $cookie_name, 1, time()+1209600, SITECOOKIEPATH, COOKIE_DOMAIN, false, true);

        // GRABS THE CURRENT PAGE NAME - THIS IS ALSO KNOWN AS THE PAGE/POST SLUG
        $pagename = get_query_var(\'pagename\');

        // MAKE SURE YOU ARE NOT AT THE PAGE YOU WANT TO BE DIRECTED TO, PREVENTS LOOP
        if( $pagename != $pageslug) {
            // REDIRECT US
            wp_redirect( get_site_url() . \'/\' . $pageslug ); exit;
        } else {

        }

    } else {


    }
}
add_action( \'init\', \'cookie_redirect\');

结束

相关推荐

Subdomain redirect problem

Wordpress已安装到我的根目录(/根/)。我有一个子域名(dammani.techbrij.com),我想从子域名访问主域名的一些文件。我做了以下事情:include_once(\'/root/wp-config.php\'); include_once(\'/root/wp-load.php\'); include_once(\'/root/wp-includes/wp-db.php\'); 现在,“http://techbrij.com/dammani“工作正常,但是”