Home » Php » wordpress – Add shortcode and div into PHP output to new shortcode

wordpress – Add shortcode and div into PHP output to new shortcode

Posted by: admin February 25, 2020 Leave a comment

Questions:

This is the current HTML but I’d like to create a shortcode to display it all…

<div class="widget" sp-sku="sku-value-goes-here"></div> 

I setup a shortcode that get the SKU

function wc_get_product_sku() { 
    global $product;
    echo $product->get_sku();
add_shortcode('product_sku', 'wc_get_product_sku'); 

But I’d like a new shortcode to output the entire div with the shortcode or sku in the div class.

How to&Answers:

Go ahead and give the WordPress Shortcode documentation a glance. The shortcode you have now is improper. WordPress Shortcodes are supposed to return a value, not echo or otherwise output it. If you see echo statements in a shortcode function, generally they have Output Buffering enabled, and then return the final value. (you also have a syntax error)

The following would be the proper way to implement your current function:

add_shortcode('product_sku', 'wc_get_product_sku'); 
function wc_get_product_sku() { 
    global $product;

    return $product->get_sku();
}

If you want to output the HTML, just include that in the return value. If you want another function:

add_shortcode( 'product_sku_div', 'wc_product_sku_div'); 
function wc_product_sku_div() { 
    global $product;

    return sprintf( '<div class="widget" sp-sku="%s"></div>', $product->get_sku() );
}

Alternatively, you could add them to the same function and use shortcode attributes to determine whether to output the whole HTML or just the SKU, something like this:

add_shortcode( 'wc_get_product_sku', 'wc_get_product_sku_function'); 
function wc_get_product_sku_function( $atts ) { 
    global $product;
    $sku = $product->get_sku();

    extract( shortcode_atts( array(
        'wrap' => false,
    ), $atts, 'wc_get_product_sku' ) );

    return ($wrap == true) ? sprintf( '<div class="widget" sp-sku="%s"></div>', $sku ) : $sku;
}

This would like you use [wc_get_product_sku] or [wc_get_product_sku wrap="false"] to get just the sku, and [wc_get_product_sku wrap="true"] to get the whole HTML.

Edit: to check the sku, just wrap the return statement in an if/else:

add_shortcode( 'product_sku_div', 'wc_product_sku_div'); 
function wc_product_sku_div() { 
    global $product;

    if( $product && !empty( $product->get_sku() ) ){
        return sprintf( '<div class="widget" sp-sku="%s"></div>', $product->get_sku() );    
    } else {
        return '<div>NO SKU FOUND</div>';
    }
}