How to handle shortcode variables that are incorrect
-
I am using building some custom shortcode that will create styled links to specific categories. However, I need to build a failsafe so that if the client puts a non-existent category name into the shortcode, things fail elegantly. Currently, they will use shortcode that looks like
[add_category category=photographer-renosparks]My function looks like
function add_category_function( $atts ) { if ($atts['category']) { $cat = $atts['category']; //Pull category name from shortcode variable in page $idObj = get_category_by_slug( $cat ); // Get the ID of the category (Includes Line Below) $category_id = $idObj->term_id; $cat_name = get_the_category_by_id( $category_id ); // Get the nice Name of the category based on it's ID $category_link = get_category_link( $category_id ); // Get the link to the category based on it's ID } else { $cat_name = "noThumb"; $category_link = '#'; } $wtf = get_bloginfo("template_url"); $slideshow_output = ''; $image = $wtf . '/images/categories/' . strtolower($cat_name) . '.jpg'; $slideshow_output.= '<div class="vendor_category_block"><div class="vendor_category_photo"><img src="' . $image . '" /></div><div class="vendor_category_title"><a href="' . $category_link . '" title="' . $cat_name . '" class="vendor_category_link">' . $cat_name . '</a></div></div>'; //create the HTML for the link. return $slideshow_output; } function register_shortcodes(){ add_shortcode('add_category', 'add_category_function');Currently, if they create code that doesn’t contain a legit category slug, I get the following error:
“Catchable fatal error: Object of class WP_Error could not be converted to string in /homepages/46/d188029515/htdocs/mattandjentry_root/otgb/wp-content/themes/otgb_1/functions.php on line 177”So there is a problem with my if statement. Clearly it’s not working. What would be a proper if statement to give this a failover?
The topic ‘How to handle shortcode variables that are incorrect’ is closed to new replies.