Last active
October 30, 2018 14:35
-
-
Save nfsarmento/8ff19aa75085e0fa0f216476d14ee849 to your computer and use it in GitHub Desktop.
Predefine category for new products - this function will add a category automatically when the user creates a Product
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* Predefine category for new products - this function will add a category automatically when the user creates a Product | |
* | |
* https://www.nuno-sarmento..com | |
*/ | |
add_action( 'save_post', 'ns_auto_add_product_category', 50, 3 ); | |
function ns_auto_add_product_category( $post_id, $post, $update ) { | |
if ( $post->post_type != 'product') return; // Only products | |
// If this is an autosave, our form has not been submitted, so we don't want to do anything. | |
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) | |
return $post_id; | |
// Check the user's permissions. | |
if ( ! current_user_can( 'edit_product', $post_id ) ) | |
return $post_id; | |
$term_id = 69; // <== Your targeted product category term ID | |
$taxonomy = 'product_cat'; // The taxonomy for Product category | |
// If the product has not "69" category id and if "69" category exist | |
if ( ! has_term( $term_id, 'product_cat', $post_id ) && term_exists( $term_id, $taxonomy ) ) | |
wp_set_post_terms( $post_id, $term_id, $taxonomy, true ); // we set this product category | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment