DHolloran/WPMultiFileUploader

how to pass an extra parameter?

Closed this issue · 14 comments

Hi,

I know this is not an issue. I´m trying to pass another value/variable in the fineuploader-execute.js like this:

validation: {
allowedExtensions: uploaderElem.data('mimetypes').split(','),
sizeLimit: parseInt( uploaderElem.data('maxsize'), 10 ) * 1024 * 1024,
currCat : uploaderElem.data('cat'),
},

no my question is, how can I access this value in php function add_attachment() ?

any help would be greatly appreciated!

thanks,
Kasper

by the way, I love this plugin!!

You should add the new parameter in the params object inside the request object directly above and then you can acces it by using $_POST or $_GET I forget which one. What is your end goal because it may be useable for someone else and I could try to incorporate it into the plugin

thanks for your reply!

I did change it to this:

    request: {
                    endpoint: ajaxUrl,

                    // Admin AJAX Param

                    params: {
                        action: 'wp_multi_file_uploader',
                        postId: uploaderElem.data('postid'),
                        category: uploaderElem.data('cat'),

                    },
                    paramsInBody: true
                },

and this in the action that receives the ajax call:

function wp_multi_file_uploader_callback()
{
$category = $_GET['category'];
$category2 = $_POST['category'];
echo $category;
echo $category2;
$file_uploader = new WPFMU_FileUploadHandler();
$file_uploader->handle_response();
} // wp_multi_file_uploader_callback()

I´m not sure why the echo is not working, but I basically want to pass this value to the add_attachment function
and finally add attachment metadata with that value:

public function add_attachment( $url )
{

// second script

    $wp_upload_dir = wp_upload_dir();
    $filename = str_replace( $wp_upload_dir['url'] . '/', '', $url );




    $wp_filetype = wp_check_filetype(basename($filename), null );

$filenamer = preg_replace('/.[^.]+$/', '', basename($filename));
$filenamer = $filenamer . 'test' . $cat_ID;
$attachment = array(
'guid' => $url,
'post_mime_type' => $wp_filetype['type'],
'post_title' => basename($filename),
'post_content' => '',
'post_status' => 'inherit'
);
$attach_id = wp_insert_attachment( $attachment, $url );
// you must first include the image.php file
// for the function wp_generate_attachment_metadata() to work
require_once( ABSPATH . 'wp-admin/includes/image.php' );
$attach_data = wp_generate_attachment_metadata( $attach_id, $filename );
wp_update_attachment_metadata( $attach_id, $attach_data );
update_post_meta( $attach_id, 'curr_cat', $category.$category2.'-test');

    return $attach_id;
} //add_attachment()

What I´m trying is to use your plugin with the "Automatic Featured Image Posts" plugin which basically just
hooks into the the add_attachment wp function and detects if it´s an image and if so, publishes a post with the image as featured image.

The final idea is to give the user, together with the upload from a select input with all the categories available.
the user choses the category and that value get´s saved as attachment meta which will be read by the other plugin so that that plugin can assign the post to the category chosen by the user.

cheers!

oh, and yes, I´m the same guy that posted on the wp support forum

You won't see the echo because it is an AJAX request so you will only see it in the response if your using some sort of dev tools but I believe it is $_POST because in the check file type function i use post for the postId but anyway you can just access that directly in the add attachment function since $_POST is a super global that can be accessed anywhere and then do what you need to do from there I think that should solve your issue. If that doesn't make sense or if it doesn't solve your issue ill mock a fix up tomorrow.

it´s really strange.

I send the parameter like shown above, within the params object which is inside the request object.

then in your class-wpmfu-file-upload-handler.php in the public function add_attachment( $url )

I use this code:

require_once( ABSPATH . 'wp-admin/includes/image.php' );
    $attach_data = wp_generate_attachment_metadata( $attach_id, $filename );
    wp_update_attachment_metadata( $attach_id, $attach_data );
    $cat = $_POST["category"];
    update_post_meta( $attach_id, 'curr_cat', $cat . '-test');

    return $attach_id;

but it saves the post meta as '-test' which means $cat is not defined

it would be awesome if you could mock up an example! I´m simply not getting my head arround it.

I tried everything and the post meta is not writing the globals into the database.

thanks!

I think your issue may be that you have not added a data- attribute to the form. Also if you do not have Codekit to recompile the JS file let me know and I can send you a new file with the category parameter. I have outlined how to add the parameter below.

I do have a possible better suggestion I was writing you last night from an iPad so I was reading my code on GitHub and forgot about this. I would assume that if you want the user to select the category you will be using a form with a select list, once a user uploads a file the plugin adds a hidden input field with the attachment id so you could do your update_post_meta() when the user submits the form by grabbing the post/get data from the form select whatever name you give it and the hidden field which has the name wp_multi_file_uploader_1. The biggest downfall to this way is it kind of removes the multi file upload capabilities unless you use multiple select lists created dynamically for every file. If you want to go this route I have included an example on how to disable the button once a user uploads a file if you only want them to add one file at a time. This personally would be in a way the best route since it does not alter any of the plugin files and you would still be able to update the plugin if need be.

Let me know if this works or if you need more explanation, thanks.

##Select List Example Disable Form

// Check if the form exists
if ( $('#wp_multi_file_uploader').length > 0 ) {
    // Grab the click event
    $('#wp_multi_file_uploader').on('click', function(){
        // This will make sure the user has selected something and not clicked cancel
        $(this).find('input[type="file"]').on('change', function(){
            // This will disable the file uploader
            $('#wp_multi_file_uploader input[type="file"]').attr('disabled', true);
            // This will be a class you can use to style the button so it looks disabled
            $('.qq-upload-button').addClass('disabled');
        });
    });
} // if()

##Select List Example

<form action="form-submit.php" method="post" accept-charset="utf-8">
    <select name="form_select_category">
        <option value="option1">Option 1</option>
        <option value="option2">Option 2</option>
        <option value="option3">Option 3</option>
        <option value="option4">Option 4</option>
    </select>
    <?php wp_multi_file_uploader(); ?>
    <input type="submit" name="form_submit" value="Submit">
</form>


<?php
  /////////////////////
 // form-submit.php //
/////////////////////
if ( !empty( $_POST['form_submit'] ) ) {
    update_post_meta( $_POST['wp_multi_file_uploader_1'], 'curr_cat', $_POST['form_select_category'] . '-test');
}
?>

##Adding a Parameter Example

 /////////////////////////////
 // class-wpmfu-plugin.php //
////////////////////////////
function build_form( $attrs = array() )
{
    extract( $attrs );
    global $post;

    $allowed_mime_types = ( gettype( $allowed_mime_types ) == 'array' ) ? implode( ',', $allowed_mime_types) : $allowed_mime_types;
    $form = '';
    $form .= '<ul ';
    $form .= 'id="wp_multi_file_uploader" ';
    $form .= 'class="unstyled" ';
    $form .= 'data-filecount="1" ';
    $form .= 'data-mimetypes="'.$allowed_mime_types.'" ';
    $form .= 'data-maxsize="'.$max_file_size.'" ';
    $form .= 'data-postid="'.$post->ID.'" ';
    $form .= 'data-cat="some_cat" '; // **** replace some_cat with the category ****
    $form .= 'data-ajaxurl="' . site_url( 'wp-admin/admin-ajax.php' ) . '">';
    $form .= '</ul>';

    return $form;
} // build_form()



  /////////////////////////////
 // fineuploader-execute.js //
/////////////////////////////
params: {
    action: 'wp_multi_file_uploader',
    postId: uploaderElem.data('postid'),
    category: uploaderElem.data('cat') // **** this references data-cat="some_cat" ****
},



  /////////////////////////////////////////
 // class-wpmfu-file-upload-handler.php //
/////////////////////////////////////////
public function add_attachment( $url )
{

    $wp_upload_dir = wp_upload_dir();
    $filename = str_replace( $wp_upload_dir['url'] . '/', '', $url );
    $wp_filetype = wp_check_filetype(basename($filename), null );

    $attachment = array(
         'guid' => $url,
         'post_mime_type' => $wp_filetype['type'],
         'post_title' => preg_replace('/\.[^.]+$/', '', basename($filename)),
         'post_content' => '',
         'post_status' => 'inherit'
    );
    $attach_id = wp_insert_attachment( $attachment, $url );
    // you must first include the image.php file
    // for the function wp_generate_attachment_metadata() to work
    require_once( ABSPATH . 'wp-admin/includes/image.php' );
    $attach_data = wp_generate_attachment_metadata( $attach_id, $filename );
    wp_update_attachment_metadata( $attach_id, $attach_data );


    /////////////////////////////////////////
    // Update Post Meta For Category Here //
    ///////////////////////////////////////
    update_post_meta( $attach_id, 'curr_cat', $_POST['category'] . '-test');
    return $attach_id;
} //add_attachment()

Hi,

I´m going to use multifile upload.

I have it setup this way:

"

        <label>Choose where to upload:</label>
        <select name='cat-parent' id='cat-parent' class='postform' >
<option value='-1'>-</option>
<option class="level-0" value="3">test</option>
<option class="level-1" value="5">&nbsp;&nbsp;&nbsp;test-job</option>
<option class="level-2" value="6">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;test-review</option>
<option class="level-2" value="4">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;test-edit</option>
<option class="level-0" value="1">Uncategorized</option>
    </div>"

    the select list I use without form and I listen in jQuery to the change of value and assign the data attribute to the form like this:

    jQuery('#cat-parent').change(displayVals);
    function displayVals() {
    jQuery('#wp_multi_file_uploader').attr('data-cat',jQuery('#cat-parent').val());
    console.log(jQuery('#cat-parent').val());

    }
    

    I hardcoded a data-cat attribute to make sure that isn´t the problem and it definitely isn´t

    I don´t really care about if it´s clicked or cancelled because I simply have the uploader button and drag&drop field with opacity:0; until a category is chosen and then I give the user the ability to select or drag files.

    I´m hitting the wall because I simply get empty $_POST['category'] and/or $_GET['category']

    In fileuploader forums they say it´s GET but when you use paramsInBody: true, then it´s POST.

    Would be great if you could try and test it yourself! Hardcode the data-attribute and save it as meta-data and check your database.

    I still get just "-test" which means both $_POST['category'] and $_GET['category'] are empty.

    thanks for your help!!

    In that situation you can jut use the jQuery('#cat-parent').val() instead of using a data attribute you may want to make sure to console.log the value to make sure it is not empty. It is for sure $_POST the last large section of code is all the changes you should have to make, short of changing the category: uploaderElem.data('cat') to category: jQuery('#cat-parent').val() and you wont need the data attribute. That should give you the correct $_POST value in the add_attachment() function. You can also $result[] = $_POST below $result = $this->handle_upload(); then you can check in the network tab of web inspector and find the request for admin-ajax.php and you should be able to see the $_POST data. Other than that I do not know the code I gave you worked at least in building some_cat-test with $_POST['some_cat']. One more thing you should not be using the $().attr('data-attr') you sould use just .data() the .attr() seems to fail in certain browsers primarily IE I've seen but could be in others too.

    Ok, I made the changes, so that it actually grabs the current .val() of the select menu.

    I did :

    $result = $this->handle_upload();
    $result[] = $_POST

    and this is what I get in the inspector:

    0: {action:wp_multi_file_uploader, postId:56, qquuid:b47f41fb-ee7d-47de-a621-edf1ad89010e,…}
    action: "wp_multi_file_uploader"
    postId: "56"
    qqtotalfilesize: "7635"
    qquuid: "b47f41fb-ee7d-47de-a621-edf1ad89010e"
    attachmentId: 248}

    I also tried and hardcoded the parameter like this-> category: 'trythis'

    so it really seems the parameter doesn´t get passed!

    Ok, I believe I have it solved as long as you use the same id for your select list this version will work for you. https://github.com/DHolloran/WPMultiFileUploader/archive/new-param-fix.zip the issue was when I did the first mockup I was not accounting for a .val() on a select list I should have asked more about your HTML setup. So the category is what the select list default is which would be -1. So I had to add an onSubmit callback that updated the value as it currently is. I have not tested if it is setting the meta correctly, it should be, but it is building the correct key which would be value-test as of now.

    Hey Dan,

    it works! thank you so much!

    I looked through the code and can´t figure out what you did differently!?

    thanks again!

    I added the onSubmit: function() in the callbacks object in the execute JS file so it would update the correct value of the select list.

    callbacks: {
        onComplete: function(id, fileName, response) {
            if(response.success) {
                var parentForm = $('#wp_multi_file_uploader').parent('form'),
                    uploader = $('#wp_multi_file_uploader'),
                    fileCount = uploader.data('filecount'),
                    attachId = response.attachmentId
                ;
                parentForm.append('<input type="hidden" name="wp_multi_file_uploader_'+fileCount+'" value="'+attachId+'">');
                uploader.data('filecount', fileCount + 1);
            } // if()
        }, // onComplete
        onSubmit: function( id, name ) {
            uploader.setParams({
                action: 'wp_multi_file_uploader',
                postId: uploaderElem.data('postid'),
                category: catParent.val()
            }, id);
        }
    }