Get current user id inside shortcode return ever 0

半城伤御伤魂 提交于 2021-02-11 03:44:05

问题


I'm trying to customize a shortcode put inside a custom plugin, but I can't get the user id, it always returns me 0.

It might also be okay to understand the role with current_user_can, but any information is always empty.

Here the code:

add_action( 'plugins_loaded', 'check_current_user' );

function check_current_user() {
// Your CODE with user data
global $current_user;
$current_user = wp_get_current_user();
return $current_user->ID;
}

function appp_hide_content_shortcode( $atts, $content = '' ) {
if( class_exists('AppPresser') && AppPresser::is_app() )
    return check_current_user();
else
    return $content;
}
add_shortcode('appp_hide_content', 'appp_hide_content_shortcode');

回答1:


Please try this

/**
* Hide content on app.
* 
* Use this shortcode to hide content when viewed using the app.
* 
* Use:
* [appp_hide_content]This content will not appear on the app.[/appp_hide_content]
*/
function appp_hide_content_shortcode( $atts, $content = '' ) {

ob_start();

    //GET CURRENT USER ID
    global $current_user;
    $current_user = wp_get_current_user();
    echo $current_user->ID;

    if (current_user_can('free')){
        if( class_exists('AppPresser') && AppPresser::is_app() )
            echo '';
        else
            echo $content;
     }

$sc_html = ob_get_contents();
ob_end_clean();


return $sc_html;
}

add_shortcode('appp_hide_content', 'appp_hide_content_shortcode');



回答2:


You need to check the user after the user is loaded. I would hook to init. You can't call the pluggable functions directly in a plugin without delaying the execution. The simpler solution to your problem would be to include your shortcode in your theme's functions.php, rather than in a plugin. But below will execute.

add_action( 'init', 'check_current_user' , 999);
function check_current_user() {
    // This returns current user id
    return get_current_user_id();
}

function appp_hide_content_shortcode( $atts, $content = '' ) {
if( class_exists('AppPresser') && AppPresser::is_app() ){
    // This is only returning an integer here.
    return check_current_user(); 
    }  else  {
    return $content;
    }
}
add_shortcode('appp_hide_content', 'appp_hide_content_shortcode');


来源:https://stackoverflow.com/questions/60683416/get-current-user-id-inside-shortcode-return-ever-0

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!