更新答案:
通过使用$args
在里面wp_get_post_terms
您不需要运行foreach
寻找子术语(您的自定义分类法是否具有层次结构?)。作为一个包罗万象的人implode
完整的列表并得到相同的结果(但在没有看到/了解您的模式的情况下,我无法确定它实际上是您想要的。)
<?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\');
}
}
通常我不会建议使用这种方法,因为有禁用/可重入的黑客,有一个用于post数据的过滤器,名为
wp_insert_post_data
用于在DB更新/插入之前更改post数据,但您可能需要了解更多内容,才能了解如何引用尚未保存的分类项目。上述方法在技术上相当昂贵,因为它需要保存一篇文章,请求该文章,然后再次保存该文章
旧答案:
wp_get_post_terms()
返回数组,而不是字符串。wp_get_post_terms docs
你需要治疗$term1
和$term2
作为阵列。
$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);