• I’m creating a shortcode to promote affiliate products, and I’m using a simple shortcode template where I fill out the variables and returns the formatted HTML with the product information.

    My questions is how do I modify the shortcode so when one of the shortcode attribute is missing or does’t require a value the “return” doesn’t output empty html code for that part of the missing value?

    function create_buysingle_shortcode($atts) {
    
    	$atts = shortcode_atts(
    		array(
    			'img' => 'product_image',
    			'title' => 'product_title',
                            'affiliate' => 'product_link',
    			'action' => 'product_action',
    		),
    		$atts,
    		'buysingle'
    	);
    
      $img = $atts['img'];
      $title = $atts['title'];
      $affiliate = $atts['affiliate'];
      $action = $atts['action'];
      $upload_dir = wp_get_upload_dir();
      $description = $atts['description'];
    
        return '<div id="item"><div id="product-recommendation-card"><div id="product-recommendation-photo"><img src="' . $upload_dir['baseurl'] . '/' . $img . '"></div><div class="product-info-wrapper"><div id="product-recommendation-text">' 
          . $title . 
          '</div><div id="product-recommendation-description">' . $description . '</div><div id="product-recommendation-button"><a href="' 
          . $affliate . 
          '">' 
          . $action . 
          '</a></div></div></div></div>';
    
    }
    add_shortcode( 'buysingle', 'create_buysingle_shortcode' );
Viewing 1 replies (of 1 total)
  • You obviously have to add more logic.
    The array you pass to shortcode_atts should contain the default values. If the default is an empty string, you can check if it’s empty and not output it.
    The array should also be a list of all the allowed attributes. It looks like you are referring to description, which is not in the array, so it will never be set.

Viewing 1 replies (of 1 total)

The topic ‘How not to output content if missing value using shortcode’ is closed to new replies.