I make custom media up loader and its working perfectly on a meta field. In my media up loader there is no gallery option. But now I want to give an option for gallery on it. I search a lot and follow their steps but not succeed.
Here is my Code that working perfectly without gallery option:
var meta_image_frame_gallery;
// Runs when the image button is clicked.
jQuery('#additional_image_1').click(function(e){
// Prevents the default action from occuring.
e.preventDefault();
// If the frame already exists, re-open it.
if ( meta_image_frame_gallery ) {
meta_image_frame_gallery.open();
return;
}
// Sets up the media library frame
meta_image_frame_gallery = wp.media.frames.meta_image_frame_gallery = wp.media({
title: 'Upload Image',
button: { text: 'Upload Image' },
library: { type: 'image' },
});
Runs when an image is selected.
meta_image_frame_gallery.on('select', function(){
// Grabs the attachment selection and creates a JSON representation of the model.
var media_attachment = meta_image_frame_gallery.state().get('selection').first().toJSON();
// Sends the attachment URL to our custom image input field.
jQuery('#itv_additional_image_1').val(media_attachment.url);
});
// Opens the media library frame.
meta_image_frame_gallery.open();
});
And here is my code for gallery option:
var meta_image_frame_gallery;
// Runs when the image button is clicked.
jQuery('#additional_image_1').click(function(e){
// Prevents the default action from occuring.
e.preventDefault();
// If the frame already exists, re-open it.
if ( meta_image_frame_gallery ) {
meta_image_frame_gallery.open();
return;
}
// Sets up the media library frame
meta_image_frame_gallery = wp.media.frames.meta_image_frame_gallery = wp.media({
title: 'Upload Image',
button: { text: 'Upload Image' },
multiple: true,
library: { type: 'image' },
});
// Runs when an image is selected.
//meta_image_frame_gallery.on('select', function(){
//
// // Grabs the attachment selection and creates a JSON representation of the model.
// var media_attachment = meta_image_frame_gallery.state().get('selection').first().toJSON();
//
// // Sends the attachment URL to our custom image input field.
// jQuery('#itv_additional_image_1').val(media_attachment.url);
//});
// When an image is selected, run a callback.
meta_image_frame_gallery.on( 'select', function() {
var selection = meta_image_frame_gallery.state().get('selection');
selection.map( function( attachment ) {
attachment = attachment.toJSON();
// Do something with attachment.id and/or attachment.url here
jQuery('#itv_additional_image_1').val(selection.url);
});
});
// Opens the media library frame.
meta_image_frame_gallery.open();
});
First I want an option for gallery and second when I create a gallery, its short-code will appear on meta field and then i save it in db.
Please any give any guidance that help me out.
I figure it by more searching and found some links check them. Now gallery option is active in my media up loader.
Here is my Code now:
Just add three more params
frame: "post",
state: 'gallery-library',
multiple: true
in this line meta_image_frame_gallery = wp.media.frames.wp_media_frame = wp.media( {
Complete code:
meta_image_frame_gallery = wp.media.frames.wp_media_frame = wp.media( {
title: 'My Gallery',
frame: "post",
state: 'gallery-library',
library: {
type: 'image'
},
multiple: true
} );
And now its working perfectly
Related
Can someone show me a good example of how to call a PHP function with Ajax? I'm trying to save an image gallery (with dynamic number of images) to database in the admin settings section. The below code is incomplete or maybe with some errors. Please show me a good example or a better way:
<button type="button" class="btn btn-primary" onclick="jsAddSettingsFields()">Save Changes</button>
function jsAddSettingsFields(){
var elements = document.getElementsByTagName("img");
var urlsdata = new Array();
for (var i = 0, element; element = elements[i++];) {
if (elements[i].id == "idGalPic") {
urlsdata[i] = elements[i].src;
// now we have all image urls in array, now need to
// call add_settings_fields
var data = {
action: 'php_addsettingsfields',
p_urls: urlsdata //I think i need to JSON this
};
jQuery.post( "", function( data ) );
}
}
}//end of js function
<?php
add_action( 'wp_ajax_update_options', 'php_addsettingsfields_callback' );
add_action( 'wp_ajax_nopriv_update_options', 'php_addsettingsfields_callback' );
function php_addsettingsfields_callback() {
$pic_urls = $_POST['p_urls']; // De-JSON-fy this variable
foreach ($pic_urls as &$url) {
add_settings_field($url);
}
add_settings_field(
'pic_url_id', // ID - slug name of field
'', // Title
array( $this, 'pic_gal_callback' ), // Callback
'TestPlugin', // Page
'setting_section_id' // Section ID - slug name of page
);
public function pic_gal_callback() {
<input type="hidden" id="idPic" name="idPic" value=$url />
}
// after all hidden fields(with gallery pic urls) are added to setting section submit
// the page and save the gallery urls to database
Here take a look at a working ajax example from one of my plugins.
Javascript Part:
//setting click event on button click to fire a function
$('#YourButtonIdHere').click(function () {
YourFunctionNameHere();
});
//function to execute
function YourFunctionNameHere() {
//formdata variable consists of
//action: this is ajax action name for WordPress which we define in PHP with a callback function with same name. See in PHP code part.
//$('#YourFormIDHere').serialize(); //this gets content from form and serialize it.
var frm_data = "action=your_action_name_here&" + $('#YourFormIDHere').serialize();
$.ajax({
type: "POST",
url: ajaxurl, // since WordPress version 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php
data: frm_data,
cache: false,
success: function(data, textStatus, jqXHR) {
//do stuff here in case of success
},
error: function(jqXHR, textStatus, errorThrown) {
//do stuff here in case of error
}
});
}
PHP Part:
//here wp_ajax is the required prefix for your custom actions
//first parameter is action name with wp_ajax prefix
//second parameter is callback function to execute with same name as your action
//for example if your action name is wp_ajax_save_settings then your callback will be save_settings
add_action( 'wp_ajax_your_action_name_here', 'your_action_name_here' );
function your_action_name_here() {
global $wpdb; // this is how you get access to the database
//do stuff here and echo response
echo "ajax call success";
wp_die(); // this is required to terminate immediately and return a proper response
}
I am trying to create a wp type text editor to upload image and content for a post. So I've used summernote as a text editor.
What I am trying to achieve is, I want to send the post content i.e the text content and the media that are attached to the post at the same time. So that i can process it at the same time.
Following is my HTML Code.
<textarea name="post_content" id="post_content" class="form-control round post_content"></textarea>
I am using the following jQuery Code:
$('#post_content').summernote(
{
height: 300,
placeholder: "Type Your Post Content...",
toolbar: [
['style', ['style']],
['style', ['bold', 'italic', 'underline', 'strikethrough', 'superscript', 'subscript', 'clear']],
['fontname', ['fontname']],
['fontsize', ['fontsize']],
['color', ['color']],
['para', ['ul', 'ol', 'paragraph']],
['height', ['height']],
['table', ['table']],
['insert', ['link', 'picture', 'video', 'hr', 'readmore']],
['view', ['fullscreen', 'codeview']]
// ['help', ['help']]
],
callbacks:
{
onImageUpload: function(files, editor, welEditable)
{
for(var i = files.length - 1; i >= 0; i--)
{
sendFile(files[i], this);
}
}
}
});
function sendFile(file, el)
{
var form_data = new FormData();
form_data.append('file', file);
$.ajax({
data: form_data,
type: "POST",
url: '/image-upload.php',
cache: false,
contentType: false,
processData: false,
success: function(url) {
$(el).summernote('editor.insertImage', url);
}
});
}
The problem with the current code is that it's uploading the image directly to the server. I want to send the image and the content at the same time on a click of a button so that I can store the text code in DB and get the images out, process them in various size and store it in DB too.
But i am not able to figure out how can i achieve it.
As part of #cloudformatter, there is an option to embedLocalImages. This essentially uses jQuery to take some content, find all images, put them on a canvas, scrape them as base64 encoded data and then replace the image URL with the base64-encoded data. This was written only to embed images that are local in that project (meaning you are running in localhost) because it would send the data remote to be formatted and of course, the remote formatter has no idea where "http://localhost/myimage.jpg" is.
You can find it in the http://www.cloudformatter.com/CSS2PDF code, the relevant part is posted here for you. You could adopt a similar method to replace all the images with base64 equivalents as such the data would be inline.
Of course, you are storing long term which means that the images would not update if they changed at some http:// location. You could add something like a data-url attribute to store the original URL and if you bring the data back out for update, and use that URL to replace the base64 encoded data.
embedLocalImages: function(dest) {
jQuery(dest).find('img').each(function(index) {
var img = this;
var imageUrl = img.src;
if (imageUrl.indexOf(xepOnline.Formatter.getBase()) != -1){
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
canvas.height = img.height;
canvas.width = img.width;
ctx.drawImage(img,0,0, img.width, img.height);
var dataURL = canvas.toDataURL();
jQuery(img).attr('src', dataURL);
canvas = null;
}
});
},
I'm using the Laravel framework. I have a form of adding a new item to the database and in that form the user can also drag and drop a file. Then, a progress bar is displayed until it's completed, using Ajax for uploading the file to the server.
Once submitting that form, I run the addItem function in a controller and I want to do/check:
That the file is already hosted in the server (successful upload)
If the file is hosted in the server, how do I find it? (I gave it a random name)
If the user chose not to submit the form, I wish to erase that file from the server, so I won't have files that are not connected to any item on my database
Can you suggest any ideas on how to complete these tasks?
To send files by AJAX you need to use FormData which is a class of XMLHttpRequest2, it doesn't work with IE<10.
You also need AJAX2 to show progress.
SAMPLE SUBMIT FORM WITH FILES AND PROGRESS VIA AJAX:
Here I have made an example. In this example the form sends the data and files via AJAX using FormData and show the upload progress percentage in #progress using the progress event. Obviously it is a sample and it could be changed to adapt it.
$('form').submit(function(e) { // capture submit
e.preventDefault();
var fd = new FormData(this); // XXX: Neex AJAX2
// You could show a loading image for example...
$.ajax({
url: $(this).attr('action'),
xhr: function() { // custom xhr (is the best)
var xhr = new XMLHttpRequest();
var total = 0;
// Get the total size of files
$.each(document.getElementById('files').files, function(i, file) {
total += file.size;
});
// Called when upload progress changes. xhr2
xhr.upload.addEventListener("progress", function(evt) {
// show progress like example
var loaded = (evt.loaded / total).toFixed(2)*100; // percent
$('#progress').text('Uploading... ' + loaded + '%' );
}, false);
return xhr;
},
type: 'post',
processData: false,
contentType: false,
data: fd,
success: function(data) {
// do something...
alert('uploaded');
}
});
});
See how works!!: http://jsfiddle.net/0xnqy7du/3/
LARAVEL:
In laravel you can get the file with Input::file, move to another location and save in the database if you need it:
Input::file('photo')->move($destinationPath, $fileName);
// Sample save in the database
$image = new Image();
$image->path = $destinationPath . $fileName;
$image->name = 'Webpage logo';
$image->save();
I want to add an image input to my own WordPress plugin.
For that I use the standard WordPress media-uploader like so:
var custom_uploader;
$('.upload_image_button').click(function(e) {
input = $(this);
e.preventDefault();
custom_uploader = wp.media.frames.file_frame = wp.media({
title: 'Choose Collage Image',
library: {
type: 'image'
},
button: {
text: 'Choose Collage Image'
},
multiple: false,
displaySettings: true,
displayUserSettings: false
});
custom_uploader.on('select', function() {
attachment = custom_uploader.state().get('selection').first().toJSON();
input.prev('input').val(attachment.url);
});
custom_uploader.open();
});
This works perfect.
I add two more image sizes that were exact for my plugin:
if ( function_exists( 'add_image_size' ) ) {
add_image_size( 'collage-large', 460, 660, true );
add_image_size( 'collage-small', 460, 325, true );
}
My problem:
The selector for the image size or better the thumbnail selector is not shown at the media upload form. How do I do that?
You could use the media insertion dialog as shown on the "edit page" site, which adds alignment, link_to and size input fields. To do so add frame: 'post' to your options array:
file_frame = wp.media.frames.file_frame = wp.media({
title: 'Select a image to upload',
button: {
text: 'Use this image',
},
multiple: false,
frame: 'post', // <-- this is the important part
state: 'insert',
});
Instead of listening to the "select" event listen to the "insert" event. This code shows how retrieve the additional properties including the size:
// When an image is inserted, run a callback.
file_frame.on( 'insert', function(selection) {
var state = file_frame.state();
selection = selection || state.get('selection');
if (! selection) return;
// We set multiple to false so only get one image from the uploader
var attachment = selection.first();
var display = state.display(attachment).toJSON(); // <-- additional properties
attachment = attachment.toJSON();
// Do something with attachment.id and/or attachment.url here
var imgurl = attachment.sizes[display.size].url;
jQuery( '#filenameFromURL' ).val( imgurl );
});
I find some where in Internet. May be it useful.
attachment = custom_uploader.state().get('selection').first().toJSON();
With attachment you can working with:
alt
author
caption
compat ( <-- It is Object )
item
meta
date
dateFormatted
description
editLink
filename
height
icon
id
link
menuOrder
mime
modified
name
nonces ( <-- thi is object)
delete
update
proto
orientation
sizes ( <-- this is object)
full ( <-- this is object)
height
orientation
url
width
proto
medium ( <-- this is object)
height
orientation
url
width
proto
thumbnail ( <-- this is object)
height
orientation
url
width
proto
proto ( <-- this is object)
status
subtype
title
type
uploadedTo
url
width
To solve your problem I suggest use with case 20 above:
input.prev('input').val(attchment.sizes.collage-large.url);
Hope this work!
You're VERY close. To make the size selectable within the admin panel, review the add_image_size Codex Entry:
add_filter( 'image_size_names_choose', 'my_custom_sizes' );
function my_custom_sizes( $sizes ) {
return array_merge( $sizes, array(
'your-custom-size' => __('Your Custom Size Name'),
) );
}
So in your case, this should do what you need:
add_filter( 'image_size_names_choose', 'my_custom_sizes' );
function my_custom_sizes( $sizes ) {
return array_merge( $sizes, array(
'collage-large' => __('Collage Large'),
'collage-small' => __('Collage Small'),
) );
}
I really need some help here!
I have a page with images in groups of 1, 2, or 3. I click on an image and the class gets sent to some jquery ajax stuff to get the id(mysql) then this gets sent to a php file to build the html for the images to display on a div in my page. This bit works OK, but I'm trying to use the galleria plugin to show the image that haave been sent, but it just act like galleria is not there! If I hardcode some images in the dive. galleria works as it should!
here is my project.js file
// whenever a link with category class is clicked
$('a.project').click(function(e) {
// first stop the link to go anywhere
e.preventDefault();
// you can get the text of the link by converting the clicked object to string
// you something like 'http://mysite/categories/1'
// there might be other methods to read the link value
var linkText = new String(this);
// the value after the last / is the category ID
var projectvalue = linkText.substring(linkText.lastIndexOf('/') + 1);
// send the category ID to the showprojects.php script using jquery ajax post method
// send along a category ID
// on success insert the returned text into the shownews div
$.post('../inc/showprojects.php', {project: projectvalue}, function(data) {
$('#shownews').html(data);
});
});
This is my showproducts.php file
<?php
include 'connect.php';
// if no project was sent, display some error message
if(!isset($_POST['project'])) {
die('No project has been chosen');
}
// cast the project to integer (just a little bit of basic security)
$project = (int) $_POST['project'];
// this will be the string that you will return into the shownews div
$returnHtml = '';
$q = "SELECT * FROM projects WHERE id='$project'";
if($r = mysql_query($q)) {
// construct the html to return
while($row = mysql_fetch_array($r)) {
$returnHtml .= "<img src='{$row['filename']}' />";
$returnHtml .= "<img src='{$row['filename1']}' />";
$returnHtml .= "<img src='{$row['filename2']}' />";
}
}
// display the html (you actually return it this way)
echo $returnHtml;
?>
This is how I'm calling galleria on the div
// Load the classic theme
Galleria.loadTheme('../galleria/themes/classic/galleria.classic.min.js');
// Initialize Galleria
$('#shownews').galleria();
Can anyone help me out?
Thanks
try this one
// whenever a link with category class is clicked
$('a.project').click(function(e) {
// first stop the link to go anywhere
e.preventDefault();
// you can get the text of the link by converting the clicked object to string
// you something like 'http://mysite/categories/1'
// there might be other methods to read the link value
var linkText = new String(this);
// the value after the last / is the category ID
var projectvalue = linkText.substring(linkText.lastIndexOf('/') + 1);
// send the category ID to the showprojects.php script using jquery ajax post method
// send along a category ID
// on success insert the returned text into the shownews div
$.ajax({url:'../inc/showprojects.php',
type:'POST' ,
method,async:false ,
data:{project: projectvalue},
success:function(data) {
$('#shownews').html(data);
}});
Galleria.run('#shownews');
});
I think, you need to call Galleria.run after recieve data from php
EDIT: ugly way - destroy gallery, if already running before inserting new images into div
if($('#shownews').data('galleria')){$('#shownews').data('galleria').destroy()} //destroy, if allready running
$.post('../inc/showprojects.php', {project: projectvalue}, function(data) {
$('#shownews').html(data);
Galleria.run('#shownews');
});
and remove $('#shownews').galleria();
EDIT 2: use Galleria's .load api to load new data
// whenever a link with category class is clicked
$('a.project').click(function(e) {
// first stop the link to go anywhere
e.preventDefault();
// you can get the text of the link by converting the clicked object to string
// you something like 'http://mysite/categories/1'
// there might be other methods to read the link value
var linkText = new String(this);
// the value after the last / is the category ID
var projectvalue = linkText.substring(linkText.lastIndexOf('/') + 1);
// send the category ID to the showprojects.php script using jquery ajax post method
// send along a category ID
// on success insert the returned text into the shownews div
$.post('../inc/showprojects.php', {project: projectvalue},
function(data) {
$('#shownews').data('galleria').load(data);
},"json"
);
});
PHP
<?php
include 'connect.php';
// if no project was sent, display some error message
if(!isset($_POST['project'])) {
die('No project has been chosen');
}
// cast the project to integer (just a little bit of basic security)
$project = (int) $_POST['project'];
// this will be data array that you will return into galleria
$returnData = array();
$q = "SELECT * FROM projects WHERE id='$project'";
if($r = mysql_query($q)) {
// construct datat object to return
while($row = mysql_fetch_array($r)) {
$returnData[] = array('image'=>$row['filename']);
$returnData[] = array('image'=>$row['filename1']);
$returnData[] = array('image'=>$row['filename2']);
}
}
// return JSON
echo json_encode($returnData);
?>
Galleria init:
(Gallery will be empty until you will load data into it)
// Load the classic theme
Galleria.loadTheme('../galleria/themes/classic/galleria.classic.min.js');
// Initialize Galleria
Galleria.run('#shownews');
Try loading galleria after the ajax request has successfully completed. By doing this jquery waits until ShowNews has been rendered and then runs galleria.
$.ajax(
{
type: "POST",
url:'../inc/showprojects.php',
data:{project: projectvalue},
success: function(data)
{
$('#shownews').html(data);
},
complete: function()
{
Galleria.loadTheme('../galleria/themes/classic/galleria.classic.min.js');
$('#shownews').galleria();
}
});
I use this method whenever i gather the image data from a remote source. Hope this helps!
I tried this answer and other answers on the web and nothing worked. Then I moved galleria-1.3.5.min.js to the parent page and it worked. What an amazingly simple solution!