Mathias Beck
Mathias Beck

Reputation: 128

Display product data with custom shortcodes in Woocommerce single product pages

In Woocommerce, I use 3 different shortcode functions that are displaying:

My 3 function looks like this:

function display_woo_sku() {

    global $product;
    return $product->get_sku();

}
add_shortcode( 'woo_sku', 'display_woo_sku' );

function display_woo_farve() {

    global $product;
    return $product->get_attribute( 'farve' );

}
add_shortcode( 'woo_farve', 'display_woo_farve' );

function display_woo_style() {

    global $post, $product;
    $categ = $product->get_categories();
    return $categ;    

}
add_shortcode( 'woo_style', 'display_woo_style' );

This actually works, but throws errors when updating products and make issues with Facebook Pixel add ons.

I can't see What is wrong with my code, but there must be something wrong since it conflicting with plugins and third party pixel tools.

Any help is appreciated.

Upvotes: 1

Views: 3597

Answers (1)

LoicTheAztec
LoicTheAztec

Reputation: 254448

Your code is making some errors for many reasons… Try this instead:

function display_woo_sku() {
    if( ! is_admin() && ! is_product() ) return;

    global $post;

    // Get an instance of the WC_Product Object
    $product = wc_get_product( $post->ID );
    return $product->get_sku();
}
add_shortcode( 'woo_sku', 'display_woo_sku' );

function display_woo_attr_farve() {
    if( ! is_admin() && ! is_product() ) return;

    global $post;

    // Get an instance of the WC_Product Object
    $product = wc_get_product( $post->ID );
    return $product->get_attribute( 'farve' );
}
add_shortcode( 'woo_farve', 'display_woo_attr_farve' );

function display_woo_cats() {
    if( ! is_admin() && ! is_product() ) return;

    global $post;

    // $categ = $product->get_categories(); // <== <== <== <== IS DEPRECATED

    return wc_get_product_category_list( $post->ID );
}
add_shortcode( 'woo_cats', 'display_woo_cats' );

This code goes on function.php file of your active child theme (or theme). Tested and works.

It should solve your issue…

Upvotes: 1

Related Questions