• Resolved gpspake

    (@gpspake)


    I’m having some trouble with this.
    I want users to be able to click on ‘Upload Media’ and insert images in to the post.

    To get the ‘Add Media’ button to appear on the add-post and edit-post pages, I granted subscribers the ‘upload_files’ capability with the User Role Editor Plugin and I enabled ‘Rich Text(Full)’ in the WPUF settings. When a subscriber logs in and clicks on the “Add Media’ button, the WordPress media upload interface appears. If the subscriber then clicks ‘Select Files,’ browses to media on his or her computer, and clicks ‘Open,’ they receive an error message where the picture thumbnail would be.

    It took me a minute to figure out what was happening but I noticed that the button at the bottom of the add media interface, instead of saying ‘Insert into Post,’ says ‘Insert into Page.’
    I went back to User Role Editor and granted subscribers three more capabilities: edit_pages, edit_others_pages, and edit_published pages. Once these capabilities have been granted, subscribers can upload media and insert it directly in to the post.

    This tells us that, for some reason, the when the add media button is clicked on the WPUF add-post or edit-post pages, the WordPress media uploader is associating the media with the page itself rather than the post. When the Insert into Page button is clicked, thie image is inserted in to the WPUF post description; the user can save the post and they have effectively inserted a picture in to the post.

    There are at least a couple of major issues here.
    Obviously, granting subscribers these capabilities is not an option as it gives them the ability to edit actual pages if they know the page id. Also, because the images are associated with the page itself, they appear below the WPUF form, on the add post and edit post pages as ‘WPUF-Attachments’ and are visible to all users.

    This is proving more difficult to figure out than I expected.
    The solution is to make wp_editor’s Add Media Button recognize that the media is being added to the post description and not the page. However, I’m having a hard time figuring out where it’s being handled. Where is the ‘page id’ being passed to the media uploader, and how can we change it to be the ‘WPUF post ID?’

    Any ideas would be greatly appreciated.

    http://wordpress.org/extend/plugins/wp-user-frontend/

Viewing 15 replies - 1 through 15 (of 30 total)
  • Thread Starter gpspake

    (@gpspake)

    If it helps any, here are the differences in the selection source for the ‘Add Media’ button.

    Add New Post in WordPress Admin (Backend)

    <div id="wp-content-media-buttons" class="wp-media-buttons">
    	<a href="#" class="button insert-media add_media" data-editor="content" title="Add Media">
    		<span class="wp-media-buttons-icon"></span> Add Media
    	</a>
    </div>

    Add New Post in WPUF (Frontend)

    div id="wp-new-post-desc-editor-tools" class="wp-editor-tools hide-if-no-js"><div id="wp-new-post-desc-media-buttons" class="wp-media-buttons">
    	<a href="#" class="button insert-media add_media" data-editor="new-post-desc" title="Add Media">
    		<span class="wp-media-buttons-icon"></span> Add Media
    	</a>
    </div>

    Don’t know whats going on here. I’m running WordPress 3.4.2 (where ‘Add Media’ button is titled ‘Upload/Insert’) and never had a problem with this in the official version or my development version.

    Could it be a problem with WordPress 3.5.1 and your installation?

    It should be displayed and work for admin by default.

    same problem i am facing.

    I have a similar problem. In fact I’m having two issues surrounding uploading images.

    1. I have enabled the upload image function for the Add Post form for WPUF and it seems to run through the motions of uploading an image (the status percentage shows ok and ticks up to 100%) but then having reached 100%, the status indicator disappears and there is no file name listed or shown (which I think there used to be with an option to remove). Then, when submitting the final post, the image is not included indicating that the upload maybe failed.

    Then, trying to add a featured image a different way leads me onto the second issue (which must be connected).

    2. The Add Media button above the post content input opens the media page successfully but then when uploading a new image, it uploads seemingly successfully but then throws up the following error message in the right side bar a second or so after… “Error: An error occurred in the upload. Please try again later.”

    It would seem that 1 and 2 are actually the same problem but occurring via 2 different routes. All post publishing in the admin area works correctly including images / attachments etc.

    I’m using the core 1.1 with no customisations.

    Thread Starter gpspake

    (@gpspake)

    Well, the error message is the same one I’m getting. As I mentioned above you’ll notice that if you use the user role editor plugin and give users the capabilities ‘edit_pages, edit_others_pages and edit_published_pages. The error will go away and users can insert pictures directly in to the post. The problem is, they can now change the url to include any page ID and use their new capabilities to edit any page on the site. Obviously, this isn’t an option.

    So, the reason the error message shows up is because the media uploader is looking at the page post-id and checking page capabilities. It should be looking at the wpuf post post-id and checking post capabilities.

    I’m going to be working on this today. I’ve managed to grab both id’s with jquery and I’m going to try to replace the page id with the post id. We’ll see what happens.

    Hi gpspake,

    I’d be really very grateful if you could let me know if you have any luck with this. I’m not particularly capable with jQuery so any literal code edits would be appreciated if you do succeed.

    Started to have a bigger look at this.

    Just for the moment looking at the dual insert problem that results in the upload being attached to the add_post or edit_post page.

    Can confirm it’s a WordPress 3.5.1 problem.

    It doesn’t occur with WordPress 3.4.2 (At least with my development version).

    What’s happening is that the rich editor executes the following lines depending on the editor chosen:

    Rich Text(full)
    wp_editor( $description, 'new-post-desc', array('textarea_name' => 'wpuf_post_content', 'editor_class' => 'requiredField', 'teeny' => false, 'textarea_rows' => 8) );

    Rich Text(tiny)
    wp_editor( $description, 'new-post-desc', array('textarea_name' => 'wpuf_post_content', 'editor_class' => 'requiredField', 'teeny' => true, 'textarea_rows' => 8) );

    wp_editor is the default WordPress editor which uses TinyMCE.

    On clicking the Add Media button this brings up the plupload (the add-on used to upload/insert media) interface.

    If your only adding a previous file already in the media library then you wont have a problem.

    However if you choose to upload media then that media will be added as an attachment to the Edit Post or Add Post page. This happens straight after the upload whether you insert the post or not.

    This is a WordPress 3.5.1 bug as it’s totally different behaviour from WordPress 3.4.2 and is undesirable for many reasons.

    So in summary this is a WordPress 3.5.1 bug. It is not a WPUF bug.

    Workaround for the moment is not to use WordPress 3.5.1 if you need this feature.

    In the meanwhile me and gpspake will try to find a better workaround.

    I will also look at submitting a WordPress trac bug report as I’m sure other plugins will have this problem as well.

    Thread Starter gpspake

    (@gpspake)

    Prof & Jong, I think I got it working with some jquery. I’m going to make absolutely sure before I post the solution. It might need some cleaning up but I successfully inserted an image into a post as a subscriber. I’ll let you know soon.

    Thread Starter gpspake

    (@gpspake)

    Ok guys, here’s what I’ve got. This isn’t finished and there might be some bugs i haven’t run in to yet; I’m going to be kicking it some to see if I can break it but it seems to be a viable solution. Right now anything is better than giving subscribers page editing capabilities.

    First of all, I was using this tutorial. I had to the code some, probably because things are a little different in wpuf but it seems to be working.

    ……………….

    ***NOTE IMPORTANT!!! THIS IS NOT USABLE YET. TWO THINGS.
    1. The post ID
    Essentially what we’re doing is creating our own media uploader frame and replacing the wpModel settings post id (Whatever that is) with a different one, in this case it should be the wpuf id which you can get by using document.getElementsByName('post_id')[0].value;
    Unfortunately I’m still working on this because if I set document.getElementsByName('post_id')[0].value; to a variable, everything stops working.

    2. Add Post page.
    I have been working on this on the edit post page.So Once I get the post id thing working I’ll need to move over to add-post and get it working there. Who knows, there might not be any problem. We’ll see.
    ……………….

    Anyway here it is.
    Create a .js file; in my case, I named it uploader_custom.js and put it in a folder called js in my child theme directory.

    Then you need to call it in functions.php. This needs to be cleaned up and modified to only load on the add post and edit pages.

    function mytheme_register_scripts() { 
    
      wp_register_script(
        'theme-custom',
        '/wp-content/themes/mythemedirectory/js/uploader_custom.js',
        array('jquery'),
        '1.0.0',
        true
      );
    }
    add_action('init', 'mytheme_register_scripts');
    
    function mytheme_enqueue_scripts(){
        wp_enqueue_script('theme-custom'); //custom.js
    }
    add_action('wp_print_scripts', 'mytheme_enqueue_scripts');

    Here’s the js that goes in uploader_custom.js

    // Uploading files
    var file_frame;
    
      //jQuery('.upload_image_button').live('click', function( event ){
    	jQuery('.insert-media').live('click', function( event ){
       event.preventDefault();
    
    	var wp_media_post_id = wp.media.model.settings.post.id ;
    	var set_to_post_id = 1197; // Set this
    
        // If the media frame already exists, reopen it.
        if ( file_frame ) {
    		// Set the post ID to what we want
    		file_frame.uploader.uploader.param( 'post_id', set_to_post_id );
    		// Open frame
    		file_frame.open();
          return;
        }else {
    // Set the wp.media post id so the uploader grabs the ID we want when initialised
    wp.media.model.settings.post.id = set_to_post_id;
    }
    
    //alert (wp.media.model.settings.post.id);
    
        // Create the media frame.
        file_frame = wp.media.frames.file_frame = wp.media({
          title: jQuery( this ).data( 'uploader_title' ),
          button: {
          text: jQuery( this ).data( 'uploader_button_text' ),
          },
          multiple: false  // Set to true to allow multiple files to be selected
        });
    
        // When an image is selected, run a callback.
        file_frame.on( 'select', function() {
          // We set multiple to false so only get one image from the uploader
          attachment = file_frame.state().get('selection').first().toJSON();
    
          // Do something with attachment.id and/or attachment.url here
        });
    
        // Finally, open the modal
        file_frame.open();
      });

    This is sort of a learning experience for me. If anyone has anyone has any input, I would greatly appreciate it. I’ll be updating this with any new developments.

    Hi gpsake.

    You probably know this already but have some info that may be useful to you and others.

    Done a bit more investigation of what is really going on and have noted the differences between WordPress 3.4.2 and 3.5.1.

    Basically WordPress 3.5.1 uses a new “Insert Media” interface for posts. This uses it’s new wp.media interface and that’s what creates our problem.

    For both WordPress 3.4.2 and 3.5.1 the WPUF Rich Text editor option results in wp_editor being called which in turn calls the function wp-admin/includes/class-wp-editor.php:editor(). This in turn invokes the action ‘media_buttons’ which results in the function wp-admin/includes/media.php:media_buttons() being called.

    From here on WordPress 3.4.2 and 3.5.1 differ.

    For WordPress 3.4.2 the following excerpt shows wp-admin/includes/media.php:media_buttons() calling get_upload_iframe_src(..) which for WPUF results in the link wp-admin/media-upload.php?post_id=0 being added to the “Upload/Insert” button. This results in the attachment not being added to the Add/Edit Post Form.

    wp-admin/includes/media.php
    =============================
    
    function media_buttons($editor_id = 'content') {
    	$context = apply_filters('media_buttons_context', __('Upload/Insert %s'));
    
    	$img = '<img src="' . esc_url( admin_url( 'images/media-button.png?ver=20111005' ) ) . '" width="15" height="15" />';
    
    	echo '<a href="' . esc_url( get_upload_iframe_src() ) . '" class="thickbox add_media" id="' . esc_attr( $editor_id ) 
    
    . '-add_media" title="' . esc_attr__( 'Add Media' ) . '" onclick="return false;">' . sprintf( $context, $img ) . '</a>';
    }
    add_action( 'media_buttons', 'media_buttons' );
    ...
    function get_upload_iframe_src( $type = null, $post_id = null, $tab = null ) {
    	global $post_ID; /** Set to new post id by edit-form-advanced.php. Null for WPUF Add/Edit Post **/
    
    	if ( empty( $post_id ) ) /** Null for WPUF Add/Edit Post **/
    		$post_id = $post_ID;
    
            /** For $post_id = null => (int)$post_id = 0 **/
    	$upload_iframe_src = add_query_arg( 'post_id', (int) $post_id, admin_url('media-upload.php') );
    
    	if ( $type && 'media' != $type )
    		$upload_iframe_src = add_query_arg('type', $type, $upload_iframe_src);
    
    	if ( ! empty( $tab ) )
    		$upload_iframe_src = add_query_arg('tab', $tab, $upload_iframe_src);
    
    	$upload_iframe_src = apply_filters($type . '_upload_iframe_src', $upload_iframe_src);
    
    	return add_query_arg('TB_iframe', true, $upload_iframe_src);
    }

    For WordPress 3.5.1 the following excerpt shows wp-admin/includes/media.php:media_buttons() calling wp_enqueue_media(..). However at the beginning of media_buttons() it calls get_post() which gets the loop page which for WPUF is either the Add or Edit page with the shortcodes. This is the cause of our problems with WordPress 3.5.1.

    wp-admin/includes/media.php
    ===========================
    
    /**
     * Adds the media button to the editor
     *
     * @since 2.5.0
     *
     * @param string $editor_id
     */
    function media_buttons($editor_id = 'content') {
    	$post = get_post(); /** Gets the loop page. For WPUF this is the pages with the Add/Edit shortcodes **/
    	if ( ! $post && ! empty( $GLOBALS['post_ID'] ) )
    		$post = $GLOBALS['post_ID'];
    
    	wp_enqueue_media( array(
    		'post' => $post
    	) );
    ...
    }
    add_action( 'media_buttons', 'media_buttons' );

    The possible workarounds are numerous.

    1. Add a custom editor (like you have done)
    2. Replace the media_buttons action
    3. Use the media_view_settings filter in the function wp-includes/media.php:wp_enqueue_media() to set the settings as desired for WPUF. This is probably the easiest option.
    4. Use a filter or action further down the call stack to achieve the desired result.

    Below is the relevant excerpt from wp-includes/media.php:wp_enqueue_media()

    wp-includes/media.php
    ======================
    
    function wp_enqueue_media( $args = array() ) {
    ...
    	$post = null;
    	if ( isset( $args['post'] ) ) {
    		$post = get_post( $args['post'] );
    		$settings['post'] = array(
    			'id' => $post->ID,
    			'nonce' => wp_create_nonce( 'update-post_' . $post->ID ),
    		);
    
    		if ( current_theme_supports( 'post-thumbnails', $post->post_type ) && post_type_supports( 
    
    $post->post_type, 'thumbnail' ) ) {
    			$featured_image_id = get_post_meta( $post->ID, '_thumbnail_id', true );
    			$settings['post']['featuredImageId'] = $featured_image_id ? $featured_image_id : -1;
    		}
    	}
    ...
    	$settings = apply_filters( 'media_view_settings', $settings, $post );
    	$strings  = apply_filters( 'media_view_strings',  $strings,  $post );
    
    	$strings['settings'] = $settings;
    
    	wp_localize_script( 'media-views', '_wpMediaViewsL10n', $strings );
    ...

    Ultimately this is a WordPress bug as attachments shouldn’t be linked to the post till the user has pressed the “Insert Post/Page” button. I am probably putting in a WordPress trac bug report on this.

    For gpsake I am posting you my complete function trace so you can see what’s going on.

    Cheers
    The Professor

    Thread Starter gpspake

    (@gpspake)

    Prof,

    This makes a lot of sense; Thanks for taking the time to type all of that out.
    Now that we know the differences between 3.5 and previous versions, I have no problem with ignoring older versions and focusing solely on 3.5.

    That being said, you mentioned that the media_view_settings filter would probably be the easiest solution here. (Apologies in advance for not knowing what I’m talking about)

    So just thinking out loud, I guess we would want to do something like:

    if (add-post-page or edit-post-page){ //Only do this on these 2 pages
    add_filter ('replace_the_id', 'media_view_settings')
    function replace_the_id() {
    array( 'id' = the wpuf id,
    'nonce' => wp_create_nonce( 'update-post_' . wpuf nonce ),
    }
    }

    Or should I be trying to do this with jquery like the previous approach?

    Hi gpspake,

    Yes this is what I’m thinking with a few mods.

    We do need to account for both WordPress 3.4.2 and 3.5.1 but this can be easily done by simply looking at the WordPress version.

    The post_id needs to be omitted altogether due to wp-admin/includes/ajax-actions.php:wp_ajax_upload_attachment() which requires a valid post_id (0 isn’t valid) or none at all.

    I think the (‘update-post_’ . $post->ID) nonce isn’t used so can be left out.

    The ‘media-form’ nonce used in wp-admin/includes/ajax-actions.php:wp_ajax_upload_attachment() is set in wp-includes/media.php:wp_plupload_default_settings() which also sets ‘action’ => ‘upload-attachment’, and a lot of the other parameters

    Yet to try it as making sure there are no other potential conflicts.

    Hi prof / gpspake,

    I’m following all of the discussion above and understand the cause of the issue now. Had a gut feeling it was linked to the new insert media interface and how it behaves so good to now have identified the reason.

    I will keep checking progress but thanks for your investigative work so far. I am toggling trying different solutions including changing the editor at least temporarily but would rather tweak the code to adjust the default behaviour and restore the default editor at some point.

    J.

    So far my checking with the media_view_settings fix hasn’t reveal any problems.

    After the post is uploaded the “insert post” button should update the editor. Attachments would have to be updated after the content is saved which is already the case.

    One other solution I didn’t mention for edit posts was to update the post id to the id of the post being edited. For new posts we could create an auto-draft post and use this id. This also would allow a preview for new posts which I was already thinking about. Both these still require the use of the media_view_settings filter.

    Anyway I’m about to see if my first solution works so wish me luck.

    One other thing…

    For the Featured Image Upload Image button on the WPUF Add Item form, there is a similar behaviour to the ‘upload image’ function via the insert media module.

    Is the fix likely to resolve this issue at the same time i.e. are they truly connected?

Viewing 15 replies - 1 through 15 (of 30 total)
  • The topic ‘Inserting Media Directly into Post with The Add Media Button’ is closed to new replies.