Woocommerce hooks usage in a non-theme php file

662 Views Asked by At

I am working on a woocommerce integrated wordpress installation.

I created a standalone "SearchByNumber.php" file and put it into the path: /wp-content/plugins/ajax-test

Normally it is not a real plugin (I am not familiar with writing a plugin). It is cURLing a web service and getting results in an xml.

What I want to do is to loop SKUs from this xml and to get their IDs, prices, stocks, etc from woocommerce.

I tried a lot, but everytime I get different errors: class not found, method not found, null object, etc.

global $product;
// a lot codes curling, looping, etc...
$product_id = $product->get_product_id_by_sku($sku_from_xml);
$product = wc_get_product($product_id);
$sku = $product->get_sku();
// or
$price = $product->get_price();

I am trying to find the ID of product via SKU, then to get from product whatever I want.

PS: I use these $product->get_sku() $product->get_attribute('Brand') in the php snippets in the product pages. They work well there.

how to hook, filter, class ?? What am I doing wrong?

I would appreciate for your any kind of help.

Many thanks,

Murat

1

There are 1 best solutions below

4
On BEST ANSWER

You can't access any function or class unless you load the Wordpress.

so if you want to load Wordpress from standalone script, you need to do the following:

<?php
require '../../../wp-load.php'; //Load WordPress



$product_id = wc_get_product_id_by_sku( 'test' ); //get the product id

if ( $product_id ) {
    $product = wc_get_product( $product_id ); //get the product
    $price   = $product->get_price(); //get the price
    echo $price;
}

but i strongly recommend to load your script as plugin for better security, and in order to do that first just rename your file to follow Wordpress Standard for example ajax-test.php and then add the following code example to your script

<?php
/*
Plugin Name: Ajax Test
*/
defined( 'ABSPATH' ) or die( 'No script kiddies please!' ); //Security Check block direct access to your plugin PHP files 



add_action( 'init', 'function_name' );

function function_name() {
    $product_id = wc_get_product_id_by_sku( 'test' ); //get the product id

    if ( $product_id ) {
        $product = wc_get_product( $product_id ); //get the product

        $price = $product->get_price(); //get the price
        echo $price;
    }
}

then go to you Wordpress backend and activate the plugin.

both way now you have access to all WordPress and Woocommerce hooks

you can check the WordPress Plugin Reference at the following link:

Reference