Updated Answer:
You’re trying to mix a lot of things that you don’t understand, by using the $args
in wp_get_post_terms
you don’t need to run the foreach
to hunt for child terms (is your custom taxonomy even hierarchical anyway?). As a catch-all you can just implode
the whole list and get the same result (but without seeing/knowing your schema I can’t be sure it’s actually what you want.)
<?php
add_action('save_post', 'update_term_title');
function update_term_title($post_id) {
if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return;
if (!current_user_can('edit_post', $post_id)) return;
$names = wp_get_post_terms($post_id, 'name', array('fields' => 'names'));
// $names == array( 0 => 'name1'[, 1 => 'name2'[, 2 => ...]])
$bands = wp_get_post_terms($post_id, 'band', array('fields' => 'names'));
// $bands == array( 0 => 'band1'[, 1 => 'band2'[, 2 => ...]])
// collapse parent and child terms
$name = implode(' ', $names);
// $name == "name1[ name2[ ...]]"
$band = implode(' ', $bands);
// $band == "band1[ band2[ ...]]"
if ($name OR $band) {
// concat name and band, use trim to clean the string if one is missing
$title = trim(implode(' ', array($name, $band)));
// $title == "name1[ name2[ ...]] band1[ band2[ ...]]"
// disable and reenable hook from within to avoid a loop
remove_action('save_post', 'update_term_title');
$update = array(
'ID' => $post_id,
'post_name' => sanitize_title_with_dashes($title),
'post_title' => $title,
);
wp_update_post($update);
add_action('save_post', 'update_term_title');
}
}
Normally I wouldn’t suggest this method because of the disable/reenable hack, there is a filter for post data called wp_insert_post_data
meant for altering the post data prior to the DB UPDATE/INSERT, but you’d probably have to understand quite a bit more to get past figuring out how to reference the taxonomy items that haven’t yet been saved. The above method is technically quite expensive as it requires saving a post, requesting the post and then saving the post again
Old Answer:
wp_get_post_terms()
returns an array, not a string.
wp_get_post_terms docsYou need to treat
$term1
and$term2
as arrays.$term1 = wp_get_post_terms($post_id, 'name', array('fields' => 'names')); $term2 = wp_get_post_terms($post_id, 'band', array('fields' => 'names')); # this assumes the first term in the taxonomy is the one you want $terms = array_pop($term1) . array_pop($term2);