我正在检查“categoryone”是否有家长。好的,我知道我可以检查并看到有一个类别叫做categoryone,但我想检查父类别和子类别的categoryone。我曾尝试编写类似以下代码的代码。最后,我的目标是使用wp\\u set\\u post\\u categorie();类别检查后。
foreach ( $network_posts as $network_post ) {
// Add the new post
$insert_id = wp_insert_post( $network_post->post );
// Add metadata (useful for lookups later)
update_post_meta( $insert_id, \'_network_content\', 1 );
update_post_meta( $insert_id, \'_network_site_orig_id\', array(
\'site_id\' => $bid,
\'post_id\' => $network_post->id,
) );
$tid = term_exists(\'categoryone\', \'category\', 0);
$term_ids = [];
if ( $tid !== 0 && $tid !== null )
{
$term_ids[] = $tid[\'term_id\'];
}
else
{
$insert_term_id = wp_insert_term( \'categoryone\', \'category\' );
if ( ! is_wp_error )
$term_ids[] = $insert_term_id;
}
wp_set_post_categories( $insert_id, $term_ids );
}
SO网友:gmazzap
首先考虑如果类别存在,term_exists
函数返回数组,而不是术语id。请参阅Codex.
因此:
$term_ids = array();
$term = term_exists(\'categoryone\', \'category\', 0);
if ( is_array($term) && isset($term[\'term_id\']) ) { // term exists as parent cat
$term_ids[] = $term[\'term_id\'];
// get all the children of the categories
$children = get_categories( array( \'parent\'=> $term[\'term_id\'], \'hide_empty\'=>false) );
if ( ! empty($children) ) {
// category exist as parent and also have children
// do you want to add also the children? If so:
$children_ids = wp_list_pluck($children, \'term_id\');
$term_ids = array_merge($term_ids, $children_ids);
} else {
// category exist as parent but has no children
}
} else { // term does not exists as parent cat
$insert_term_id = wp_insert_term( \'categoryone\', \'category\' );
$term_ids[] = $insert_term_id;
}
然后,如果
$insert_id
是您可以使用的帖子的ID:
wp_set_post_categories( $insert_id, $term_ids );
有关更多信息,请参阅codex For