Attaching media to post type without editor support - wordpress

I'm trying to add attachments to a custom post type that hasn't editor support (only excerpt).
I've managed to show the Media Manager dialog box, but I can only see the "Insert into post" button (that does nothing anyway) and when uploading images, they don't get attached to the post.
To implement what I did so far, I've added a very simple meta box to the post type:
function add_gallery_post_media_meta_box()
{
add_meta_box(
'gallery_post_media',
'Gallery Media',
'gallery_post_media',
'gallery',
'side',
'high'
);
} // add_file_meta_box
add_action('add_meta_boxes', 'add_gallery_post_media_meta_box');
function gallery_post_media()
{
echo '' . __('Add media') .'';
} // end post_media
function register_admin_scripts() {
wp_enqueue_media();
wp_register_script( 'gallery_post_media_admin_script', get_template_directory_uri() . '/library/cpt/gallery.js' );
wp_enqueue_script( 'gallery_post_media_admin_script' );
} // end register_scripts
add_action( 'admin_enqueue_scripts', 'register_admin_scripts' );
And the script:
jQuery(document).ready(function ($) {
$('#gallery-add-media').click(function (e) {
var send_attachment_bkp = wp.media.editor.send.attachment;
var button = $(this);
var id = button.attr('id').replace('_button', '');
wp.media.editor.send.attachment = function (props, attachment) {
$("#" + id).val(attachment.url);
wp.media.editor.send.attachment = send_attachment_bkp;
}
wp.media.editor.open(button);
event.preventDefault();
return false;
});
});
If I would able to find some documentation about wp.media.editor.send.attachment, I'd probably manage to get what I want, but I can't find anything useful.
The only solutions I've found all relies on custom fields, instead I want to simply attach these images to the post, without inserting them in the post content, as I would do with normal posts.
As a side question: is it possible to tell the Media Manager to only accept images?

This is the JavaScript I use for media fields. Once you hit insert you can do whatever you want with the data from the image's selected
jQuery(document).ready(function() {
//uploading files variable
var custom_file_frame;
jQuery(document).on('click', '.meida-manager', function(event) {
event.preventDefault();
$this = jQuery(this);
//If the frame already exists, reopen it
if (typeof(custom_file_frame)!=="undefined") {
custom_file_frame.close();
}
//Create WP media frame.
custom_file_frame = wp.media.frames.customHeader = wp.media({
//Title of media manager frame
title: "Sample title of WP Media Uploader Frame",
library: {
type: 'image'
},
button: {
//Button text
text: "insert text"
},
//Do not allow multiple files, if you want multiple, set true
multiple: false
});
//callback for selected image
custom_file_frame.on('select', function() {
var attachment = custom_file_frame.state().get('selection').first().toJSON();
//do something with attachment variable, for example attachment.filename
//Object:
//attachment.alt - image alt
//attachment.author - author id
//attachment.caption
//attachment.dateFormatted - date of image uploaded
//attachment.description
//attachment.editLink - edit link of media
//attachment.filename
//attachment.height
//attachment.icon - don't know WTF?))
//attachment.id - id of attachment
//attachment.link - public link of attachment, for example ""http://site.com/?attachment_id=115""
//attachment.menuOrder
//attachment.mime - mime type, for example image/jpeg"
//attachment.name - name of attachment file, for example "my-image"
//attachment.status - usual is "inherit"
//attachment.subtype - "jpeg" if is "jpg"
//attachment.title
//attachment.type - "image"
//attachment.uploadedTo
//attachment.url - http url of image, for example "http://site.com/wp-content/uploads/2012/12/my-image.jpg"
//attachment.width
$this.val(attachment.url);
$this.siblings('img').attr('src',attachment.url);
});
//Open modal
custom_file_frame.open();
});
});

Related

FullCalendar - Retrieve fileId of Attachments in Google Calendar

I'm hoping to find some help retrieving the Google Calendar attachment fileId through FullCalendar v2.9.0.
The Google calendar is dedicated to this project and is public as is the Drive folder containing image files which are the attachments - one image per event. I am new to the details of Javascript, but I've searched and researched quite a bit. I have not been able to find an example or tutorial that is close enough to what I'm trying to do that I can understand.
My project involves a month view FullCalendar where a user clicks an event, the event background highlights and a sidebar div populates with title, dateTime, description, location, and attachment image file. The user would browse through multiple events with the sidebar updating accordingly.
Here's what I've done so far:
The Google calendar elements are populating and updating correctly except for the image attachment.
I can hard code the HTML in gcal.html with a URL appended with the attachment fileId and get the image in the sidebar. The image, of course, is static though.
Using Google API Explorer calendar.events.get and entering calendarId, eventId, and simple API key, all of which are retrievable from FullCalendar, API Explorer returns the attachment fileId,
(Note that the fileUrl below works in a browser pulling up a viewer, but does not work in my HTML. This one does though: "https://drive.google.com/uc?export=view&id=0B5Nk_tOCzCISaWdqYy1DYnF6SzA")
From API Explorer
Execute without OAuth
calendar.events.get executed 16 minutes ago time to execute: 282 ms
Request
GET https://www.googleapis.com/calendar/v3/calendars/c6kag4dlhqs7m160s3t3lfggak%40group.calendar.google.com/events/u9a5fuoqkfmkm2c20vpn75krf4?fields=attachments(fileId%2CfileUrl)&key={YOUR_API_KEY}
Response
200
- Show headers -
{
"attachments": [
{
"fileUrl": "https://drive.google.com/file/d/0B5Nk_tOCzCISaWdqYy1DYnF6SzA/view?usp=drive_web",
"fileId": "0B5Nk_tOCzCISaWdqYy1DYnF6SzA"
}
]
}
I've tried what seems like endless combinations of statements, basically guessing, at the right syntax in a gcal.html eventClick function. I've also been trying to add code to events.push in gcal.js. This is the only place where I can find other event elements referenced.
My current setup with "alert(event.fileid);" under eventClick ingcal.html and "attachments: entry.fileid" under events.push in gcal.js returns an alert "undefined". In gcal.js a few lines down I notice "successArgs = [ events ].concat(Array.prototype.slice.call(arguments, 1)); // forward other jq args". I'm wondering if FullCalendar returns all fields for an event?
gcal.html (head)
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8' />
<link href='../fullcalendar.css' rel='stylesheet' />
<link href='../fullcalendar.print.css' rel='stylesheet' media='print' />
<script src='../lib/moment.min.js'></script>
<script src='../lib/jquery.min.js'></script>
<script src='../fullcalendar.min.js'></script>
<script src='../gcal.js'></script>
<script>
$(document).ready(function() {
$('#calendar').fullCalendar({
eventLimit: 4,
googleCalendarApiKey: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
events: {
googleCalendarId: 'c6kag4dlhqs7m160s3t3lfggak#group.calendar.google.com'
},
//$('#calendar'.fullCalendar( 'clientEvents' [, filter ] )
// Need to highlight next upcoming event on page load
// var filter = (events, event.start > getdate(new))
eventClick: function(event, events ) {
alert(event.fileid);
//eventRender: function(event, element, view) {
// Need to reset highlight on prevoiusly clicked event
// element.css('background-color', '#5777c8');
//}
//$('#calendar').fullCalendar( 'updateEvents' );
$( "#sidebar2" ).html(event.title);
$( "#sidebar3" ).html(event.start.format('dddd MMM. Do'));
$( "#sidebar4" ).html(event.start.format('h:mm a'));
$( "#sidebar5" ).html(event.description);
$( "#sidebar6" ).html(
'<a style= color:#a2cadc; href=http://' +
event.location + ' target="_blank">' +
"More Band Info" + '</a>'
);
$(this).css('background-color', '#5777c8');
return false;
console.log
},
loading: function(bool) {
$('#loading').toggle(bool);
}
});
});
</script>
gcal.js (line 122 to end)
return $.extend({}, sourceOptions, {
googleCalendarId: null, // prevents source-normalizing from happening again
url: url,
data: data,
startParam: false, // `false` omits this parameter. we already included it above
endParam: false, // same
timezoneParam: false, // same
success: function(data) {
var events = [];
var successArgs;
var successRes;
if (data.error) {
reportError('Google Calendar API: ' + data.error.message, data.error.errors);
}
else if (data.items) {
$.each(data.items, function(i, entry) {
var url = entry.htmlLink || null;
// make the URLs for each event show times in the correct timezone
if (timezoneArg && url !== null) {
url = injectQsComponent(url, 'ctz=' + timezoneArg);
}
events.push({
id: entry.id,
title: entry.summary,
start: entry.start.dateTime || entry.start.date,
// try timed. will fall back to all-day
end: entry.end.dateTime || entry.end.date, // same
url: url,
location: entry.location,
description: entry.description,
attachments: entry.fileid // tryiing to find the attachment reference
});
});
// call the success handler(s) and allow it to return a new events array
successArgs = [ events ].concat(Array.prototype.slice.call(arguments, 1));
// forward other jq args
successRes = applyAll(success, this, successArgs);
if ($.isArray(successRes)) {
return successRes;
}
}
return events;
}
});
}
// Injects a string like "arg=value" into the querystring of a URL
function injectQsComponent(url, component) {
// inject it after the querystring but before the fragment
return url.replace(/(\?.*?)?(#|$)/, function(whole, qs, hash) {
return (qs ? qs + '&' : '?') + component + hash;
});
}
});
Any help to get this working would be greatly appreciated.

CK Editor custom plugin to create a button

I have been trying to create a custom plugin to create a 'h1' button for the toolbar. Here is my plugin code -
"use strict";
var pluginName = 'customButtons';
CKEDITOR.plugins.add( 'customButtons', {
icons: 'h1_btn', // If you wish to have an icon...
init: function( editor ) {
// Tagname which you'd like to apply.
var tag = 'h1';
// Note: that we're reusing.
//style = new CKEDITOR.style( editor.config[ 'format_' + tag ] );
var style = new CKEDITOR.style( { element: 'h1' } );
// Creates a command for our plugin, here command will apply style. All the logic is
// inside CKEDITOR.styleCommand#exec function so we don't need to implement anything.
editor.addCommand( pluginName, new CKEDITOR.styleCommand( style ) );
// This part will provide toolbar button highlighting in editor.
editor.attachStyleStateChange( style, function( state ) {
!editor.readOnly && editor.getCommand( pluginName ).setState( state );
} );
// This will add button to the toolbar.
editor.ui.addButton( 'h1', {
label: 'Click to apply format',
command: 'customButtons',
toolbar: 'insert'
} );
}
} );
I added the plugin to config.js as well.
Any idea why this isn't working ?
Never mind. I figured out the answer. But letting the question be, in case some stumbles over with the same problem.
It turned out that ckeditor.editor.php has a bug (wrong directory name for plugin). I changed it back to the directory name in the folder structure and voila, it worked !!

Wordpress Image Uploader As Thumbnail

How can I convert the uploaded image to a 125x166px thumbnail?
// jQuery
wp_enqueue_script('jquery');
// This will enqueue the Media Uploader script
wp_enqueue_media();
var image = wp.media({
title: 'Upload Image',
multiple: false
}).open()
.on('select', function (e) {
// This will return the selected image from the Media Uploader, the result is an object
var uploaded_image = image.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;
});
});
You could use the wp_get_image_editor function.
Examples of how to use is available at: https://codex.wordpress.org/Function_Reference/wp_get_image_editor
But this is using PHP

Open/Access WP Media library from tinymce plugin popup window

I'm building a tinymce button plugin for the Wordpress (4) editor. The popup window that my button opens displays a form with several fields. One of them is for selecting an image inside the WP media library. I can't figure how to achieve this.
If that's not possible, what would be the best way to allow the user to select an image stored in the WP media library from a tinymce plugin popup window ?
FYI, the tinymce plugin inserts a shortcode with an image src as an attribute.
thanks !
I had the same problem just now and found the solution so I'm sharing it here. I hope it's not too late.
First to be able to use WP Add Media button you would have to enqueue the needed script. This is easy, just call the wp_enqueue_media() function like so:
add_action('admin_enqueue_scripts', 'enqueue_scripts_styles_admin');
function enqueue_scripts_styles_admin(){
wp_enqueue_media();
}
This call ensures you have the needed libraries to use the WP Media button.
Of course you should also have the HTML elements to hold the uploaded/selected media file URL, something like this:
<input type="text" class="selected_image" />
<input type="button" class="upload_image_button" value="Upload Image">
The first text field will hold the URL of the media file while the second is a button to open the media popup window itself.
Then in your jscript, you'd have something like this:
var custom_uploader;
$('.upload_image_button').click(function(e) {
e.preventDefault();
var $upload_button = $(this);
//Extend the wp.media object
custom_uploader = wp.media.frames.file_frame = wp.media({
title: 'Choose Image',
button: {
text: 'Choose Image'
},
multiple: false
});
//When a file is selected, grab the URL and set it as the text field's value
custom_uploader.on('select', function() {
var attachment = custom_uploader.state().get('selection').first().toJSON();
$upload_button.siblings('input[type="text"]').val(attachment.url);
});
//Open the uploader dialog
custom_uploader.open();
});
Now I'm not going to explain every line because it's not that hard to understand. The most important part is the one that uses the wp object to make all these to work.
The tricky part is making all these work on a TinyMCE popup(which is the problem I faced). I've searched hi and lo for the solution and here's what worked for me. But before that, I'll talk about what problem I encountered first. When I first tried to implement this, I encountered the "WP is undefined" problem on the popup itself. To solve this, you just have to pass the WP object to the script like so:
(function() {
tinymce.create('tinymce.plugins.someplugin', {
init : function(ed, url) {
// Register commands
ed.addCommand('mcebutton', function() {
ed.windowManager.open(
{
file : url + '/editor_button.php', // file that contains HTML for our modal window
width : 800 + parseInt(ed.getLang('button.delta_width', 0)), // size of our window
height : 600 + parseInt(ed.getLang('button.delta_height', 0)), // size of our window
inline : 1
},
{
plugin_url : url,
wp: wp
}
);
});
// Register buttons
ed.addButton('someplugin_button', {title : 'Insert Seomthing', cmd : 'mcebutton', image: url + '/images/some_button.gif' });
}
});
// Register plugin
// first parameter is the button ID and must match ID elsewhere
// second parameter must match the first parameter of the tinymce.create() function above
tinymce.PluginManager.add('someplugin_button', tinymce.plugins.someplugin);
})();
What we're interested in is this line => "wp: wp" . This line ensures that we are passing the wp object to the popup window (an iframe really...) that is to be opened when we click the tinymce button. You can actually pass anything to the popup window via this object (the 2nd parameter of the ed.windowManager.open method)!
Last but not the least you'd have to reference that passed wp object on your javascript like so:
var args = top.tinymce.activeEditor.windowManager.getParams();
var wp = args.wp;
Make sure you do that before calling/using the WP object.
That's all you have to do to make this work. It worked for me, I hope it works for you :)
I took the code of Paolo and simplified it in order not to have many files to manage. Also, I didn't manage to make it work like this.
So this solution has less code and uses only one single file.
Just put this in your tinyMCE plugins js file:
(function(){
tinymce.PluginManager.add('myCustomButtons', function(editor, url){
editor.addButton('btnMedia', {
icon: 'image',
tooltip: 'Add an image',
onclick: function() {
editor.windowManager.open({
title: 'Add an image',
body: [{
type: 'textbox',
subtype: 'hidden',
name: 'id',
id: 'hiddenID'
},
{
type: 'textbox',
name: 'text',
label: 'Text',
id: 'imageText'
},
{
type: 'button',
text: 'Choose an image',
onclick: function(e){
e.preventDefault();
var hidden = jQuery('#hiddenID');
var texte = jQuery('#imageText');
var custom_uploader = wp.media.frames.file_frame = wp.media({
title: 'Choose an image',
button: {text: 'Add an image'},
multiple: false
});
custom_uploader.on('select', function() {
var attachment = custom_uploader.state().get('selection').first().toJSON();
hidden.val(attachment.id);
if(!texte.val()){
if(attachment.alt)
texte.val(attachment.alt);
else if(attachment.title)
texte.val(attachment.title);
else
texte.val('See the image');
}
});
custom_uploader.open();
}
}],
onsubmit: function(e){
var image = '<button data-id="'+e.data.id+'">'+e.data.text+'</button>';
editor.insertContent(image);
}
});
}
});
});
})();
The result in the frontend html is a button which has the ID of the image in a data-id attribute, and a text to display (the alt of the image, by default, or its title or a text the user can write).
Then, with my frontend js, I will get the corresponding image with its ID and show it in an ajax popup.
With this solution, you have all of your js functions in one single file, and you don't need to enqueue any script nor to create a php file.
I know it's old but in case anyone else facing the same situation, The Paolo's solution above is working fine but no need to enqueue wp_enqueue_media(); this will load a bunch of scripts, you can load only 2 scripts:
wp_enqueue_script( 'jquery' );
wp_enqueue_script( 'media-lib-uploader-js' );

WordPress Custom Insert Into Post Button

For images uploaded using WordPress' media uploader, there is an "Insert Into Post" button that sends a shortcode to the editor for that image.
I have a text input that, when focused, I'd like the media uploader to appear so that the user can select an image and send the file URL to the text input.
The main issue I'm having is creating the additional "Insert Into Post" button that sends the file URL to the appropriate text field.
Which hook do I use for that and how can I get the file URL data returned to the input field?
Your guidance is appreciated!
What you've described is the older Wordpress way of doing it... If you want to use the new uploader in Wordpress 3.5+, you can create a wp.media object to upload it, similar to the code in wp-admin/js/custom-background.js:
// Create the media frame.
frame = wp.media.frames.customBackground = wp.media({
// Set the title of the modal.
title: $el.data('choose'),
// Tell the modal to show only images.
library: {
type: 'image'
},
// Customize the submit button.
button: {
// Set the text of the button.
text: $el.data('update'),
// Tell the button not to close the modal, since we're
// going to refresh the page when the image is selected.
close: false
}
});
// When an image is selected, run a callback.
frame.on( 'select', function() {
// Grab the selected attachment.
var attachment = frame.state().get('selection').first();
// Run an AJAX request to set the background image.
$.post( ajaxurl, {
action: 'set-background-image',
attachment_id: attachment.id,
size: 'full'
}).done( function() {
// When the request completes, reload the window.
window.location.reload();
});
});
// Finally, open the modal.
frame.open();
the frame.on('select' function(){ code is run when a file is chosen.
A litter further searching and I was able to find some good sources explaining how to do this. I went for a JavaScript, PHP mix:
JavaScript
$j('input').live('focusin',function(){
var target = '#'+$j(this).attr('id');
tb_show('','media-upload.php?post_id=[post_id]&tab=gallery&context=choose&TB_iframe=1');
window.send_to_editor = function(html) {
fileurl = $j(html).attr('href');
$j(target).val(fileurl);
tb_remove();
};
});
source: http://jaspreetchahal.org/wordpress-using-media-uploader-in-your-plugin/
PHP
/* Customize button */
function media_uploader_btn($form_fields, $post) {
$send = "<input type='submit' class='button' name='send[$post->ID]' value='" . esc_attr__( 'Choose This File' ) . "' />";
$form_fields['buttons'] = array('tr' => "\t\t<tr class='submit'><td></td><td class='savesend'>$send</td></tr>\n");
$form_fields['context'] = array( 'input' => 'hidden', 'value' => 'choose' );
return $form_fields;
}
/* Check for button context */
function check_upload_image_context($context){
if(isset($_REQUEST['context']) && $_REQUEST['context'] == $context){
return true;
} elseif(isset($_POST['attachments']) && is_array($_POST['attachments'])){
/* check for context in attachment objects */
$image_data = current($_POST['attachments']);
if (isset($image_data['context']) && $image_data['context'] == $context ){
return true;
}
}
return false;
}
if(check_upload_image_context('choose')){
add_filter('attachment_fields_to_edit', 'media_uploader_btn', 20, 2);
}
source: http://shibashake.com/wordpress-theme/how-to-hook-into-the-media-upload-popup-interface

Resources