After finding a couple of leads on how to do this, I’m coming up blank. What I am trying to accomplish is to add the post to a new category based on camera name. If the category doesn’t exist, then to create it and add.
Essentially what I have below grabs the attachment meta information and saves the camera information into $camera. From there, it kind of falls apart.
function add_post_camera_category() {
global $post;
global $wpdb;
// Load array with attachment information
if (is_null($imgID)) {
$images = get_children(array(
'post_parent' => $post->ID,
'post_type' => 'attachment',
'numberposts' => 1,
'post_mime_type' => 'image',
'orderby' => 'ID',
'order' => 'ASC'
));
if ($images) {
foreach ($images as $image) {
$imgID = $image->ID;
}
}
}
$imgmeta = wp_get_attachment_metadata($imgID);
if ($imgmeta)
{
if ($imgmeta['image_meta']['camera'])
$camera = $imgmeta['image_meta']['camera'];
// Add to custom category
if(!has_term('','category',$post_ID)){
$category = get_term_by( 'slug', $camera, 'category' );
$cat = array($category->slug);
wp_set_object_terms($post_ID, $cat, 'category');
}
}
}
add_action('save_post', 'add_post_camera_category');
First, some comments on your code:
$post
and$wpdb
are not needed, in any case you can declare them asglobal $post, $wpdb;
if (is_null($imgID))
get_term_by
with “slug”, but I guess it’s better to do it by “name”The following is a working code, but I’m not sure if there are any flaws in it. As I was not able to debug the
save_post
using FirePHP, I did a dirty trick dumping the vars inside a custom field:update_post_meta($post_ID, 'cf_debug_info', print_r($imgmeta,true));
.You use $post->ID to get the image data and then you use $post_ID to save your term data. I don’t think $post_ID is defined.
I usually take the post ID from the function call
Maybe it should be:
function add_post_camera_category($post_ID) {
http://codex.wordpress.org/Plugin_API/Action_Reference/save_post