-1

I'm having trouble with WooCommerce and Custom Post Type/Custom Fields.

I have an application where a new WooCommerce order automatically creates a new post (CPT = "audits"). The post has some custom fields, Order Number (pre-populated with the WooCommerce order number), and Status (drop down with 4 options).

My objective is when the Status of the post is changed to "Complete" (from "In Progress" or any other status), the WooCommerce order will automatically be changed to Completed.

Here is the code I am currently trying with no luck:

function my_change_status_function () {     
    global $post;
    $ordernumber = get_post_meta( $post->ID, 'order_number', true );
    $audit_status = get_post_meta( $post->ID, 'audit_status', true );    
    if ( $audit_status == 'Complete' ) {   
        return;
        $order = new WC_Order( $ordernumber );
        $order->update_status( 'completed' ); 
    }    
}
add_action( 'save_post_audits', 'my_change_status_function' );
  • Have you tried it without return;? – Gabriel Nov 2 '15 at 6:20
  • @Gabriel Would you like to add this comment as an answer? This post is currently coming up unanswered :) – Tim Malone Jul 10 '16 at 21:24
  • @Tim Malone - I added an answer, but this question should probably be closed as off-topic for a couple reasons. – Gabriel Jul 10 '16 at 21:47
  • @Gabriel Thanks! It's no longer marked as "unanswered" :) I thought about that, but it's using WP hooks rather than WC specific hooks, and even though the issue turned out to be a PHP one, I think it probably can still class as a WP question. – Tim Malone Jul 10 '16 at 21:49
  • @Gabriel Actually sorry no you're right - I skimmed over the code before and thought it was post_status. It is definitely more WC related. Ah well, I've flagged it as off topic, but at least it's answered now haha (I'm trying to deal with our massive unanswered lists atm!) – Tim Malone Jul 10 '16 at 21:51
2

Remove return; from your code, which is prematurely exiting the function before the following two lines can be executed; that is why the status is not changed.

function my_change_status_function () {     
    global $post;
    $ordernumber = get_post_meta( $post->ID, 'order_number', true );
    $audit_status = get_post_meta( $post->ID, 'audit_status', true );    
    if ( $audit_status == 'Complete' ) {   
        $order = new WC_Order( $ordernumber );
        $order->update_status( 'completed' ); 
    }    
}
add_action( 'save_post_audits', 'my_change_status_function' );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.