Selezionare un'immagine dalla Media Library di WordPress è un compito che jQuery svolge egregiamente interfacciandosi con le API JavaScript di WordPress.
Definiamo come prima cosa il seguente plugin:
<?php
/*
Plugin Name: My Image Shortcode
Version: 1.0
Description: Descrizione
Author: Gabriele Romanato
Author URI: http://gabrieleromanato.com
*/
// Creiamo il bottone
add_action( 'media_buttons','add_sc_button', 11 );
function add_sc_button() {
$html = '<a href="#" id="my-image-shortcode-btn">Scegli un'immagine</a>';
echo $html;
}
// Creiamo lo shortcode
function add_sc( $atts, $content = null ) {
extract( shortcode_atts( array(
'imageid' => '',
'size' => 'full'
), $atts ) );
// Reperiamo l'immagine tramite il suo ID
$id = (int) $imageid;
$img = wp_get_attachment_image_src( $id, $size );
$html = '<figure class="my-image"><img src="' . $img[0] . '" alt="" /></figure>';
return $html;
}
add_shortcode( 'my-image', 'add_sc' );
// Includiamo i file JavaScript e CSS
function add_sc_js() {
wp_enqueue_script( 'media-upload' );
wp_enqueue_script( 'thickbox' );
wp_register_script( 'my-image-shortcode', plugins_url() . '/my-image-shortcode/script.js', array( 'jquery' ), '1.0', false );
wp_enqueue_script( 'my-image-shortcode' );
wp_enqueue_style( 'thickbox' );
wp_register_style( 'my-image-shortcode', plugins_url() . '/my-image-shortcode/style.css' );
wp_enqueue_style( 'my-image-shortcode' );
}
add_action( 'admin_enqueue_scripts', 'add_sc_js' );
Quindi creiamo il codice jQuery per il file che abbiamo chiamato script.js
:
(function( $ ) {
var MyImage = function( element ) {
this.$element = $( element );
if( this.$element.length ) {
this.init();
}
};
MyImage.prototype = {
init: function() {
var self = this;
self.$element.click(function( e ) {
e.preventDefault();
if( wp.media.frames.gk_frame ) {
wp.media.frames.gk_frame.open();
} else {
wp.media.frames.gk_frame = wp.media({
title: "Seleziona immagine",
multiple: false,
library: {
type: "image"
},
button: {
text: "Usa immagine"
}
});
var selectMedia = function() {
var selection = wp.media.frames.gk_frame.state().get( "selection" );
if( !selection ) {
return;
}
selection.each(function( attachment ) {
var attrs = attachment.attributes;
var imageID = attrs.id;
send_to_editor( '[my-image imageid="' + imageID + '"]' );
});
};
wp.media.frames.gk_frame.on( "close", selectMedia );
wp.media.frames.gk_frame.open();
}
});
}
};
$(function() {
var myImageInstance = new MyImage( "#my-image-shortcode-btn" );
});
})( jQuery );
Il nostro codice inserirà lo shortcode come segue:
[my-image imageid="1234"]
Se volete invece usare un URL è sufficiente modificare il codice JavaScript quando avete ottenuto la proprietà attributes
dell'oggetto attachment
. Usate semplicemente console.log( attrs );
per una panoramica delle proprietà a disposizione.