Set a custom field to all orders

Is there a way or hook to set this custom field to true for all orders in woocommerce?
Set a custom field to all orders

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

You can achieve this via the save_post hook as per the following example:

function wpse_374688_save_post( $post_id, $post, $update ) {
    // only update orders (post_type=shop_order)
    if ( 'shop_order' !== $post->post_type ) {
        return;
    }
 
    update_post_meta( $post_id, 'activecampaign_for_woocommerce_accepts_marketing', 1 );
}

add_action( 'save_post', 'wpse_374688_save_post', 10, 3 );

This callback will run each type a post_type of any kind is saved and or updated in some form. In the above example we check the post_type to ensure it is a shop_order, if not, we bail early.

If you want to ensure that all orders have this set to true (1) no matter whether saving or updating then you can leave the code as is. If you only want it to run on update then make use of the $update variable which will be true or false depending on whether this is the first save or a subsequent update.

As a tip you may want to check the status of the order and whether or not certain types of orders should have this value set to true (1) such as cancellations/refunds, but that is entirely at your discretion.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x