Last active
June 26, 2017 22:02
-
-
Save hearvox/cb3ed3cd9c0f2182fa18dd456136b2ca to your computer and use it in GitHub Desktop.
WordPress: (very specific use script) Matches number in attachment (PDF) name to a custom field value and attaches media to that post.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* Get unattached files in Media Library */ | |
$args_search = array( | |
'post_type' => 'attachment', | |
'post_status' => 'inherit', | |
'post_parent' => 0, | |
'post_mime_type' => 'application/pdf', // Only PDFs. | |
'posts_per_page' => 40, | |
'orderby' => 'id', | |
'order' => 'ASC', | |
's' => 'trail_study_', | |
); | |
$query_search = new WP_Query( $args_search ); | |
/* Make array unattached files' slugs (value) and IDs (keys) */ | |
foreach ( $query_search->posts as $post ) { | |
$attachments[$post->ID] = $post->post_name; // Make array. | |
// echo "'$post->ID' => '$post->post_name',\n"; // Print array items. | |
} | |
// print_r( $attachments ); | |
/* Find a post with attachment slug in content (e.g, in a link). */ | |
foreach ( $attachments as $attach_id => $attach_name ) { | |
// Get number from slug (e.g.: 'trail_study_5-nebraska-rural-trails'). | |
$slug_arr = preg_split( '/(\d+)\K/', $attach_name, -1, PREG_SPLIT_DELIM_CAPTURE ); | |
$args = array( | |
'post_type' => 'trail', | |
'meta_key' => 'study_id', | |
'meta_value' => $slug_arr[1], | |
'fields' => 'ids', | |
'posts_per_page' => 1, | |
); | |
$query = new WP_Query( $args ); | |
$post_id = $query->posts[0]; | |
// For testing befoe=re running. | |
echo "<pre>$attach_id\t$attach_name\t$slug_arr[1]\t$post_id</pre>"; | |
// Attach file (in Media Library) to post. | |
// UNCOMMENT TO RUN | |
// $wp_update_post = wp_update_post( array( 'ID' => $attach_id, 'post_parent' => $post_id ) ); | |
// UNCOMMENT TO PRINT RESULTS | |
// echo "$slug_arr[1]\t$attach_id\t$wp_update_post\rhttps://headwaterseconomics.org/trail/$post_slug/\r\r"; | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment