Wordpress wp.media Upload image - php

Ok here is my code - stock standard and works if I simply select an existing image
jQuery(function($){
var file_frame;
$('#upload-button').on( 'click', function( e ){
e.preventDefault();
// If the media frame already exists, reopen it.
if ( file_frame ) {
file_frame.open();
return;
}
// Create a new media frame
file_frame = wp.media({
title: 'Select or Upload Media Of Your Chosen Persuasion',
button: {
text: 'Use this media'
},
multiple: false // Set to true to allow multiple files to be selected
});
file_frame.on('open', function(){
console.log("inside open");
});
file_frame.on('update', function(){
console.log("inside update");
});
file_frame.on('select', function(){
// This will return the selected image from the Media Uploader, the result is an object
var uploaded_image = file_frame.state().get('selection').first();
// We convert uploaded_image to a JSON object to make accessing it easier
// Output to the console uploaded_image
console.log(uploaded_image);
var image_url = uploaded_image.toJSON().url;
// Let's assign the url value to the input field
$('#image-url').val(image_url);
});
file_frame.open();
});
});
But if I goto drag and drop an image in there the image is uploaded but an error is returned
"An error occurred in the upload. Please try again later."
What have I missed, I'm assuming its some kind of refresh for the existing media selection window and my googling has not turned up anything.
Cheers
EDIT
I have tried several things to get the uploaded image to be shown in the media frame once uploaded. Not having much success.
As I said it appears the image is uploaded and added to the media library but I am missing a refresh or reload of the frame to show the image.
Any one have experience with or know another place to go look?

Maybe this call when everything is 'done':
if(wp.media.frame.library) wp.media.frame.library.props.set({ignore: (+ new Date())});
Or if you need to separate the library Grid modal from media upload (edit post) modal:
if(wp.media.frame.library){
wp.media.frame.library.props.set({ignore: (+ new Date())});
} else if(wp.media.frame.content.get().collection){
wp.media.frame.content.get().collection.props.set({ignore: (+ new Date())});
wp.media.frame.content.get().options.selection.reset();
}

Related

Limit wordpress gallery to post only

I've got a front-end uploader that allows users to upload images to a post. When they click the upload button that opens up the gallery they are able to see every image in the galllery, not just the ones tied to that specific post. I'd like to change that. I'd like when a user is in a post trying to upload an image, they can not see images tied to another post.
I've googled all I can think of and can't find a solution.
Here's my code:
var image_custom_uploader_2;
var $thisItem = '';
jQuery(document).on('click', '.avatar-upload-image', function(e) {
e.preventDefault();
$thisItem = jQuery(this);
//If the uploader object has already been created, reopen the dialog
if (image_custom_uploader_2) {
image_custom_uploader_2.open();
return;
}
//Extend the wp.media object
image_custom_uploader_2 = wp.media.frames.file_frame = wp.media({
title: 'Choose Image',
button: {
text: 'Choose Image'
},
multiple: false
});
console.log(image_custom_uploader_2);
//When a file is selected, grab the URL and set it as the text field's value
image_custom_uploader_2.on('select', function() {
attachment = image_custom_uploader_2.state().get('selection').first().toJSON();
var url = '';
url = attachment['url'];
var attachId = '';
attachId = attachment['id'];
$thisItem.parent().find('.listing-upload-gallery-image-data-url').val(url);
$thisItem.parent().find('.listing-upload-gallery-image-data-id').val(attachId);
$thisItem.parent().find(".gallery-image-holder").css("background-image", "url(" + url + ")");
$thisItem.parent().find(".avatar-upload-image").css("display", "none");
$thisItem.parent().find(".avatar-delete-image").css("display", "inline-block");
});
//Open the uploader dialog
image_custom_uploader_2.open();
});
jQuery(document).on('click', '.avatar-delete-image', function(e) {
jQuery(this).parent().find('.listing-upload-gallery-image-data-url').val('');
jQuery(this).parent().find('.listing-upload-gallery-image-data-id').val('');
jQuery(this).parent().find(".gallery-image-holder").css("background-image", "none");
jQuery(this).parent().find(".avatar-upload-image").css("display", "inline-block");
jQuery(this).css("display", "none");
});
I have a feeling I need to somehow incorporate one of the following:
uploadedTo :
post_parent :
but I'm not sure how to apply a post ID to them when this would be on a brand new, unsaved post
EDIT:
uploadedTo : wp.media.view.settings.post.id
uploadedTo : $post-id
Still allow all the other media items to be seen on the post's media library

issue including wp_enqueue_media - WordPress

I am building a custom interface that is utilizing WordPress functions and a specific area I am trying to utilize is the media section of WordPress. I am first including the core files of WordPress:
$location = $_SERVER['DOCUMENT_ROOT'] . "/wordpress";
include($location.'/wp-config.php');
include($location.'/wp-load.php');
include($location.'/wp-includes/pluggable.php');
global $wpdb;
if( !isset($wpdb) )
{
include($location.'/wp-config.php');
include($location.'/wp-includes/wp-db.php');
}
Than within my media file I am using: wp_enqueue_media() to allow me to access the media viewer for when a user is uploading media from their account.
My JS script I am using to run the media request is as follows:
$('.add-media').on('click', function( event ){
var file_frame;
var wp_media_post_id = wp.media.model.settings.post.id; // Store the old id
event.preventDefault();
// If the media frame already exists, reopen it.
if ( file_frame ) {
file_frame.open();
return;
}
// 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: true // Set to true to allow multiple files to be selected
});
// When an image is selected, run a callback.
file_frame.on( 'select', function() {
var selection = file_frame.state().get('selection');
selection.map( function( attachment ) {
attachment = attachment.toJSON();
// Do something with attachment.id and/or attachment.url here
$(".load-attachments").append('<div class="singleImg"><img src="'+attachment.url+'" width="100px" height="100px"/><input type="hidden" class="fileURL load-single-attachment" value="'+attachment.id+'"/><span class="removeImg remove"> X </span></div>');
$(".removeImg").bind('click', function(){
$(this).parent().remove();
});
});
});
// Finally, open the modal
file_frame.open();
});
The issue here is, when running the add-media event, wp is undefined. Now I am not sure as to why this is. Any thoughts or suggestions?
After looking through documentation, I couldn't really figure out why this was happening. But I found the solution. Some final files are called when using wp_footer(). And without this, none of your JavaScript files will run.
So In the future if your developing an application and want to use WordPress core functionalities, make sure to include wp_footer() at the end of your application to make sure you won't run into wp not being defined in js.

Can't retrieve variable from php

PHP FILE:
<?php
#Communication with the API
require_once 'api.php';
$cloudkey = new CloudKey($user_id, $api_key);
if(isset($_FILES["FileInput"]) && $_FILES["FileInput"]["error"]== UPLOAD_ERR_OK)
{
//Deleted Code: putting the uploaded files in my server.
if(move_uploaded_file($_FILES['FileInput']['tmp_name'], $UploadDirectory.$NewFileName ))
{
$video_file = "/home/george/public_html/q/";
$video_file = $video_file . $NewFileName;
#Sending the video from my server to the cloud server
$res = $cloudkey->file->upload_file($video_file);
#The cloud server will create a link
$source_url = $res->url;
#The cloud server will convert the video very fastly
while(1) {
#Deleted Code: Conversion
if ($asset->status == 'ready') {
# A lot of code. It will convert the videos here and if it succeeds it will stop.
break;
# If the conversion fails, display error
} else if ($asset->status == 'error') {
echo "Error while transcoding the media\n";
}
sleep(1);
}
# Getting the URL of a thumbnail
echo $thumb = $cloudkey->media->get_stream_url(array('id' => $media_id, 'asset_name' => 'jpeg_thumbnail_source'));
}else{
die('error uploading File!');
}
}
else
{
die('Something went wrong!');
}
?>
HTML FILE:
{literal}
<script type="text/javascript">
$(document).ready(function() {
var options = {
target: '#output', // target element(s) to be updated with server response
beforeSubmit: beforeSubmit, // pre-submit callback
success: afterSuccess, // post-submit callback
uploadProgress: OnProgress, //upload progress callback
resetForm: true // reset the form after successful submit
};
//function after succesful file upload (when server response)
function afterSuccess()
{
$('#loading-img').hide(); //hide submit button
$('#progressbox').fadeOut(); //hide progress bar
//I WANT TO INSERT SOMETHING HERE.
}
//progress bar function
function OnProgress(event, position, total, percentComplete)
{
//DOES NOT INTEREST YOU
});
</script>
{/literal}
<div id="output"></div>
I am using smarty template engine. I have an html upload form that will communicate with a php file progressupload.php where the php file will convert the video (using API services) and brings back a response when it finishes.
When the user uploads the video file, ajax will take over show the percentage (in html), and it will send the file to progressupload.php and when the progressupload.php finishes the conversion it will output everything echoed in the php by simply putting this in the html file (I don't know why): <div id="output"></div>.
WHAT I WANT:
When progressupload.php finishes the conversion, it will generate a thumbnail (screenshot) and store its link in $thumb. I want to retrieve $thumb and show it to the user using jquery.
Now if you look at the HTML Code, afterSuccess() is the function where I want to show the thumbnail to the user:
function afterSuccess()
{
$('#loading-img').hide(); //hide submit button
$('#progressbox').fadeOut(); //hide progress bar
//I WANT TO SHOW THE THUMBNAIL HERE.
}
I deleted a lot of unnecessary code that could've distracted you. Remember that I am using smarty template engine, my html file does not end with .php, I cannot echo the variable directly. How can I retrieve the php variable and put it in a jquery method after the variable is created.
I have a suspicion that if you retrieve the variable directly on page load, it will not succeed in getting $thumb since the link needs time to be created (uploading, conversion). How can I retrieve that $thumb?
Assuming that you are using jQuery.ajax();
First parameter in the $.ajax 'success' callback is what returned from the server side.
function afterSuccess( response /** this is what returned from your server **/ )
{
$('#loading-img').hide(); //hide submit button
$('#progressbox').fadeOut(); //hide progress bar
//I WANT TO INSERT SOMETHING HERE.
console.log(response); // here you can access your $thumbnail
// below code is untested but it should work
// $("#output").html("<img src='"+response+"' class='thumbnail' />");
}

Adding Attachment Display Settings in custom media frame

I made my own custom media frame :
$('.add').bind('click', function(event) {
event.preventDefault();
// Create the media frame.
file_frame = wp.media.frames.file_frame = wp.media({
title: 'Select image to insert',
button: {
text: 'Insert',
},
multiple: true
});
file_frame.open();
});
It opens the media manager alright but Attachement display setting part is missing. How can i get that?
Under title, you need to add frame: 'post' and on the callback, you should have frame.on('insert') not frame.on('select')

Jquery upload function doesn't work for multiple images on 1 page

How it works:
I'm trying to create an instant upload function with Jquery/Ajax. When a user double-clicks an image, a Fancybox shows up with the upload field. After choosing an image, the image is uploaded and the source of the clicked image is changed immediately.
The problem:
When having multiple images on one page, sometimes another image gets replaced by the new image (randomly).
The code:
function uploader(thumb) {
new AjaxUpload('imageUpload', {
action: 'uploader.php',
name: 'file',
onComplete: function(file, response) {
thumb.attr('src', response);
$.fancybox.close();
}
});
}
$("img").dblclick(function(){
var img = $(this);
$.fancybox({
href: '#imageUpload',
overlayShow: true
});
uploader(img);
return false;
});
What I've tried:
When I alert the ID of the image that should be replaced, it always alerts the correct ID of the image. And still it replaces another image instead.
Regards,
Bo
The way you're getting a reference to the clicked image is not good. You should extract the clicked element from the event object passed to the handler.
$('img').dblclick(function(event) {
var img = $(event.target);
...
});

Categories