简体   繁体   中英

Wordpress: Display different content based on loged in user

I'm running a simple wordpress site where there is a possibility for users to log in. I'm now at a point where I want to display different HTML content based on the currently logged in user.

I know that this can be solved by using PHP and I even have a basic knowledge in using PHP but I just don't know where and how to start.

Thanks for every input and best regards

It is quite simple to do this, once you get to know your way around PHP. You can use this by using shortcodes (which, in HTML, you can call with do_shortcode term) so you will be able to use it with shortcodes and in HTML if needed.

You will first have to register a shortcode first. As you said, you only want a different HTML content for logged in users. To create a shortcode open your functions.php file and copy/paste this code:

add_shortcode('EXAMPLE','show_user_content');
function show_user_content($atts,$content = null){
global $post;
if (!is_user_logged_in()){
return "You aren’t allowed to read this. " . wp_login_url( get_permalink($post->ID) ) . ' to view the content';
}
return $content;
}

You can edit the part which returns the error if someone, who isn't logged, wants to view the content and also the EXAMPLE part in the first row - that is the name of your shortcode, so make it unique. This won't go by roles (admin, mod, editor etc) but by the state if someone is logged in.

After that just use [EXAMPLE] Some content [/EXAMPLE] in your post editor. Be aware that you have to use the text editor of the post, not the visual editor (as it doesn't recognize shortcodes).

If you want to implement this in HTML, just use the do_shortcode function:

<?php echo do_shortcode('[EXAMPLE]Hello world![/EXAMPLE]'); ?>

And just put content inside the 'Hello world!' part.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM