I multiple custom post types and I would like to set a default category that can be set from one function through parameters. I initially did this for one custom post type and was hardcoded but I thought I'd make so we only have to output the function with parameters in case we ever decided to add more custom post types.
The problem is inside the function WordPress doesn't seem to link it's own hooks and functions and is returning invalid taxonomy errors when trying to set it via the wp_set_object_terms() function. When I have done this the WordPress way which would make you create a separate function for each post type and default term you want which I have put below.
function set_default_object_terms( $post_id, $post ) {
if ( 'publish' === $post->post_status && $post->post_type === 'comic' ) {
$defaults = array(
'story' => array( 'draft' )https://silentcomics.com
);
$taxonomies = get_object_taxonomies( $post->post_type );
foreach ( (array) $taxonomies as $taxonomy ) {
$terms = wp_get_post_terms( $post_id, $taxonomy );
if ( empty( $terms ) && array_key_exists( $taxonomy, $defaults ) ) {
wp_set_object_terms( $post_id, $defaults[$taxonomy], $taxonomy );
}
}
}
}
add_action( 'save_post', 'set_default_object_terms', 0, 2 );
What I am trying to achieve is something like below but none of WordPress' global variables are working or any wordpress function like get_object_taxonomies() or wp_set_object_terms() which are used in the example WordPress gives.
Below is a simplified version of what I am trying to achieve and the parameters I am trying to pass through is the cpt slug, the taxonomy slug and the id of the category I want to fallback to. I have also tried it with the variable $cat_id as an array.
function set_default_term( $cpt_slug, $taxonomy_slug, $term_id ) {
if ( isset( $_GET['post'] ) ) {
$post_id = intval( $_GET['post'] );
$post_type = get_post_type( $post_id );
$status = get_post_status( $post_id );
$cat_id = array( $term_id );
$cat_id = array_map( 'intval', $cat_id );
$cat_id = array_unique( $cat_id );
if ( $status === 'publish' && $post_type === $cpt_slug ) {
wp_set_object_terms( $post_id, $cat_id, $taxonomy_slug, true );
}
}
}
add_action( 'save_post', 'set_default_term', 20, 3 );
set_default_term('deployment-guides', 'deployment-guide-category', 98);
none of WordPress' global variables are working or any wordpress function
makes me think that you are trying to write this code as ajax handler in separate php file, and requesting this file directly from ajax. Am i right? If so you need to setup wp ajax handler in WP way and not as separate file with direct ajax call, because WP core isn't gets loaded if you do so, and wp functions are not accessible. – Mikhail.root