I am setting a taxonomy based on the post_status. It works as needed except I want to allow the taxonomy to be overridden if a particular taxonomy is selected.
Here is the code
function add_categories_automatically($postID) {
if(get_post_status($postID) == 'draft'){
$catsID = array(1); //active
wp_set_post_categories($postID, $catsID);
}
if(get_post_status($postID) == 'publish'){
$catsID = array(5); //complete
wp_set_post_categories($postID, $catsID);
}
if(get_post_status($postID) == 'publish' && has_category( 'billed' ) ){
$catsID = array(16); //billed
wp_set_post_categories($postID, $catsID);
}
}
add_action('save_post', 'add_categories_automatically');
On the last if statement I have tried to use && to set a new category if the post is published AND the category billed is selected. It just keeps being set as id 5 from the previous if statement.
Any ideas on how I can make the last if statement work?
I am setting a taxonomy based on the post_status. It works as needed except I want to allow the taxonomy to be overridden if a particular taxonomy is selected.
Here is the code
function add_categories_automatically($postID) {
if(get_post_status($postID) == 'draft'){
$catsID = array(1); //active
wp_set_post_categories($postID, $catsID);
}
if(get_post_status($postID) == 'publish'){
$catsID = array(5); //complete
wp_set_post_categories($postID, $catsID);
}
if(get_post_status($postID) == 'publish' && has_category( 'billed' ) ){
$catsID = array(16); //billed
wp_set_post_categories($postID, $catsID);
}
}
add_action('save_post', 'add_categories_automatically');
On the last if statement I have tried to use && to set a new category if the post is published AND the category billed is selected. It just keeps being set as id 5 from the previous if statement.
Any ideas on how I can make the last if statement work?
Share Improve this question edited Feb 23, 2022 at 1:58 Nik asked Feb 22, 2022 at 17:29 NikNik 951 silver badge13 bronze badges 4 |1 Answer
Reset to default 2This is what works with the help of WebElaine above. I had to pass the postID to has_category()
and then set variables.
function add_categories_automatically($postID) {
$p_published = get_post_status($postID) == 'publish';
$p_draft = get_post_status($postID) == 'draft';
$p_cat = has_category( 'billed', $postID);
if ($p_draft == 'draft'){
$catsID = array(1); //active
wp_set_post_categories($postID, $catsID);
}
if ($p_published == 'publish'){
$catsID = array(5); //complete
wp_set_post_categories($postID, $catsID);
}
if($p_published == 'publish' && $p_cat ){
$catsID = array(16); //billed
wp_set_post_categories($postID, $catsID);
}
}
add_action('save_post', 'add_categories_automatically');
has_category()
check since you're not in the loop. – WebElaine Commented Feb 22, 2022 at 21:30has_category( 'billed' )
tohas_category( 'billed', $postID )
. – WebElaine Commented Feb 23, 2022 at 13:37