Sessions in word press

时间:2013-12-26 作者:Kiren S

是否可以在wordpress中设置会话。如果是,你能告诉我怎么做吗?我的示例代码是。

<?php
session_start();

if(!isset($_SESSION[\'impression\'])) {
    $_SESSION[\'impression\'] = 100;  
}else {
    if($_SESSION[\'impression\']<=0)
        $_SESSION[\'impression\'] = 100;
}

echo $_SESSION[\'impression\']    = $_SESSION[\'impression\'] -1;

?>

2 个回复
SO网友:Shazzad

注意,会话必须在发送标头之前启动。所以你应该试试-

<?php
if( !session_id() ){
    if( headers_sent() ){
        die(\'headers already sent, cant start session\');
    }
    else{
        session_start();
    }
}

// check existence, or not below 1
if( !isset($_SESSION[\'impression\']) || $_SESSION[\'impression\'] < 1 ){
    $_SESSION[\'impression\'] = 100;  
}

// decrease the value by one
$_SESSION[\'impression\']--;

// test
echo $_SESSION[\'impression\'];
?>

SO网友:Akshay Paghdar

您不能使用$_SESSION 在wordpress中。。。因为$_SESSION 被wordpress禁用。。。

您可以签入“wp includes/load.php”

/**
 * Turn register globals off.
 *
 * @access private
 * @since 2.1.0
 * @return null Will return null if register_globals PHP directive was disabled
 */
function wp_unregister_GLOBALS() {
    if ( !ini_get( \'register_globals\' ) )
        return;

    if ( isset( $_REQUEST[\'GLOBALS\'] ) )
        die( \'GLOBALS overwrite attempt detected\' );

    // Variables that shouldn\'t be unset
    $no_unset = array( \'GLOBALS\', \'_GET\', \'_POST\', \'_COOKIE\', \'_REQUEST\', \'_SERVER\', \'_ENV\', \'_FILES\', \'table_prefix\' );

    $input = array_merge( $_GET, $_POST, $_COOKIE, $_SERVER, $_ENV, $_FILES, isset( $_SESSION ) && is_array( $_SESSION ) ? $_SESSION : array() );
    foreach ( $input as $k => $v )
        if ( !in_array( $k, $no_unset ) && isset( $GLOBALS[$k] ) ) {
            unset( $GLOBALS[$k] );
        }
}
所以如果你想使用$_SESSION, 您可能需要使用插件。有几个插件允许wordpress使用$_SESSION.

结束