I'm new to shortcode and PHP. I'm creating a shortcode by following many tutorials such as this. Is the below safe and recommended to do when trying to add a long output conditional string in a shortcode? Or is there a better way?
function some_shortcode() {
if(/*condition*/) {
$return = "Something...";
}
$return .= "...interesting";
return $return;
}
CodePudding user response:
Solution 1
check for userid, in case not loggin in return "not logged in" after check your own condition and combine to a string
add_shortcode('yourShortcodeName', 'yourShortcodeFunction');
function yourShortcodeFunction(){
$user_id = get_current_user_id();
if(!$user_id || $user_id == 0){
return "not logged in";
}
$return = "";
if ( wp_is_application_passwords_available_for_user( $user_id ) || ! wp_is_application_passwords_supported() ) {
$return.= "Whatever";
}
$return.= " another value";
return $return;
}
Solution 2
check for userid, in case not loggin in return "not logged in" after check your own condition and combine to a array and implode to output string
add_shortcode('yourShortcodeName', 'yourShortcodeFunction');
function yourShortcodeFunction(){
$user_id = get_current_user_id();
if(!$user_id || $user_id == 0){
return "not logged in";
}
$return = [];
if ( wp_is_application_passwords_available_for_user( $user_id ) || ! wp_is_application_passwords_supported() ) {
$return[] = "Whatever";
}
$return[] = " another value";
return implode(' ' , $return);
}