0

I am currently working on what can be described as a simple maintenance site, just so you understand the functionality I will explain it real quick. It makes use of woocommerce to buy blocks of time, once the purchase goes through, the amount is inserted into a custom table.

Now the idea is that when you create a post in the custom post type called clients you put the hours it took into a custom field called hours_taken and then once it is published it will run a function to upload the new number to the database.

I am trying to get it so it only carries it out once, so that updating the published post doesn't remove more hours.

I got the code below from another question on this site, with similar functionality, it didn't seem to work however. I added a die() in it in order to see whether the code was running on publishing, it didn't run the code however.

function edit_user_hours($post){
$post_id = $post->ID;
$customer_id = get_current_user_id();

if ( !get_post_meta( $post_id, 'firstpublish', $single = true ) ) {
  // ...run code once
    $get_table = $wpdb->get_results($wpdb->prepare("SELECT * FROM wp_woocommerce_userHours WHERE userId = %s LIMIT 1", $customer_id));
    $get_table = $get_table[0];
    $mykey_values = get_post_custom_values( 'hours_taken' );

    foreach ( $mykey_values as $key => $value ) {
        $hourBlock = $value - $get_table->hourBlocks;
    }

// Do something!
    $wpdb->query($wpdb->prepare("UPDATE wp_woocommerce_userHours SET userHours = userHours + $hourBlock WHERE userId = %s LIMIT 1",  $customer_id));
    die('Data inserted');
  update_post_meta( $post_id, 'firstpublish', true );
}
}
add_action( 'draft_to_published', 'get_user_hours' )

I

0

Take a look at Wordpress' Post Status Transitions hooks: https://codex.wordpress.org/Post_Status_Transitions

If you've added proper debugging (so that you die at the top of your hooked function) it sounds like you're not hooking into the right action.

Since you're adding some meta and checking for it to see if you should run again, you could hook into publish_custom-post-type. Also, the status may be confusing. I see you're trying draft, but that does not include new or auto-draft. Make sure you are confident about the previous status and the new status as well as the post_type.

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.