首先,对您的代码进行一些评论:
全球$post
和$wpdb
不需要,在任何情况下,您都可以将其声明为global $post, $wpdb;
我不明白你用这个条件if (is_null($imgID))
您正在使用get_term_by
使用“slug”,但我想最好使用“name”以下是一个工作代码,但我不确定其中是否有任何缺陷。因为我无法调试
save_post
使用FireHP,我做了一个肮脏的把戏,将变量转储到自定义字段中:
update_post_meta($post_ID, \'cf_debug_info\', print_r($imgmeta,true));
.
add_action(\'save_post\', \'wpse_53549_add_post_camera_category\', 10, 2);
function wpse_53549_add_post_camera_category($post_ID, $post) {
if ( defined( \'DOING_AUTOSAVE\' ) && DOING_AUTOSAVE ) return;
$images = get_children( array(
\'post_parent\' => $post_ID,
\'post_type\' => \'attachment\',
\'numberposts\' => 1,
\'post_mime_type\' => \'image\',
\'orderby\' => \'ID\',
\'order\' => \'ASC\'
));
if ( $images )
{
$image = array_shift( $images );
$imgID = $image->ID;
}
if ( !$imgID )
return;
$imgmeta = wp_get_attachment_metadata($imgID);
if ( $imgmeta )
{
// this info may be useful when checking for has_term
// $defaultcat = get_option(\'default_category\');
$camera = ($imgmeta[\'image_meta\'][\'camera\']) ? $imgmeta[\'image_meta\'][\'camera\'] : false;
if ( $camera )
// Add to custom category
if( !has_term( $camera, \'category\', $post_ID ) )
{
$category = get_term_by( \'name\', $camera, \'category\' );
if ( $category )
{
$cat = array( $category->slug );
// the last parameter sets if the term must be appended or overwrite the previous
wp_set_object_terms( $post_ID, $cat, \'category\', true );
}
else
{
$id = wp_create_category( $camera );
$new_cat = get_term_by( \'id\', $id, \'category\' );
wp_set_object_terms( $post_ID, $new_cat->slug, \'category\', true );
}
}
}
}