wc_get_product in a none woocommerce page

Question

I am creating a new shortcode in which I want to show some details about a product in a review-like page.

If I got it right – I can only use wc_get_product if the current page is using the WooCommerce plugin. Since it’s a post page it does not includes the WooCommerce plugin and hence I can’t use the wc_get_product.

(Please currect me if I’m wrong – I’m here to learn 😀 )

Is there a way I can get a product details by it’s id on a page?

Thanks!

EDIT:

I am using this code as a shortcode with an attribute:

<?php

// Add custom Theme Functions here
// 

function gear_guide_product_view( $atts ) {
    $a = shortcode_atts( array(
        'id' => '0'
    ), $atts );
    echo var_dump(wc_get_product($a["id"]));
    wp_register_script( 'load_product_info' , '/wp-content/themes/theme-child/js/test.js' , array( 'jquery' ) );
    wp_enqueue_script( 'load_product_info' );
    wp_localize_script( 'load_product_info' , 'ids' , $atts);
}

add_action( 'woocommerce_loaded', 'my_function_with_wc_functions' );

add_shortcode( 'fsg' , 'gear_guide_product_view' );

This calls the js script:

function load_product_info() {
    jQuery.ajax({
        type: 'POST',
        url: '/wp-content/themes/theme-child/js/controllers/get_product_info.php',
        data: ids,
        dataType: 'json',
        success: function (data) {
            console.log(data);
        },
        error: function () {
            console.log("Failed to get data!");
        }
    });
}
load_product_info();

And that ajax function calls the following controller:

<?php
    if (isset($_POST["id"])) {
        $product_id = $_POST["id"];
        $product = wc_get_product($product_id);
        echo json_encode($product);
    } else {
        echo "Nothing to return!";
    }
?>
0
Omer 2 months 0 Answers 13 views 0

Leave an answer