0

On my wordpress site I have a front end form that allows users to create posts and upload photos for a custom post type 'Property'.

Using the following function -

$property_sights_value = get_post_meta($Property_Id, 'imic_property_sights', false);

if (!empty($_FILES['sightMulti']['tmp_name'][0])) {
                    $i = 1;
                    $files = $_FILES['sightMulti'];
                    foreach ($files['name'] as $key => $value) {
                        if ($files['name'][$key]) {
                            $file = array(
                                'name' => $files['name'][$key],
                                'type' => $files['type'][$key],
                                'tmp_name' => $files['tmp_name'][$key],
                                'error' => $files['error'][$key],
                                'size' => $files['size'][$key]
                            );
                            $_FILES = array("sight" . $i => $file);
                            $newuploadMulti = sight("sight" . $i, $pid);
                            if ($i == 1) {
                                update_post_meta($pid, '_thumbnail_id', $newuploadMulti);

                            }
                            add_post_meta($pid, 'imic_property_sights', $newuploadMulti, false);
                        }
                        $i++;
                    }
                }
        }

And then on another page I have the same thing except for a different custom post type 'v_editor', and a different upload function, which converts images to .png format and gets rid of the original -

$vid_pix = get_post_meta($v_Id, 'vid_pix', false);

    if (!empty($_FILES['vidPix']['tmp_name'][0])) {
                        $i = 1;
                        $files = $_FILES['vidPix'];
                        foreach ($files['name'] as $key => $value) {
                            if ($files['name'][$key]) {
                                $file = array(
                                    'name' => $files['name'][$key],
                                    'type' => $files['type'][$key],
                                    'tmp_name' => $files['tmp_name'][$key],
                                    'error' => $files['error'][$key],
                                    'size' => $files['size'][$key]
                                );
                                $_FILES = array("sight" . $i => $file);
    add_filter( 'upload_dir', 'wpse_141088_upload_dir' );
    add_filter('intermediate_image_sizes_advanced', 'no_image_resizing');

                            $mfile =  wp_handle_upload($files, $upload_overrides );             

                                $newvidPix = sight("sight" . $i, $v_Id);
    remove_filter( 'upload_dir', 'wpse_141088_upload_dir' );
    remove_filter('intermediate_image_sizes_advanced', 'no_image_resizing');
    // Convert the image to PNG and delete the old image.
    attachment_to_png( $newvidPix );

                                if ($i == 1) {
                                    update_post_meta($v_Id, '_thumbnail_id', $newvidPix);
                                }
                                    add_post_meta($v_Id, 'vid_pix', $newvidPix, false);
                            }
                            $i++;
                        }
                    }

Both functions work fine, however, what I am trying to do is--

On the 'v_editor' cpt form, I am trying to create a select dropdown to let the user choose a post of his from the 'property' cpt, and grab the images saved there to copy over to use. --

<?php query_posts(array('post_type'=>'property','order'=>'desc','author'=>$current_user->ID,'posts_per_page' => 25,'paged' => get_query_var('paged'),'post_status' => array('publish','pending','draft')));
if(have_posts()): 

echo '<select id="property_posts" name="property_posts">';

while(have_posts()):the_post();

echo '<option value="'.get_the_ID().'">'.get_the_title().'</option>';

endwhile;

echo '</select>';

endif; ?>

<button type="button" id="import_pics">Import</button>

Both of the images when uploaded get stored to meta keys -

PROPERTY CPT - $property_sights_value = get_post_meta($Property_Id, 'imic_property_sights', false);

V_EDITOR CPT - $vid_pix = get_post_meta($v_Id, 'vid_pix', false);

How can I achieve this?

UPDATE

This is what I currently have - On my front end custom post editor form for my V_EDITOR CPT, I have the following code that creates a drop down list of the current user's post in the PROPERTY CPT, with each of its id and title -

<form id="import_photos" action="import-pics.php" method="post" target="_blank">

<?php query_posts(array('post_type'=>'property','order'=>'desc','author'=>$current_user->ID,'post_status' => array('publish','pending','draft')));
if(have_posts()):

echo '<select id="propertyID" name="propertyID">';
while(have_posts()):the_post();
$id = get_the_ID();
$v_title1 = get_the_title($id);

echo '<option value="'.$id.'">'.$v_title1.'</option>';
endwhile;
echo '</select>';
endif; ?>
<input type="hidden" name="videoID" id="videoID" value="<?php echo $v_Id; ?>">
<input type="submit" id="ip_submit" class="savestuff2" name="ip_submit" value="Import Photos">
</form>
<?php wp_reset_query(); ?>

When a user selects an option and clicks the submit button, a new window opens up and currently shows the photos from that post. This is the import-pics.php script --

<?php
require_once $_SERVER['DOCUMENT_ROOT'] . '/wp-load.php';

$propertyID = $_POST['propertyID'];
$vidID = $_POST['videoID'];

$query = new WP_Query( 
  array( 
    'post_type' => 'property', 
    'posts_per_page' => -1,
    'fields' => 'ids',
    'p' => $propertyID
  ) 
);
$image_query = new WP_Query( 
  array( 
    'post_type' => 'attachment', 
    'post_status' => 'inherit', 
    'post_mime_type' => 'image', 
    'posts_per_page' => -1, 
    'post_parent__in' => $query->posts, 
    'order' => 'DESC' 
  ) 
);

if( $image_query->have_posts() ){
  while( $image_query->have_posts() ) {
      $image_query->the_post();
      $filename = basename ( get_attached_file( get_the_ID() ) );
      $imgurl = wp_get_attachment_url( get_the_ID() );

      echo '<div style="display:inline-block;margin:10px;">';
      echo '<a href="'.$imgurl.'"><img style="width:200px;" src="'.$imgurl.'"></a>';
      echo '</div>';
  }
}

?>

What I need to do is copy over the images in the PROPERTY post type custom field $property_sights_value into the V_EDITOR post type custom field $vid_pix, they are both image attachments. How can I do this using my script?

UPDATE

(Trying to get it work with ajax)

My code in my functions.php file --

add_action( 'wp_enqueue_scripts', 'ajax_imp_enqueue_scripts' );
function ajax_imp_enqueue_scripts() {

wp_enqueue_script( 'imp', get_stylesheet_directory_uri() . '/imp.js', array(), '1.0.0', true );

wp_localize_script( 'imp', 'imppro', array(
        'ajax_url' => admin_url( 'admin-ajax.php' )
    ));

}

add_action('wp_ajax_imp_pros', 'import_the_photos');
add_action('wp_ajax_nopriv_imp_pros', 'import_the_photos');

function import_the_photos() {

Global $wp_query;
$current_page_id = $wp_query->get_queried_object_id();
global $post;
global $current_user;
$current_user = wp_get_current_user();

$propertyID = $_POST['propertyID'];
$videoID = $_POST['videoID'];

// Get the attachments (IDs) attached to the `property` CPT.
$prop_att_ids = (array) get_post_meta( $propertyID, 'imic_property_sights', false );

// Copy the meta value (attachments) to the `v_editor` CPT.
$vid_pix = get_post_meta( $videoID, 'vid_pix', false ); // test
//delete_post_meta( $videoID, 'vid_pix' );
foreach ( $prop_att_ids as $att_id ) {
    add_post_meta( $videoID, 'vid_pix', $att_id );
}
$vid_pix2 = get_post_meta( $videoID, 'vid_pix', false ); // test
var_dump( $vid_pix, $vid_pix2 ); // test

// Show a notice to the user.
echo '<p>Photos below have been imported ' .
    'from <i>' . get_the_title( $propertyID ) . '</i> ' .
    'to <i>' .  $videoID . '</i>:</p>';

// And show the attachments.
foreach ( $prop_att_ids as $att_id ) {
    $imgurl = $att_id ? wp_get_attachment_url( $att_id ) : '';
    if ( $imgurl ) {
        echo '<div style="display:inline-block;margin:10px;">';
        echo '<a href="'.$imgurl.'"><img style="width:200px;" src="'.$imgurl.'"></a>';
        echo '</div>';
    }
}

die();

}

And my JS code --

jQuery(document).on('click','#ip_submit',function (e) {
  e.preventDefault();

 var propertyID = $('#propertyID').val();
 var videoID = $('#videoID').val();

                    $.ajax({
                      url: imppro.ajax_url,
                      data: {
                       action: 'imp_pros',
                       propertyID: propertyID,
                       videoID: videoID
                         },
                     //processData: false,
                     //contentType: false,
                      type: 'POST',
                      success: function(data){
                        console.log(data);
                        $("#save-order").trigger("click");
                        //$('#loader').hide();
                        //$('#finished').show().delay(3000).fadeOut();
                        }
                    });

        });
  • I don't see any field named videoID in the v_editor CPT form? Are you getting the right post ID ($vidID) in import-pics.php? – Sally CJ Sep 25 '18 at 23:20
  • yes. i had it as a static value for testing and forgot to add the input to the form when I changed it for the question – Rich Sep 26 '18 at 0:44
1

UPDATE #2

In your import_the_photos() function, please change this:

// Copy the meta value (attachments) to the `v_editor` CPT.
$vid_pix = get_post_meta( $videoID, 'vid_pix', false ); // test
//delete_post_meta( $videoID, 'vid_pix' );
foreach ( $prop_att_ids as $att_id ) {
    add_post_meta( $videoID, 'vid_pix', $att_id );
}
$vid_pix2 = get_post_meta( $videoID, 'vid_pix', false ); // test
var_dump( $vid_pix, $vid_pix2 ); // test

to:

// Get the attachments (IDs) attached to the `v_editor` CPT.
$vid_att_ids = (array) get_post_meta( $vidID, 'vid_pix', false );

// Copy/add the attachments to the `v_editor` CPT.
foreach ( $prop_att_ids as $att_id ) {
    if ( $att_id && ! in_array( $att_id, $vid_att_ids ) ) {
        add_post_meta( $vidID, 'vid_pix', $att_id );
    }
}

var_dump( $prop_att_ids, $vid_att_ids, get_post_meta( $vidID, 'vid_pix', false ) ); // test

Apologize for the delete_post_meta(), which thankfully you commented out..


Original Answer

(Old code removed, though.)

In your import-pics.php file, add this before the $query = new WP_Query line:

// Get the attachments (IDs) attached to the `property` CPT.
$prop_att_ids = (array) get_post_meta( $propertyID, 'imic_property_sights', false );

// Copy the meta value (attachments) to the `v_editor` CPT.
// OLD CODE HERE; REMOVED

But here's the full code I used, where I don't use the new WP_Query() constructs:

<?php
// File: import-pics.php

require_once $_SERVER['DOCUMENT_ROOT'] . '/wp-load.php';

$propertyID = $_POST['propertyID'];
$vidID = $_POST['videoID'];

// Get the attachments (IDs) attached to the `property` CPT.
$prop_att_ids = (array) get_post_meta( $propertyID, 'imic_property_sights', false );

// Copy the meta value (attachments) to the `v_editor` CPT.
// OLD CODE HERE; REMOVED

// Show a notice to the user.
echo '<p>Photos below have been imported ' .
    'from <i>' . get_the_title( $propertyID ) . '</i> ' .
    'to <i>' . get_the_title( $vidID ) . '</i>:</p>';

// And show the attachments.
foreach ( $prop_att_ids as $att_id ) {
    $imgurl = $att_id ? wp_get_attachment_url( $att_id ) : '';
    if ( $imgurl ) {
        echo '<div style="display:inline-block;margin:10px;">';
        echo '<a href="'.$imgurl.'"><img style="width:200px;" src="'.$imgurl.'"></a>';
        echo '</div>';
    }
}

// Show a "close" JS button..
echo '<p><a href="#" onclick="window.close(); return false;">Back to form</a></p>';
?>

PS: Updated because I forgot the meta imic_property_sights and vid_pix are added multiple times to a post. Sorry about that.

  • I am trying to use the code as a function in functions.php so I can do it via ajax from my page. It seems to copy everything except the image url. When using as a script, as described in my question, it works fine. Any tweak im missing to get to work with ajax? – Rich Sep 28 '18 at 14:20
  • Thanks for accepting the answer. First, are you using add_action( '{wp_ajax OR wp_ajax_nopriv}_{ACTION}' )? Secondly, can you share your AJAX JS code and the PHP function for handling the request, unless you're making AJAX requests to the import-pics.php? – Sally CJ Sep 28 '18 at 14:33
  • i've updated my question with the code – Rich Sep 28 '18 at 14:54
  • Check the id attribute, which should be videoID, since in the JS code, you use $('#videoID'): <input type="hidden" name="videoID" id="videoId" ...>. The id is case-sensitive - I mean, $('#videoID') and $('#videoId') are referencing to different elements. – Sally CJ Sep 28 '18 at 15:16
  • Alternatively, in the JS code, use $('#videoId') instead. Or is that videoId was just a typo in the question? (I hope it's not... means changing it in the HTML/JS code would solve the problem.) – Sally CJ Sep 28 '18 at 15:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.