To display conditional content on the front end of a WordPress site based on whether a user is logged in or not, you can use PHP code within your theme’s template files, widgets, or even within posts or pages using a custom shortcode.
You can easily display different content based on whether the user is logged in or not in WordPress. Make sure to place the code in appropriate places depending on where you want to display the conditional content.
If you are editing a theme’s template file (like header.php
, footer.php
, or footer.php
), you can use the following PHP code to check if a user is logged in:
<?php if ( is_user_logged_in() ) : ?> <!-- Content for logged-in users --> <?php else : ?> <!-- Content for visitors who are not logged in --> <?php endif; ?>
Using Conditional Tags in Widgets
If you want to conditionally display content in a widget, you might need to enable PHP in widgets first. This can be done by adding a code snippet to your theme’s functions.php
file:
function enable_php_in_widgets($widget_text) { if ( strpos($widget_text, '<?php' ) !== false ) { ob_start(); eval('?>' . $widget_text); $widget_text = ob_get_contents(); ob_end_clean(); } return $widget_text; } add_filter('widget_text', 'enable_php_in_widgets');
Then, you can use the same is_user_logged_in()
logic within a Text widget:
<?php if ( is_user_logged_in() ) : ?> <p>Exclusive content for logged-in users.</p> <?php else : ?> <p>General content for visitors.</p> <?php endif; ?>
Using a Shortcode in Posts or Pages
If you want to use this condition within posts or pages, you can create a custom shortcode by adding the following code to your functions.php
file:
function conditional_content_shortcode($atts, $content = null) { if ( is_user_logged_in() ) { return ' ' . do_shortcode($content) . ' '; } else { return ' Please log in to see this content. '; } } add_shortcode('conditional_content', 'conditional_content_shortcode');
You can then use this shortcode in your posts or pages like this:
[conditional_content] This content is only visible to logged-in users. [/conditional_content]
Using a Page Builder or Theme Builder
If you’re using a page builder like Elementor or Divi, you may be able to conditionally display content based on user login status using built-in features. For example, Elementor Pro allows you to set “Display Conditions” for sections or widgets, where you can choose “User Logged In” or “User Logged Out” as conditions.