[英]PHP Import WP Terms child term into custom post type
我創建了一個導入工具,用於從json文件導入數據,以自定義帖子類型創建帖子。 一切正常,我可以導入acf字段以及指定的條款。 我的問題是,如何導入分配給該術語的子術語。
我現在有兩個變量來收集數據。 我想讓變量eventCategoryChildName將其有效值作為子項分配給eventCategoryID
$eventCategoryChildName = $ev['OfficialCity'];
$eventCategoryId = $ev['RegionID'];
這是現在沒有子術語的情況下術語導入的功能:
// set category terms
$cat_ids = $eventCategoryName;
// Add these categories, note the last argument is true.
wp_set_object_terms( $post_id, $cat_ids, 'lan', true );
編輯:
因此,我設法將與正確的父母相關聯的孩子導入,但未將其選中
// set category terms
$cat_ids = $eventCategoryName;
// Import category name
$term_taxonomy_ids = wp_set_object_terms( $post_id, $cat_ids, 'lan', true );
$parent_term = wp_set_object_terms( $post_id, $cat_ids, 'lan', true );
// Check terms import for errors
if ( is_wp_error( $term_taxonomy_ids ) ) {
// There was an error somewhere and the terms couldn't be set.
echo $return->get_error_message();
} else {
// Success! These categories were added to the post.
}
$parent_term = term_exists( $eventCategoryName, 'lan' );
wp_insert_term(
$eventCategoryChildName, // Customize as you wish
'lan',
array(
'parent' => $parent_term['term_id'],
'slug' => $eventCategoryChildName // Customize as you wish
)
);
if ( !is_wp_error( $child_term_result ) ) {
wp_set_object_terms( $post_id, $child_term_result['term_id'], 'lan', true );
}
首先,您應該檢查wp_set_object_terms
的結果,以查看是否返回了錯誤:
$term_taxonomy_ids = wp_set_object_terms( $post_id, $cat_ids, 'lan', true );
if ( is_wp_error( $term_taxonomy_ids ) ) {
// There was an error somewhere and the terms couldn't be set.
echo $return->get_error_message();
} else {
// Success! These categories were added to the post.
}
然后,您要添加的術語可能不存在。 在這種情況下, wp_set_object_terms
將返回invalid_taxonomy
錯誤。 因此,您可能需要在分類法中添加以下缺失術語:
wp_insert_term(
'Term Name', // Customize as you wish
'lan',
array(
'description' => 'Term desc', // Customize as you wish
'slug' => 'lan-slug1' // Customize as you wish
)
);
// For child term:
$parent_term = term_exists( 'parent_term_id', 'lan' );
$child_term_result = wp_insert_term(
'Child Term Name', // Customize as you wish
'lan',
array(
'parent' => $parent_term['term_id']
'description' => 'Term desc', // Customize as you wish
'slug' => 'lan-slug1' // Customize as you wish
)
);
// Add the child term to the post
if ( !is_wp_error( $child_term_result ) ) {
wp_set_object_terms( $post_id, $child_term_result['term_id'], 'lan', true );
}
最后,請確保至少在Wordpress的init
鈎子之后執行此代碼。 例如:
function parse_my_json() {
// Your code here
}
add_action('init','parse_my_json');
有用的參考資料:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.