i am trying to assign multiple categories to my Custom Post Type using advanced custom field named 'cat'. But there is nothing saving to my categories. Any help?
<?php
// Add an action to run on post save
add_action( 'save_post', 'set_genre_on_save' );
function set_genre_on_save( $post_id ){
// Check the post type
if (is_single('hvm')) {
// Get the custom field data
$custom_field_data = get_post_custom( $post_id );
// Check if there is any category entered in the metabox
if (isset($custom_box_data['cat'])) {
// Save the data (separated by comma) into an array
$genre_array = explode( ',', $custom_box_data['cat'] );
//Set the array values to lower case
foreach ($genre_array as $genre){
$genre = strtolower($genre);
}
// Set the categories for these genres
wp_set_object_terms( $post_id, $genre_array, 'category' );
}
}
}
?>
i am trying to assign multiple categories to my Custom Post Type using advanced custom field named 'cat'. But there is nothing saving to my categories. Any help?
<?php
// Add an action to run on post save
add_action( 'save_post', 'set_genre_on_save' );
function set_genre_on_save( $post_id ){
// Check the post type
if (is_single('hvm')) {
// Get the custom field data
$custom_field_data = get_post_custom( $post_id );
// Check if there is any category entered in the metabox
if (isset($custom_box_data['cat'])) {
// Save the data (separated by comma) into an array
$genre_array = explode( ',', $custom_box_data['cat'] );
//Set the array values to lower case
foreach ($genre_array as $genre){
$genre = strtolower($genre);
}
// Set the categories for these genres
wp_set_object_terms( $post_id, $genre_array, 'category' );
}
}
}
?>
Share
Improve this question
asked May 28, 2019 at 9:58
DennisDennis
216 bronze badges
1 Answer
Reset to default 0You can not use is_single() conditional tag here.
You can check the type of post in the function this way:
add_action( 'save_post', 'set_genre_on_save', 20, 3 );
function set_genre_on_save( $post_id, $post, $update ) {
if ($post->post_type != 'hvm')
return;
// ...
}
You can also attach the function to the action hook save_post_{post_type}, which is triggered only for the {post_type}
type. Then there is no need to check the type of post inside the function.
add_action( 'save_post_hvm', 'set_genre_on_save', 20, 3 );