0

I have created a custom metabox with an image uploader that will upload multiple images into a gallery that I can then query. It all works accept for the fact that the images don't show as attached to the post in the media library. They are showing as unattached. Any ideas folks?

<?php
// Add the Meta Box
function agch_properties_add_custom_meta_box() {
    add_meta_box(
        'custom_meta_box', // $id
        'Property Photos', // $title
        'agch_properties_show_custom_meta_box', // $callback
        'properties', // $page
        'normal', // $context
        'high'); // $priority
}
add_action('add_meta_boxes', 'agch_properties_add_custom_meta_box');

// Field Array
$prefix = 'agch_properties_';
$custom_meta_fields = array(
    array(
        'label'=> 'Upload Images',
        'desc'  => 'This is the gallery images on the single item page.',
        'id'    => $prefix.'gallery',
        'type'  => 'gallery'
    ),
);

// The Callback
function agch_properties_show_custom_meta_box($object) {
        global $custom_meta_fields, $post;
        // Use nonce for verification
        echo '<input type="hidden" name="custom_meta_box_nonce" value="'.wp_create_nonce(basename(__FILE__)).'" />';

        // Begin the field table and loop
        echo '<table class="form-table">';
        foreach ($custom_meta_fields as $field) {
                // get value of this field if it exists for this post
                $meta = get_post_meta($post->ID, $field['id'], true);
                // begin a table row with
                echo '<tr>
                <th><label for="'.$field['id'].'">'.$field['label'].'</label></th>
                <td>';
                switch($field['type']) {
                        case 'gallery':
                        $meta_html = null;
                        if ($meta) {
                                $meta_html .= '<ul class="agch_properties_gallery_list">';
                                $meta_array = explode(',', $meta);
                                foreach ($meta_array as $meta_gall_item) {
                                        $meta_html .= '<li><div class="agch_properties_gallery_container"><span class="agch_properties_gallery_close"><img id="' . esc_attr($meta_gall_item) . '" src="' . wp_get_attachment_thumb_url($meta_gall_item) . '"></span></div></li>';
                                }
                                $meta_html .= '</ul>';
                        }
                        echo '<input id="agch_properties_gallery" type="hidden" name="agch_properties_gallery" value="' . esc_attr($meta) . '" />
                        <span id="agch_properties_gallery_src">' . $meta_html . '</span>
                        <div class="agch_gallery_button_container"><input id="agch_properties_gallery_button" type="button" value="Add Images" /></div>';
                        break;
                } //end switch
                echo '</td></tr>';
        } // end foreach
        echo '</table>'; // end table
}

// Save the Data
function agch_properties_save_custom_meta($post_id) {
        global $custom_meta_fields;
        // Verify nonce
        if ($_POST && !wp_verify_nonce($_POST['custom_meta_box_nonce'], basename(__FILE__)))
                return $post_id;
        // Check autosave
        if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE)
                return $post_id;
        // Check permissions
        if ('properties' == get_post_type()) {
                if (!current_user_can('edit_page', $post_id))
                        return $post_id;
        } elseif (!current_user_can('edit_post', $post_id)) {
                return $post_id;
        }
        // Loop through meta fields
        foreach ($custom_meta_fields as $field) {
                $new_meta_value = esc_attr($_POST[$field['id']]);
        $meta_key = $field['id'];
                $meta_value = get_post_meta( $post_id, $meta_key, true );
                // If theres a new meta value and the existing meta value is empty
                if ( $new_meta_value && $meta_value == null ) {
                        add_post_meta( $post_id, $meta_key, $new_meta_value, true );
                // If theres a new meta value and the existing meta value is different
                } elseif ( $new_meta_value && $new_meta_value != $meta_value ) {
                        update_post_meta( $post_id, $meta_key, $new_meta_value );
                } elseif ( $new_meta_value == null && $meta_value ) {
                        delete_post_meta( $post_id, $meta_key, $meta_value );
                }
        }
}
add_action('save_post', 'agch_properties_save_custom_meta');

function AGCH_properties_load_wp_admin_style() {
        wp_enqueue_media();
        wp_enqueue_script('media-upload');
        wp_enqueue_style( 'AGCH_properties_admin_css', get_template_directory_uri() . '/library/css/properties_gallery_admin.css' );
        wp_enqueue_script( 'AGCH_properties_admin_script', get_template_directory_uri() . '/library/js/properties_gallery_admin.js' );
}
add_action( 'admin_enqueue_scripts', 'AGCH_properties_load_wp_admin_style' );
?>

2 Answers 2

0

Here is my function to save attachment in a field using acf plugin. It may helps

    $filename = $wp_upload_dir['path'].'/'.$img;

    // Check the type of file. We'll use this as the 'post_mime_type'.
    $filetype = wp_check_filetype( basename( $filename ), null );

    // Prepare an array of post data for the attachment.
    $attachment = array(
      'guid'           => $wp_upload_dir['url'] . '/' . basename( $filename ),
      'post_mime_type' => $filetype['type'],
      'post_title'     => preg_replace( '/\.[^.]+$/', '', basename( $filename ) ),
      'post_content'   => '',
      'post_status'    => 'inherit'
    );

    // Insert the attachment.
    $attach_id = wp_insert_attachment( $attachment, $filename, $post_id );

    // Make sure that this file is included, as wp_generate_attachment_metadata() depends on it.
    require_once( ABSPATH . 'wp-admin/includes/image.php' );

    // Generate the metadata for the attachment, and update the database record.
    $attach_data = wp_generate_attachment_metadata( $attach_id, $filename );
    wp_update_attachment_metadata( $attach_id, $attach_data );

    //Save attachment id in meta
update_field( $field, $attach_id , $post_id );
0

Here's a simplidfied "pseudo-code" example how you could set the gallery images as attachments to your post. The basic idea is to set the current post ID as the post_parent for the image posts.

You should have some kind of conditional check within the loop to check, if the current iteration / image should be attached or unattached to the post. Otherwise the images will stay attached to the post although you would remove their IDs from the post's meta.

I hope this example illustrates how you can set the image-post relation and you can modify your existing code with the help of this.

function your_save_function($post_ID, $post, $update) {

  // conditional checks, if this code should run or not

  // loop image IDs
  foreach ($gallery_image_ids as $gallery_image_id) {
    // should the image be attached or removed from post
    $no_parent_or_current_post = ( $some_condition ) ? $post_ID: 0;
    // update attachment post parent
    $att_args = array(
      'ID'          => $gallery_image_id,
      'post_parent' => $no_parent_or_current_post,
    );
    $att_updated = wp_update_post( $att_args, true );
    // log if something went wrong
    if ( is_wp_error( $att_updated ) ) {
      error_log( print_r( $att_updated, true ) );
    }    
  }

}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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