WP Media Insert into Text Editor - wordpress

I have this code that does open Wordpress Media Uploader upon my custom button click and I have everything working from uploading image to selecting an image ... but how do I send the image/attachment to Text editor
jQuery(document).ready( function($){
var mediaUploader;
$('#_button').on('click',function(e) {
e.preventDefault();
if( mediaUploader ){
mediaUploader.open();
return;
}
mediaUploader = wp.media.frames.file_frame = wp.media( {
title : 'My Custom Library',
multiple : false,
library : { type : 'image' },
button : { text : 'Select Image' },
frame : 'post',
state : 'insert',
} );
mediaUploader.on('insert', function() {
var attachment = mediaUploader.state().get('selection').first().toJSON();
//WHAT TO DO HERE TO SEND THIS TO TEXT EDITOR??????
});
mediaUploader.open();
}); });

Found the answer myself from
https://core.trac.wordpress.org/browser/tags/4.9.8/src/wp-includes/js/media-editor.js#L852
mediaUploader.on('insert', function() {
var embed = mediaUploader.state().get( 'selection' ).first().toJSON();
_.defaults( embed, {
title: embed.url,
linkUrl: '',
align: 'none',
link: 'none'
});
if ( 'none' === embed.link ) {
embed.linkUrl = '';
} else if ( 'file' === embed.link ) {
embed.linkUrl = embed.url;
}
wp.media.editor.insert( wp.media.string.image( embed ) );
});

Related

Hide "Attributes" tab for a "Simple Product" type option

I have added a third checkmark option to the "Simple Product" tab, like this:
add_filter("product_type_options", function ($product_type_options) {
$product_type_options["personalize"] = [
"id" => "_personalize",
"wrapper_class" => "show_if_simple",
"label" => "Personalize",
"description" => "personalize Products",
"default" => "no",
];
return $product_type_options;
});
add_action("save_post_product", function ($post_ID, $product, $update) {
update_post_meta(
$product->ID
, "_personalize"
, isset($_POST["_personalize"]) ? "yes" : "no"
);
}, 10, 3);
I need to hide the "Attributes" tab when this custom "Personalize" checkbox is selected. ie., if you click on the "Virtual" option checkbox, the "Shipping" tab hides. Likewise, I need the "Personalize" option checkbox to hide the "Attributes" tab upon selection.
I have tried:
add_filter('woocommerce_product_data_tabs', 'misha_product_data_tabs' );
function misha_product_data_tabs( $tabs ){
$tabs['attribute']['class'][] = 'hide_if_personalize';
return $tabs;
}
But it is not working. Can you please help?
Check screenshot: https://snipboard.io/vhqMyA.jpg
First, you have to update the meta value on the checkbox change. then you can add class hide_if_personalize if meta value is yes using this woocommerce_product_data_tabs filter hook. check below code.
add_filter("product_type_options", function ( $product_type_options ) {
$product_type_options["personalize"] = [
"id" => "_personalize",
"wrapper_class" => "show_if_simple",
"label" => "Personalize",
"description" => "personalize Products",
"default" => "no",
];
return $product_type_options;
});
add_filter('woocommerce_product_data_tabs', 'misha_product_data_tabs' );
function misha_product_data_tabs( $tabs ){
$personalize = get_post_meta( get_the_ID() , "_personalize" , true );
if( $personalize == 'yes' ){
$tabs['attribute']['class'] = 'hide_if_personalize';
}
return $tabs;
}
add_action( 'wp_ajax_hide_attribute_if_personalize', 'hide_attribute_if_personalize' );
add_action( 'wp_ajax_nopriv_hide_attribute_if_personalize', 'hide_attribute_if_personalize' );
function hide_attribute_if_personalize(){
$personalize = $_POST['personalize'];
$product_id = $_POST['product_id'];
update_post_meta( $product_id, '_personalize', $personalize );
}
function add_custom_admin_js_css(){
?>
<style type="text/css">
li.attribute_options.attribute_tab.hide_if_personalize {
display: none !important;
}
</style>
<script type="text/javascript">
(function($){
$(document).ready(function(){
$( document ).on('change','#_personalize',function(){
var personalize = 'no';
if( $(this).is(":checked") ){
$('li.attribute_options.attribute_tab').addClass('hide_if_personalize');
personalize = 'yes';
}else{
$('li.attribute_options.attribute_tab').removeClass('hide_if_personalize');
}
$.ajax({
url: '<?php echo admin_url('admin-ajax.php'); ?>',
type: "post",
data: {personalize:personalize,product_id:$('#post_ID').val(),action:'hide_attribute_if_personalize'},
success: function( response ) {
},error: function (jqXHR, exception) {
var msg = '';
if (jqXHR.status === 0) {
msg = 'Not connect.\n Verify Network.';
} else if (jqXHR.status == 404) {
msg = 'Requested page not found. [404]';
} else if (jqXHR.status == 500) {
msg = 'Internal Server Error [500].';
} else if (exception === 'parsererror') {
msg = 'Requested JSON parse failed.';
} else if (exception === 'timeout') {
msg = 'Time out error.';
} else if (exception === 'abort') {
msg = 'Ajax request aborted.';
} else {
msg = 'Uncaught Error.\n' + jqXHR.responseText;
}
console.log(msg);
},
});
});
});
})(jQuery);
</script>
<?php }
add_action( 'admin_footer', 'add_custom_admin_js_css', 10, 1 );
Tested and works.
You can hide the "Attributes" tab via a jQuery script.
The showHideAttributeTab() script it will be activated when the page is loaded and when the "Personalize" checkbox is clicked.
It is also important to disable the <input> and <select> fields of the
add attributes form to ensure that they are not sent when saving the
product.
In fact, a user could add one or more attributes to the product, check the "Personalize" checkbox and finally save the product.
If you simply hide the elements, it is true that they will not be visible to the user, but they will still be captured by the Ajax function for saving attributes.
To prevent this it is necessary to disable any field of the Attributes tab. Then, after saving, all attributes will be removed if the "Personalize" checkbox is checked.
ADDITION
When the "Personalize" checkbox is unchecked, the "General" tab is
automatically activated.
Also, if the "Attributes" tab is active and the user selects "Personalize", it automatically activates the "General" tab to avoid white content.
// adds script in Wordpress backend to show or hide attribute tab based on custom field
add_action( 'admin_footer', 'show_hide_attribute_tab' );
function show_hide_attribute_tab() {
?>
<script type="text/javascript">
function showHideAttributeTab() {
if ( jQuery('#_personalize').is(':checked') ) {
jQuery('li.attribute_options.attribute_tab').hide();
jQuery('#product_attributes').hide();
// disable all fields of the "Attributes" tab
jQuery("#product_attributes input, #product_attributes select").each(function() {
jQuery(this).prop("disabled", true);
});
// if user enables "Attributes" tab, switch to general tab.
if ( jQuery( '.attribute_options.attribute_tab' ).hasClass( 'active' ) ) {
jQuery( '.general_options.general_tab > a' ).trigger( 'click' );
}
} else {
jQuery('li.attribute_options.attribute_tab').show();
jQuery('#product_attributes').show();
// enables all fields of the "Attributes" tab
jQuery("#product_attributes input, #product_attributes select").each(function() {
jQuery(this).prop("disabled", false);
});
// switch to general tab
jQuery("li.general_options.general_tab > a").trigger("click");
}
}
// runs the script when the page loads
showHideAttributeTab();
// runs the script when the "Personalize" checkbox is clicked
jQuery("#_personalize").click(function() {
showHideAttributeTab();
});
</script>
<?php
}
The code has been tested and works. Add it to your active theme's functions.php.

WordPress TinyMCE custom styles with input option

I want to add a custom style to the wordpress tiny mce. There are tons of tutorials for just adding a simple option like "highlight" which will add a span with a "highlight" class. Like: https://torquemag.io/2016/09/add-custom-styles-wordpress-editor-manually-via-plugin/
But what I need is an option to add additional data, like if you add a link. You mark the words, hit the link button, an input for the url shows up.
What I want to achieve? A custom style "abbriation" (https://get.foundation/sites/docs/typography-base.html). The solution I'm thinking of is, the user marks the word, chooses the abbriation style, an input for the descriptions shows up. fin.
Hope you can help me out!
So I have something similar in most of my WordPress projects. I have a TinyMCE toolbar button that has a couple of fields that output a bootstrap button.
What you need to do is create your own TinyMCE "plugin" and to achieve this you need two parts:
A javascript file (your plugin)
A snippet of PHP to load your javascript (plugin) into the TinyMCE editor.
First we create the plugin:
/js/my-tinymce-plugin.js
( function() {
'use strict';
// Register our plugin with a relevant name
tinymce.PluginManager.add( 'my_custom_plugin', function( editor, url ) {
editor.addButton( 'my_custom_button', {
tooltip: 'I am the helper text',
icon: 'code', // #link https://www.tiny.cloud/docs/advanced/editor-icon-identifiers/
onclick: function() {
// Get the current selected tag (if has one)
var selectedNode = editor.selection.getNode();
// If we have a selected node, get the inner content else just get the full selection
var selectedText = selectedNode ? selectedNode.innerHTML : editor.selection.getContent();
// Open a popup
editor.windowManager.open( {
title: 'My popup title',
body: [
// Create a simple text field
{
type: 'textbox',
name: 'field_name_textbox',
label: 'Field label',
value: selectedText || 'I am a default value' // Use the selected value or set a default
},
// Create a select field
{
type: 'listbox',
name: 'field_name_listbox',
label: 'Field list',
value: '',
values: {
'value': 'Option 1',
'value-2': 'Option 2'
}
},
// Create a boolean checkbox
{
type: 'checkbox',
name: 'field_name_checkbox',
label: 'Will you tick me?',
checked: true
}
],
onsubmit: function( e ) {
// Get the value of our text field
var textboxValue = e.data.field_name_textbox;
// Get the value of our select field
var listboxValue = e.data.field_name_listbox;
// Get the value of our checkbox
var checkboxValue = e.data.field_name_checkbox;
// If the user has a tag selected
if ( selectedNode ) {
// Do something with selected node
// For example we can add a class
selectedNode.classList.add( 'im-a-custom-class' );
} else {
// Insert insert content
// For example we will create a span with the text field value
editor.insertContent( '<span>' + ( textboxValue || 'We have no value!' ) + '</span>' );
}
}
} );
}
} );
} );
} )();
Now we add and modify the below snippet to your themes functions.php file.
/functions.php
<?php
add_action( 'admin_head', function() {
global $typenow;
// Check user permissions
if ( !current_user_can( 'edit_posts' ) && !current_user_can( 'edit_pages' ) ) {
return;
}
// Check if WYSIWYG is enabled
if ( user_can_richedit() ) {
// Push my button to the second row of TinyMCE actions
add_filter( 'mce_buttons', function( $buttons ) {
$buttons[] = 'my_custom_button'; // Relates to the value added in the `editor.addButton` function
return $buttons;
} );
// Load our custom js into the TinyMCE iframe
add_filter( 'mce_external_plugins', function( $plugin_array ) {
// Push the path to our custom js to the loaded scripts array
$plugin_array[ 'my_custom_plugin' ] = get_template_directory_uri() . '/js/my-tinymce-plugin.js';
return $plugin_array;
} );
}
} );
Make sure to update the file name and path if you it's different to this example!
WordPress uses TinyMCE 4 and the documentation for this is lacking so finding exactly what you need can be painful.
This is merely a starting point and has not been tested.
Hope this helps!
EDIT
The below code should help you with the insertion of an "abbreviations" tag and title attribute.
( function() {
'use strict';
tinymce.PluginManager.add( 'my_custom_plugin', function( editor, url ) {
editor.addButton( 'my_custom_button', {
tooltip: 'Insert an abbreviation',
icon: 'plus',
onclick: function() {
var selectedNode = editor.selection.getNode();
var selectedText = selectedNode ? selectedNode.innerHTML : editor.selection.getContent();
editor.windowManager.open( {
title: 'Insert an abbreviation',
body: [
{
type: 'textbox',
name: 'abbreviation',
label: 'The abbreviated term',
value: selectedText
},
{
type: 'textbox',
name: 'title',
label: 'The full term',
value: ''
}
],
onsubmit: function( e ) {
var abbreviation = e.data.abbreviation;
var title = e.data.title.replace( '"', '\"' );
if ( selectedNode && selectedNode.tagName === 'ABBR' ) {
selectedNode.innerText = abbreviation;
selectedNode.setAttribute( 'title', title );
} else {
editor.insertContent( '<abbr title="' + title + '">' + abbreviation + '</abbr>' );
}
}
} );
}
} );
} );
} )();

TypeError: window.tinyMCE.get(...) is null

I am getting the following error when trying to edit a Wordpress page in visual editor on http://www.domaine-audubert.com.
TypeError: window.tinyMCE.get(...) is null
window.tinyMCE.get( current_id ).setContent( content, {format: 'html'} );
The error seems to be located in wp-content/plugins/fusion-core/admin/page-builder/assets/js/js-wp-editor.js?ver=1.8.1 (line 173 col 7)
In that column I can find this code:
$(self).before('<link rel="stylesheet" id="editor-buttons-css" href="' + fusionb_vars.includes_url + 'css/editor.css" type="text/css" media="all">');
$(self).before(wrap);
$(self).remove();
new QTags(current_id);
QTags._buttonsInit();
switchEditors.go(current_id, options.mode);
if( content && options.mode == 'tmce' ) {
setTimeout( function() {
window.tinyMCE.get( current_id ).setContent( content, {format: 'html'} );
}, 1000);
}
$(wrap).on( 'click', '.insert-media', function( event ) {
var elem = $( event.currentTarget ),
editor = elem.data('editor'),
options = {
frame: 'post',
state: 'insert',
title: wp.media.view.l10n.addMedia,
multiple: true
};
event.preventDefault();
elem.blur();
if ( elem.hasClass( 'gallery' ) ) {
options.state = 'gallery';
options.title = wp.media.view.l10n.createGalleryTitle;
}
wp.media.editor.open( editor, options );
//hide insert from URL
$('.media-menu a:contains(Insert from URL)').remove();
});
}
});
}
})( jQuery, window )
But I have no idea where the error comes from. Is this a common problem and what can I do about it?

visual composer front editor not working

Hi I'm using Word press visual composer .. the problem is that with some pages(not all pages) , the front editor is not working , it just keep loading endlessly ,at first it wasn't working with all pages .. but when I added a blank page , Front editor worked with the blank page and some other pages , so what to do to make visual composer front editor works with these pages?
I'm using word press the 7 theme.
this is my suffering:
There may be many reasons for this but the root is js error.
1. at first disable page "preloader" and try.
2. If not working try disabling other plugins for wordpress which may have js conflict.
3. The best way: Have a look on console log for js error in browser's developer tools and fix them.
i had problem with visual. In my case helped when i changed on classic mode and return to backend editor.
This issue is mostly related to composer-view.js, I faced the same issue and it got resolved after following this link -
visual-composer-templateget-is-not-a-functi and Visual Composer is not working
You need to replace old code of composer-view.js as follow. (ps:- backup your old file before replacing this code.)
You can find this file at following location-
wp-content/plugins/js_composer/assets/js/backend
Old Code
html2element: function ( html ) {
var attributes = {},
$template;
if ( _.isString( html ) ) {
this.template = _.template( html );
$template = $( this.template( this.model.toJSON(), vc.templateOptions.default ).trim() );
} else {
this.template = html;
$template = html;
}
_.each( $template.get( 0 ).attributes, function ( attr ) {
attributes[ attr.name ] = attr.value;
} );
this.$el.attr( attributes ).html( $template.html() );
this.setContent();
this.renderContent();
}
Replace with new one as follows-
html2element:function (html) {
var attributes = {},
$template;
if (_.isString(html)) {
this.template = _.template(html);
} else {
try {
this.template = _.template(html());
} catch (err) {
this.template = html;
}
}
$template = $(this.template(this.model.toJSON()).trim());
_.each($template.get(0).attributes, function (attr) {
attributes[attr.name] = attr.value;
});
this.$el.attr(attributes).html($template.html());
this.setContent();
this.renderContent();
}
then also replace the Render Function
Old code
render: function () {
var $shortcode_template_el = $( '#vc_shortcode-template-' + this.model.get( 'shortcode' ) );
if ( $shortcode_template_el.is( 'script' ) ) {
this.html2element( _.template( $shortcode_template_el.html(),
this.model.toJSON(),
vc.templateOptions.default ) );
} else {
var params = this.model.get( 'params' );
$.ajax( {
type: 'POST',
url: window.ajaxurl,
data: {
action: 'wpb_get_element_backend_html',
data_element: this.model.get( 'shortcode' ),
data_width: _.isUndefined( params.width ) ? '1/1' : params.width,
_vcnonce: window.vcAdminNonce
},
dataType: 'html',
context: this
} ).done( function ( html ) {
this.html2element( html );
} );
}
this.model.view = this;
this.$controls_buttons = this.$el.find( '.vc_controls > :first' );
return this;
}
Replace with new code as follows-
render: function () {
var $shortcode_template_el = $( '#vc_shortcode-template-' + this.model.get( 'shortcode' ) );
if ( $shortcode_template_el.is( 'script' ) ) {
var newHtmlCode = _.template( $shortcode_template_el.html(),
this.model.toJSON(),
vc.templateOptions.default );
if(!_.isString(newHtmlCode)){
newHtmlCode = $shortcode_template_el.html();
}
this.html2element( newHtmlCode );
} else {
var params = this.model.get( 'params' );
$.ajax( {
type: 'POST',
url: window.ajaxurl,
data: {
action: 'wpb_get_element_backend_html',
data_element: this.model.get( 'shortcode' ),
data_width: _.isUndefined( params.width ) ? '1/1' : params.width,
_vcnonce: window.vcAdminNonce
},
dataType: 'html',
context: this
} ).done( function ( html ) {
this.html2element( html );
} );
}
this.model.view = this;
this.$controls_buttons = this.$el.find( '.vc_controls > :first' );
return this;
}

Improving FrontEnd Uploads in Wordpress

I want to improve the process of uploading pictures in a Real Estate Website. This website is running WordPress 3.8. The theme offers front end submission with a very simple interface. The user selects the images (one by one) and then clicks to add. Finally when the user submit the listing all the images are uploaded at once. This is the screenshot of how it looks: Original Option: Listing Images.
This is the JQuery Plugin I am currently using,
/*!
* jQuery imagesLoaded plugin v2.1.1
* http://github.com/desandro/imagesloaded
*
* MIT License. by Paul Irish et al.
*/
/*jshint curly: true, eqeqeq: true, noempty: true, strict: true, undef: true, browser: true */
/*global jQuery: false */
;(function($, undefined) {
'use strict';
// blank image data-uri bypasses webkit log warning (thx doug jones)
var BLANK = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==';
$.fn.imagesLoaded = function( callback ) {
var $this = this,
deferred = $.isFunction($.Deferred) ? $.Deferred() : 0,
hasNotify = $.isFunction(deferred.notify),
$images = $this.find('img').add( $this.filter('img') ),
loaded = [],
proper = [],
broken = [];
// Register deferred callbacks
if ($.isPlainObject(callback)) {
$.each(callback, function (key, value) {
if (key === 'callback') {
callback = value;
} else if (deferred) {
deferred[key](value);
}
});
}
function doneLoading() {
var $proper = $(proper),
$broken = $(broken);
if ( deferred ) {
if ( broken.length ) {
deferred.reject( $images, $proper, $broken );
} else {
deferred.resolve( $images );
}
}
if ( $.isFunction( callback ) ) {
callback.call( $this, $images, $proper, $broken );
}
}
function imgLoadedHandler( event ) {
imgLoaded( event.target, event.type === 'error' );
}
function imgLoaded( img, isBroken ) {
// don't proceed if BLANK image, or image is already loaded
if ( img.src === BLANK || $.inArray( img, loaded ) !== -1 ) {
return;
}
// store element in loaded images array
loaded.push( img );
// keep track of broken and properly loaded images
if ( isBroken ) {
broken.push( img );
} else {
proper.push( img );
}
// cache image and its state for future calls
$.data( img, 'imagesLoaded', { isBroken: isBroken, src: img.src } );
// trigger deferred progress method if present
if ( hasNotify ) {
deferred.notifyWith( $(img), [ isBroken, $images, $(proper), $(broken) ] );
}
// call doneLoading and clean listeners if all images are loaded
if ( $images.length === loaded.length ) {
setTimeout( doneLoading );
$images.unbind( '.imagesLoaded', imgLoadedHandler );
}
}
// if no images, trigger immediately
if ( !$images.length ) {
doneLoading();
} else {
$images.bind( 'load.imagesLoaded error.imagesLoaded', imgLoadedHandler )
.each( function( i, el ) {
var src = el.src;
// find out if this image has been already checked for status
// if it was, and src has not changed, call imgLoaded on it
var cached = $.data( el, 'imagesLoaded' );
if ( cached && cached.src === src ) {
imgLoaded( el, cached.isBroken );
return;
}
// if complete is true and browser supports natural sizes, try
// to check for image status manually
if ( el.complete && el.naturalWidth !== undefined ) {
imgLoaded( el, el.naturalWidth === 0 || el.naturalHeight === 0 );
return;
}
// cached images don't fire load sometimes, so we reset src, but only when
// dealing with IE, or image is complete (loaded) and failed manual check
// webkit hack from http://groups.google.com/group/jquery-dev/browse_thread/thread/eee6ab7b2da50e1f
if ( el.readyState || el.complete ) {
el.src = BLANK;
el.src = src;
}
});
}
return deferred ? deferred.promise( $this ) : $this;
};
})(jQuery);
My goal is to have a more flexible system, where all the images can be selected at the same time and it starts loading right away. This will speed up the process and improve user experience. Also to arrange them in any order by moving them around. This is an example I found on another website. See screenshot: New Option: Multiple Image Upload
What programing language is good for this development? Any recommendations of where I can find code snippets for this application? Thanks in advance for your help!!
rough draft.....you need jquery and wordpress media js..just watch the js variable names below if there are errors it will be with these...
php in functions file:
if(function_exists( 'wp_enqueue_media' )){
wp_enqueue_media();
}
javascript...add to the page header..wp_enqueue_scripts or to your template (do this first to make sure its working!) you'll need your element called upload_image_button or change accordinely
// Uploading files
var media_uploader;
jQuery('.upload_image_button').live('click', function( event ){
var button = jQuery( this );
// If the media uploader already exists, reopen it.
if ( media_uploader ) {
media_uploader.open();
return;
}
// Create the media uploader.
media_uploader = wp.media.frames.media_uploader = wp.media({
title: button.data( 'uploader-title' ),
// Tell the modal to show only images.
library: {
type: 'image',
query: false
},
button: {
text: button.data( 'uploader-button-text' ),
},
multiple: button.data( 'uploader-allow-multiple' )
});
// Create a callback when the uploader is called
media_uploader.on( 'select', function() {
var selection = media_uploader.state().get('selection'),
input_name = button.data( 'input-name' ),
bucket = $( '#' + input_name + '-thumbnails');
selection.map( function( attachment ) {
attachment = attachment.toJSON();
// console.log(attachment);
bucket.append(function() {
return '<img src="'+attachment.sizes.thumbnail.url+'" width="'+attachment.sizes.thumbnail.width+'" height="'+attachment.sizes.thumbnail.height+'" class="submission_thumb thumbnail" /><input name="'+input_name+'[]" type="hidden" value="'+attachment.id+'" />'
});
});
});
// Open the uploader
media_uploader.open();
});
template file:
<span class="upload_image_button alt_button" data-input-name="images" data-uploader- title="Upload Images" data-uploader-button-text="Add to Submission" data-uploader-allow-multiple="true">Upload</span>
php $_POST return
if ( !empty( $_POST['submission_images'] ) ) {
// do something with the files, set featured img, add to content or save post_meta
}
or..............i came across a plugin that does this a lot better........sorry its in OOP and designed on back end but you can modify for front end! The problem with multi file uploader from WP is it required users to hit "CTRL" + click with no guidance....massive problem on front-end forms...this one you can add more guidance to easily...sorry i havent a frontend sample yet, i have yet to create :)
"Multi File Upload"
e.g.
public function render_meta_box_content($post)
{
// Add an nonce field so we can check for it later.
wp_nonce_field('miu_inner_custom_box', 'miu_inner_custom_box_nonce');
// Use get_post_meta to retrieve an existing value from the database.
$value = get_post_meta($post->ID, '_ad_images', true);
$metabox_content = '<div id="miu_images"></div><input type="button" onClick="addRow()" value="Add Image" class="button" />';
echo $metabox_content;
$images = unserialize($value);
$script = "<script>
itemsCount= 0;";
if (!empty($images))
{
foreach ($images as $image)
{
$script.="addRow('{$image}');";
}
}
$script .="</script>";
echo $script;
}
save function
public function save_image($post_id)
{
/*
* We need to verify this came from the our screen and with proper authorization,
* because save_post can be triggered at other times.
*/
// Check if our nonce is set.
if (!isset($_POST['miu_inner_custom_box_nonce']))
return $post_id;
$nonce = $_POST['miu_inner_custom_box_nonce'];
// Verify that the nonce is valid.
if (!wp_verify_nonce($nonce, 'miu_inner_custom_box'))
return $post_id;
// If this is an autosave, our form has not been submitted,
// so we don't want to do anything.
if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE)
return $post_id;
// Check the user's permissions.
if ('page' == $_POST['post_type'])
{
if (!current_user_can('edit_page', $post_id))
return $post_id;
} else
{
if (!current_user_can('edit_post', $post_id))
return $post_id;
}
/* OK, its safe for us to save the data now. */
// Validate user input.
$posted_images = $_POST['miu_images'];
$miu_images = array();
foreach ($posted_images as $image_url)
{
if(!empty ($image_url))
$miu_images[] = esc_url_raw($image_url);
}
// Update the miu_images meta field.
update_post_meta($post_id, '_ad_images', serialize($miu_images));
}
js file
jQuery(document).ready(function(){
jQuery('.miu-remove').live( "click", function(e) {
e.preventDefault();
var id = jQuery(this).attr("id")
var btn = id.split("-");
var img_id = btn[1];
jQuery("#row-"+img_id ).remove();
});
var formfield;
var img_id;
jQuery('.Image_button').live( "click", function(e) {
e.preventDefault();
var id = jQuery(this).attr("id")
var btn = id.split("-");
img_id = btn[1];
jQuery('html').addClass('Image');
formfield = jQuery('#img-'+img_id).attr('name');
tb_show('', 'media-upload.php?type=image&TB_iframe=true');
return false;
});
window.original_send_to_editor = window.send_to_editor;
window.send_to_editor = function(html){
if (formfield) {
fileurl = jQuery('img',html).attr('src');
jQuery('#img-'+img_id).val(fileurl);
tb_remove();
jQuery('html').removeClass('Image');
} else {
window.original_send_to_editor(html);
}
};
});
function addRow(image_url){
if(typeof(image_url)==='undefined') image_url = "";
itemsCount+=1;
var emptyRowTemplate = '<div id=row-'+itemsCount+'> <input style=\'width:70%\' id=img- '+itemsCount+' type=\'text\' name=\'miu_images['+itemsCount+']\' value=\''+image_url+'\' />'
+'<input type=\'button\' href=\'#\' class=\'Image_button button\' id=\'Image_button- '+itemsCount+'\' value=\'Upload\'>'
+'<input class="miu-remove button" type=\'button\' value=\'Remove\' id=\'remove-'+itemsCount+'\' /></div>';
jQuery('#miu_images').append(emptyRowTemplate);
}

Resources