4
votes

I'm having a lot of trouble getting the product SKU for a product in a single product page inside of functions.php. I have multiple single product pages and I want different text to display depending on the product. I've created a child theme and I'm working in the functions.php file. I'm new to wordpress and editing themes so I don't quite understand the order of operations yet. I was able to get code working to loop through and give me all the SKU's for all the products but that's independent of the actual page that I'm on.

I've tried a bunch of things. The common solution seems to be:

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

but that doesn't work. For some reason the $product variable is null inside the functions.php script.

The loop that I have loops through all the product posts and gets the post ID. I also tried getting the ID of the current page but was also unsuccessful in doing that (the code below was copied from another site). Any help would be greatly appreciated. Thanks.

$full_product_list = array();
    $loop = new WP_Query( array( 'post_type' => array('product', 'product_variation'), 'posts_per_page' => -1 ) );

    while ( $loop->have_posts() ) : $loop->the_post();
        $theid = get_the_ID();
        $product = new WC_Product($theid);
1
What hook/template are you running your code on?helgatheviking
I created a child theme and I'm editing the functions.php script. I don't have an issue with the hooks into Woocommerce. My action looks something like: add_action( 'woocommerce_after_single_product_summary', 'wc_product_add_text', 35 );brad14

1 Answers

4
votes

get_sku() works just fine assuming that your theme has not removed woocommerce_after_single_product_summary for any reason.

add_action( 'woocommerce_after_single_product_summary', 'so_32545673_add_sku', 35 );
function so_32545673_add_sku(){
    global $product;
    if( $product->get_sku() ) {
        echo 'the sku = ' . $product->get_sku(); 
    }
}

I didn't see the output at first because it was below all the related products and upsells, etc.

Additionally you may want to switch to wc_get_product() instead of trying to call the class directly. With the following I get a list of product SKUs. You should use an if( $loop->have_posts() ) to open the <ul> but I'm being lazy.

$loop = new WP_Query( array( 'post_type' => array('product', 'product_variation'), 'posts_per_page' => -1 ) );

while ( $loop->have_posts() ) : $loop->the_post();
    $theid = get_the_ID();
    $product = wc_get_product($theid);

    if( $product->get_sku() ) echo '<li>' . $product->get_sku() . '</li>';
endwhile;