Internet Solutions

PHP

Adding or Editing Products in WooCommerce via XML-RPC

I was recently tasked with connecting an external inventory control system with WooCommerce. In this environment, the ICS is the main repository and WooCommerce is just a customer portal.

After researching the WooCommerce API, I quickly found that it only supports read access for the most part. I then tried connecting through the Jetpack REST API but that had it’s own set of issues and design limitations.

[ Edit: Woocommerce has updated their REST API since this article was written and it now appears to support most post functions. ]

Finally, I decided on the standard WordPress XML-RPC API. It may be less secure, but at least it works and since it only has to accept data from a single source, a firewall rule will help with security.

Here are some quick notes that caused me some difficulty in an otherwise simple setup.

Custom fields (meta fields) are stored in an array of arrays when preparing the data to send.

$custom_fields = array(
                array('key' => '_sku', 'value' => '001abc'),
                array('key' => '_price', 'value' => '1000')
            )

 

Any meta fields starting with an underscore are considered protected and can not be edited through XMLRPC without changing some default behavior.

 You can add this code to your functions.php or plugin as needed:

 

function _meta_sanitize_cb ( $meta_value, $meta_key, $meta_type ) {
    return $meta_value;
}
	
function _meta_yes_you_can( $can, $key, $post_id, $user_id, $cap, $caps ) {
    return true;
}

function test_register_meta() {
    register_meta( 'post', '_sku', '_meta_sanitize_cb', '_meta_yes_you_can');
    register_meta( 'post', '_price', '_meta_sanitize_cb', '_meta_yes_you_can');
}
add_action( 'init', 'test_register_meta' );

 

Remove NULL or empty values from a PHP array

I found this simple code while searching. To remove emtpy ( “” ) values and NULL values:

$new_array_without_nulls =($array_with_nulls);

To remove only NULL values but ignore empty strings, etc:

$new_array_without_nulls = array_filter($array_with_nulls, 'strlen');

Credit goes to Brian Cray for the original post.