• 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?

Viewing 3 replies - 1 through 3 (of 3 total)
  • You only check the page input against the term ‘category’ but you don’t check if the category actually exists.

    get_category_by_slug returns false in case the category was not found. You should make a check against that before treating the return as an object. (Also checked if it really returned an object would be nice ( php: is_object() )

    Thread Starter mortalwombat

    (@mortalwombat)

    Hey thanks! So that helped me build in the fail-safe, so now it fails elegantly. I’m not sure how to check to make sure it returns an object though (or why it’s important for that matter), but I’d love to learn! 🙂

    As I said, easy in PHP, 🙂

Viewing 3 replies - 1 through 3 (of 3 total)

The topic ‘How to handle shortcode variables that are incorrect’ is closed to new replies.