Created
March 12, 2019 20:24
-
-
Save savyounts/7b6afcd3c1e2ddc3b68f9d5a33b93b2f to your computer and use it in GitHub Desktop.
Set default taxonomies to custom post types in WordPress
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
Usually for normal posts, if a user doesn't select a custom category then it defaults to 'uncategorized', with custom post_types | |
that isn't always the case. If you want to have your custom post_type default on a certain taxonomy you can add this function | |
to your functions.php file in your template directory. | |
/** | |
* Set default cat for cpt | |
* @source {https://circlecube.com/says/2013/01/set-default-terms-for-your-custom-taxonomy-default/} | |
* @source {http://wordpress.mfields.org/2010/set-default-terms-for-your-custom-taxonomies-in-wordpress-3-0/} | |
* @license GPLv2 | |
*/ | |
function set_default_object_terms_203962( $post_id, $post ) { | |
if ( 'publish' === $post->post_status && $post->post_type === 'your_post_type' ) { | |
$defaults = array( | |
//'your_taxonomy_id' => array( 'your_term_slug', 'your_term_slug' ) | |
'post_tag' => array( 'taco', 'banana' ), | |
'monkey-faces' => array( 'see-no-evil' ), | |
); | |
$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_203962', 100, 2 ); | |
Here you just need to replace 'your_post_type' with the type of custom post you want to set the default on and then switch out | |
'your_taxonomy_id' and 'your_term_slug' with the property values. You can find these by going to that taxonomy in your WordPress | |
(so if I'm wanting a category, I'd click on my categories link in my side bar) then you can look in your url to find the | |
taxonomy id, which is probably just the name of it. Then you slug should be in one of the columns under your individual | |
taxonomy types. | |
After you have saved this, it won't work on posts already created, but will work on any new posts from then on out. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://wordpress.stackexchange.com/questions/203962/set-a-default-category-if-the-user-didnt-select-one-before-creating-a-post
https://circlecube.com/says/2013/01/set-default-terms-for-your-custom-taxonomy-default/