0

I currently have a WooCommerce site with the WooCommerce Subscriptions plugin. I am trying to add post meta when creating a new subscription order via the dashboard and am having trouble getting the meta to save when the subscription is still pending.

I need the value to save only when a couple of conditions are met:

  • First only when the post is created via the WordPress dashboard and not via the shopping cart system on the front end.
  • Second only when the meta does not already exist, only for new posts
  • This needs to happen even when the post is still pending

This is what I currently have:

add_action( 'added_post_meta', 'shop_sync_on_shop_subscription_save', 10, 4 );
add_action( 'updated_post_meta', 'shop_sync_on_shop_subscription_save', 10, 4 );
function shop_sync_on_shop_subscription_save( $meta_id, $post_id, $meta_key, $meta_value ) {
        if ( $meta_key == '_edit_lock' ) { // we've been editing the post
            if ( get_post_type( $post_id ) == 'shop_subscription' ) { // we've been editing a subscription
                $remaining_issues = get_post_meta($post_id, '_remaining_issues');

                if ($remaining_issues == "") {  // we only want to update to the default 6 if this has not already been set
                  update_post_meta($post_id, '_remaining_issues', '6');
                }
            }
        }
    }
0

get_post_meta() without the third parameter will return an empty array if the key isn't found, so it looks like your check on $remaining_issues will fail every time.

Try

$remaining_issues = get_post_meta($post_id, '_remaining_issues',true);

if ($remaining_issues === false) {  // we only want to update to the default 6 if this has not already been set
              update_post_meta($post_id, '_remaining_issues', '6');
}

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.