1

I'm trying to make WooCommerce automatically add some attributes to a product when it's created.

I'm trying to find the right hook to start with, so far the only one that seems correct is 'woocommerce_api_create_product' but it doesn't work and the WooCommerce help site actually goes to a 404 not found page for that hook.

I'm trying to get this code to execute:

if ( $new_status == "auto-draft" && isset( $post->post_type ) && $post->post_type == 'product' ){

    // do stuff here
        $defaults = array ( 'pa_color' => array (
                                      'name' => 'pa_color',
                                      'value' => '',
                                      'position' => 1,
                                      'is_visible' => 1,
                                      'is_variation' => 1,
                                      'is_taxonomy' => 1,
                                   ),
                            'pa_capacity' => array (
                                      'name' => 'pa_capacity',
                                      'value' => '',
                                      'position' => 2,
                                      'is_visible' => 1,
                                      'is_variation' => 1,
                                      'is_taxonomy' => 1,
                                   )
        );

    update_post_meta( $post->ID , '_product_attributes', $defaults );

}
  • Please, show the complete callback. I assume it's post status transition? – kaiser Nov 17 '15 at 9:32
1
add_action( 'save_post_product', 'create_product', 10 );
function create_product( $post_id, $post) {   
    // $post_id and $post are required
    if ( empty( $post_id ) || empty( $post ) ) {
        return;
    }

    // Dont' save meta boxes for revisions or autosaves
    if ( defined( 'DOING_AUTOSAVE' ) || is_int( wp_is_post_revision( $post ) ) || is_int( wp_is_post_autosave( $post ) ) ) {
        return;
    }

    // Check the nonce
    if ( empty( $_POST['woocommerce_meta_nonce'] ) || ! wp_verify_nonce( $_POST['woocommerce_meta_nonce'], 'woocommerce_save_data' ) ) {
        return;
    }

    // Check the post being saved == the $post_id to prevent triggering this call for other save_post events
    if ( empty( $_POST['post_ID'] ) || $_POST['post_ID'] != $post_id ) {
        return;
    }

    // Check user has permission to edit
    if ( ! current_user_can( 'edit_post', $post_id ) ) {
        return;
    }

    //Only if this is a new published product
    if ($post->post_date != $post->post_modified) {
        return;
    }

    // do stuff here...
}
| improve this answer | |

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.