I try to assign custom taxonomies to a page when newly added by the “publish” button.
This is the function:
function set_default_object_terms( $id, $post ) {
if ( 'publish' === $post->post_status ) {
log_me ('From inside function: '.__FUNCTION__.', while I pressed the "publish" button. Post-ID: '.$id);
$taxonomy_ar = get_terms( 'property-features', '' );
foreach ($taxonomy_ar as $taxonomy_term) {
log_me ('Inside the function: '.__FUNCTION__.' and inside the "foreach"-loop for the ID: '.$id.' and Term: '. $taxonomy_term->name . ' and Post-ID :'. $post->ID);
wp_set_object_terms( $post->ID, $taxonomy_ar, $taxonomy_term->name, true );
}
}}
and here is the hook:
add_action( 'save_post', 'set_default_object_terms', 100, 2 );
In the logfile which i added to figure out if i find all my values, all my custom taxonomies get found:
[13-May-12 16:28] be in function while "publish" is pressed with this id: **64**
[13-May-12 16:28] In the "foreach" with id: 64 and Term: **Kitchen** and Post-ID :**64**
[13-May-12 16:28] In the "foreach" with id: 64 and Term: **Stove** and Post-ID :**64**
[13-May-12 16:28] In the "foreach" with id: 64 and Term: **Pets ok** and Post-ID :**64**
But it does not assign it.
Does somebody know where the trick is?
You are using
wp_set_object_terms
wrong, the second parameter should be the term slug or id and the 3 parameter should be the taxonomy name, so try:and make sure you register the taxonomy for pages type using
register_taxonomy_for_object_type
ex:I’ve got a snippet that does this on load of the edit page, instead of on save. (So the user can see the selection before they hit publish, no surprise default terms being assigned on post_save).
I had a function changing the checkboxes to radio buttons already but it seemed like the appropriate place to also add
checked
to one of the inputs.Works on Add new, works on edit of an existing item.