WP Assign Attached Image to Category

128 Views Asked by At

Managed to display images attached to a specific category independently of it's parent's category. Now wanting newly uploaded images to be dynamically assigned to a category. In mySQL can manually do this with:

INSERT INTO `wp_term_relationships` (`object_id`, `term_taxonomy_id`, `term_order`) VALUES ('1000', '1', '0');

When adding the following to functions.php it produces an upload error:

    function image_category() {
        $wpdb->insert('wp_term_relationships', array(
        'object_id' => '1000',
        'term_taxonomy_id' => '26',
        'term_order' => '0'
    ));
}

Obviously once it succeeds would replace1000 with variable of new image ID.

Also tried:

$object_id = 1000;
$term_taxonomy_id = 26;
$term_order = 0;
   $wpdb->query( $wpdb->prepare( 
    "
        INSERT INTO $wpdb->wp_term_relationships
        ( object_id, term_taxonomy_id, term_order )
        VALUES ( %d, %s, %s )
    ", 
        array(
        10, 
        $object_id,
        $term_taxonomy_id, 
        $term_order
    ) 
) );
1

There are 1 best solutions below

0
On

Had an easier time simplifying it to:

add_action( 'add_attachment', 'image_category', 10 );
    function image_category($post_ID) {
        global $wpdb;

$term_taxonomy_id = 26;
$table = $wpdb->prefix.'term_relationships';
$data = array('object_id' => $post_ID, 'term_taxonomy_id' => $term_taxonomy_id, 'term_order' => 0);
$format = array('%d', '%s', '%s');
$wpdb->insert($table,$data,$format);
// $my_id = $wpdb->insert_id;
}