Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- // Details: https://wordpress.stackexchange.com/questions/316454/copy-attachments-to-another-post-type-and-change-attachment-url/316669#316669
- // File: import-pics.php
- require_once $_SERVER['DOCUMENT_ROOT'] . '/wp-load.php';
- global $current_user, $imic_options; // Use global
- wp_get_current_user(); // Make sure global is set, if not set it.
- $yourID = $current_user->ID;
- $propertyID = $_POST['propertyID'];
- $vidID = $_POST['videoID'];
- $path = WP_CONTENT_DIR . '/uploads/' . $yourID . '/' . $vidID;
- $path2 = $yourID . '/' . $vidID; // relative to wp-content/uploads
- $prop_att_ids = (array) get_post_meta( $propertyID, 'imic_property_sights', false );
- // Check copied attachments and don't include already copied ones.
- $copied_atts = (array) get_post_meta( $vidID, '_copied_imic_property_sights', true );
- $copied_atts = array_unique( array_filter( $copied_atts ) );
- $to_copy = array_diff( array_unique( array_filter( $prop_att_ids ) ), $copied_atts );
- // These two are for testing:
- echo 'Old $copied_atts: ' . implode( ', ', $copied_atts ) . '<br>';
- echo '$prop_att_ids: ' . implode( ', ', $prop_att_ids ) . '<br>';
- foreach ( $to_copy as $att_id ) {
- // Check if we have a valid image/attachment.
- if ( $att_id && $file = get_attached_file( $att_id ) ) {
- $filename = basename( $file );
- $file2 = $path . '/' . wp_unique_filename( $path, $filename );
- // Copy the image file to $path.
- if ( @copy( $file, $file2 ) ) {
- // Copy the attachment (post) data.
- $att = get_post( $att_id, ARRAY_A );
- unset( $att['ID'] );
- $att_id2 = wp_insert_attachment( $att, $file2 );
- // Then add the meta data `vid_pix`.
- add_post_meta( $vidID, 'vid_pix', $att_id2 );
- // Copy the attachment's meta data. (no thumbnails)
- $data = wp_get_attachment_metadata( $att_id );
- $data['file'] = $path2 . '/' . basename( $file2 );
- $data['sizes'] = [];
- wp_update_attachment_metadata( $att_id2, $data );
- // Add to copied attachments list.
- $copied_atts[ $att_id2 ] = $att_id;
- $url = wp_get_attachment_image_url( $att_id2, 'full' ); // test
- echo 'File copied! ' . make_clickable( $url ) . '<br>'; // test
- } else {
- echo "Could not copy <i>$file</i> to <b>$file2</b>!<br>"; // test
- }
- } else {
- echo 'Invalid attachment ID or missing attached file.<br>'; // test
- }
- }
- // Updates copied attachments.
- update_post_meta( $vidID, '_copied_imic_property_sights', $copied_atts );
- // These two are for testing:
- echo 'New $copied_atts: ' . implode( ', ', $copied_atts ) . '<br>';
- echo 'vid_pix: ' . implode( ', ', get_post_meta( $vidID, 'vid_pix', false ) ) . '<br>';
- ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement