minemind minemind - 1 month ago 14
PHP Question

Get WooCommerce product SKU in product pages meta box

I have a custom meta box in the backend of WooCommerce. Currently I have it setup to display some data from the single product page.

I've used

<?php the_title(); ?>
to display the title of the product and I've used
<?php the_field('myfield'); ?>
to display some content from an ACF field.

I really want to be able to display the SKU in this meta box as well, but everything I've tried breaks the page.

I tried adding
<?php echo $product->get_sku(); ?>
and it breaks the page. I've tried a bunch of other stuff to.

I just need to pass the value of the sku on the inventory tab to a meta box on the same admin page.

Can anyone else with this? Thanks.

Answer

You could try to insert a new metabox SKU field on general options product pages this way:

add_action( 'woocommerce_product_options_general_product_data', 'add_the_sku_to_general_product_field' );
function add_the_sku_to_general_product_field() {
    global $post;

    $product_sku = get_post_meta( $post->ID, '_sku', true );

    echo '<div class="options_group">';

    woocommerce_wp_text_input( array(
        'id'                => '_sku',
        'label'             => __( 'SKU', 'woocommerce' ),
        'placeholder'       => '',
        'description'       => __( 'Enter the SKU', 'woocommerce' )
    ) );

    echo '</div>';

}

// Saving the Custom Admin Field in general tab products pages when submitted
add_action( 'woocommerce_process_product_meta', 'save_the_sku_to_general_product_field' );
function save_the_sku_to_general_product_field( $post_id ){

    $wc_field = $_POST['_sku'];

    if( !empty($wc_field))
        update_post_meta( $post_id, '_sku', esc_attr( $wc_field ) );
}

Or alternatively just displaying the SKU…

enter image description here

With this code:

add_action( 'woocommerce_product_options_general_product_data', 'add_the_sku_to_general_product_field' );
function add_the_sku_to_general_product_field() {
    global $post;

    $product_sku = get_post_meta( $post->ID, '_sku', true );

    echo '<div class="options_group">';

    echo '<p class="form-field _sku_product "><label for="_sku_product">SKU: </label><span style="font-size:120%;">'.$product_sku.'</span></p>';

    echo '</div>';

}

As I don't use your plugin, I doesn't guaranty that this should work, but you should try it.

The Code goes in function.php file of your active child theme (or theme) or also in any plugin file.


References:

Comments