Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RadGH/4a0d3e7ac3fb74e0053687662f515fc4 to your computer and use it in GitHub Desktop.
Save RadGH/4a0d3e7ac3fb74e0053687662f515fc4 to your computer and use it in GitHub Desktop.
Assign folder to an uploaded attachment with Wicked Folders using PHP
<?php
/**
* Adds an object to the given folder name.
*
* @param $object_id
* @param $folder_name
* @param $parent_folder_id
*
* @return bool
*/
function rs_assign_folder_to_object( $object_id, $folder_name, $parent_folder_id = 0 ) {
$term_name = $folder_name;
$taxonomy = 'wf_'. get_post_type( $object_id ) .'_folders';
// Get the existing term name
$term_id = term_exists( $term_name, $taxonomy, $parent_folder_id );
if ( !$term_id ) {
// Create the term instead
$t = wp_insert_term( $term_name, $taxonomy, array( 'parent' => $parent_folder_id ) );
if ( $t && !is_wp_error($t) ) $term_id = $t['term_id'];
}
if ( $term_id ) {
wp_add_object_terms( $object_id, $term_id, 'wf_attachment_folders' );
}
return false;
}
// *******************
// EXAMPLE USAGE
// *******************
// Assign attachment ID #47 to the folder "Important Documents"
function example_assign_folder_to_attachment() {
$attachment_id = 47;
$folder_name = 'Important Documents';
rs_assign_folder_to_object( $attachment_id, $folder_name );
}
// MUST be called after "init" priority 15, which is where the taxonomy is registered.
// If you call this function earlier the example will not work.
add_action( 'init', 'example_assign_folder_to_attachment', 16 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment