Support » Fixing WordPress » display error message when return is empty

  • Hi so I am usng this snippet for a custom shortcode to display a users submitted events in their buddypress profile

    function custom_shortcode(){
         $user_id = bp_displayed_user_id();
         return do_shortcode( '[eo_events author='.$user_id.']' );
    }
    add_shortcode( 'eo_custom_shortcode', 'custom_shortcode' );

    I am very new to php and trying to learn. I would like to add an if statement to display some text like “sorry no events yet” when the shortcode returns no events. How do I do this as I dont know what the return type of a shortcode is…

    Thanks

Viewing 5 replies - 1 through 5 (of 5 total)
  • Moderator keesiemeijer

    (@keesiemeijer)

    Try it with this:

    function custom_shortcode() {
    	$user_id = bp_displayed_user_id();
    	$events = do_shortcode( '[eo_events author='.$user_id.']' );
    
    	if ( empty( $events ) ) {
    		$events = "sorry no events yet";
    	}
    
    	return $events;
    }
    add_shortcode( 'eo_custom_shortcode', 'custom_shortcode' );

    Thread Starter lfeddern

    (@lfeddern)

    Thanks for the reply. Still displays when there is an event but the if statement doesn’t seem to be working as the error message is not showing when there are no events.

    Is there something that I need to add in order to display text when the variable $events is returned as text?

    Thread Starter lfeddern

    (@lfeddern)

    when i try !empty() I get the error message displayed for all profiles though. Even those without events. So I guess for some reason even when the shortcode returns no events it must return somehing

    Thread Starter lfeddern

    (@lfeddern)

    (and hence not be empty) if there another function that would work? I tried to look and tried is_null but also didnt work

    Moderator keesiemeijer

    (@keesiemeijer)

    Try this to see what it returns.

    function custom_shortcode() {
    	$user_id = bp_displayed_user_id();
    	$events = do_shortcode( '[eo_events author='.$user_id.']' );
    
    	// Print the the $events value
    	echo '<pre>';
    	var_dump ($events );
    	echo '</pre>';
    
    	if ( empty( $events ) ) {
    		$events = "sorry no events yet";
    	}
    
    	return $events;
    }
    add_shortcode( 'eo_custom_shortcode', 'custom_shortcode' );
Viewing 5 replies - 1 through 5 (of 5 total)
  • The topic ‘display error message when return is empty’ is closed to new replies.