Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save trey8611/a0321f0b109dba111e894642eaa89853 to your computer and use it in GitHub Desktop.
Save trey8611/a0321f0b109dba111e894642eaa89853 to your computer and use it in GitHub Desktop.
Assign imported images to folders in the Media Library Organizer plugin

This example assumes that you're importing images during a posts import and you want to assign the images to the "Products" folder in the Media Library. You can modify the code to assign them to different folders or even dynamic folders.

Plugin and hooks used:

function wpai_image_imported( $post_id, $att_id, $filepath, $is_keep_existing_images = '' ) {
	$taxonomy = 'mlo-category';
	$cat_name = 'Products';
	$cache_terms = get_option( 'wpai_cache_terms_for_recount_in_'.$taxonomy );
	if ( empty( $cache_terms ) ) {
		$cache_terms = [];
	} else {
		$cache_terms = maybe_unserialize( $cache_terms );
	}

	// Check if the term exists in the taxonomy.
	$term = term_exists( $cat_name, $taxonomy );

	// If the term doesn't exist, create it.
	if ( ! $term ) {
		$term = wp_insert_term( $cat_name, $taxonomy );
	}

	// Bail out if there was an error.
	if ( is_wp_error( $term ) ) {
		return;
	}

	// Determine the term ID.
	if ( is_array( $term ) ) {
		$term_id = $term['term_id'];
	} else {
		$term_id = $term;
	}

	// Assign the term to the attachment.
	wp_set_object_terms( $att_id, intval( $term_id ), $taxonomy, true );
	$cache_terms[] = intval( $term_id );
	update_option( 'wpai_cache_terms_for_recount_in_'.$taxonomy, $cache_terms );
}
add_action( 'pmxi_gallery_image', 'wpai_image_imported', 10, 4 );

function after_xml_import( $import_id, $import ) {
    $taxonomy = 'mlo-category';
	$cache_terms = get_option( 'wpai_cache_terms_for_recount_in_'.$taxonomy );
	if ( empty( $cache_terms ) ) return;
	$cache_terms = maybe_unserialize( $cache_terms );
	if ( is_array( $cache_terms ) ) {
		wp_update_term_count_now( $cache_terms, $taxonomy );
	}
	
	delete_option( 'wpai_cache_terms_for_recount_in_'.$taxonomy );

}
add_action( 'pmxi_after_xml_import', 'after_xml_import', 10, 2 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment