skip to Main Content

I get an error from this function when we request this shortcode

function salex_func( $atts ){
   global $product;
if($product->is_on_sale()){
        echo '<span class="onsale soldout">';
    echo __( 'SALE!!!!', 'hello');
    echo '</span>';
}   
}
add_shortcode('saletex', 'salex_func');

2

Answers


  1. You can’t echo shortcode output. You have to return it.

    function salex_func( $atts ){
       global $product;
        if($product->is_on_sale()){
            $output = '<span class="onsale soldout">';
            $output .= __( 'SALE!!!!', 'hello');
            $output .= '</span>';
         }
        return $output;   
    }
    add_shortcode('saletex', 'salex_func');
    
    Login or Signup to reply.
  2. You don’t need to echo inside the shortcode function.

    You can try this code:

    function salex_func( $atts ){
        global $product;
        if($product->is_on_sale()){ 
            ob_start(); ?>
            <span class="onsale soldout"><?php __( 'SALE!!!!', 'hello'); ?></span>
            <?php return ob_get_clean();
        }   
    }
    add_shortcode('saletex', 'salex_func');
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search