labur_add_metabox
is created, which contains a input de tipo text
empty and a button. labur_init
is also executed in which a js file is registered ( labur.js
). labur.js
file is executed when the user clicks on the id=button_labur_get_url
button
labur.js
the function labur_get_url_process
is executed, which must pick up the url of the current post and return it to the js file. Code of labur.php
//show metabox in post editing page
add_action('add_meta_boxes', 'labur_add_metabox' ); // Creación de metabox personlaizado
//load external files
add_action( 'add_meta_boxes', 'labur_init' ); // 'add_meta_boxes' tal vez no sea correcto. Tal vez sea mas correcto otro Hook
// add admin settings
add_action('wp_ajax_labur_get_url', 'labur_get_url_process'); // El prefijo wp_ajax es por convención de wordpress
// Función para procesar el AJAX
function labur_get_url_process() {
global $post;
echo get_permalink( $post->ID );
}
/**
* load external files
*/
function labur_init() {
//register plugin js file. Jquery is a requirement for this script so we specify it
wp_register_script( 'labur-js', plugins_url( '/labur.js', __FILE__ ), array('jquery') );
//load scripts
wp_enqueue_script('jquery');
wp_enqueue_script('labur-js');
}
function labur_add_metabox() {
//doc http://codex.wordpress.org/Function_Reference/add_meta_box
add_meta_box('labur_url', 'Bidalketaren labur.eus helbidea','labur_url_handler', 'post', 'side', 'high');
}
/**
* metabox handler
*/
function labur_url_handler() {
echo '<input type="text" id="labur_shortened_url" name="labur_direccion" readonly />';
echo '<p class="submit"><input id="button_labur_get_url" class="button button-primary button-large" name="labur_url" value="Sortu labur helbidea" type="button"/></p>';
}
Code labur.js
jQuery(document).ready(function($) {
jQuery("#button_labur_get_url").click(function(){
var url = document.location.protocol+'//'+document.location.host+'/aldakurnet/wp-admin/admin-ajax.php';
jQuery.ajax({
type: 'POST',
url: url,
dataType: 'text',
data: {
action: 'labur_get_url', // Ejecuta labur_get_url_process
},
success: function(data, textStatus, XMLHttpRequest){
$('#labur_shortened_url').val(data);
},
error: function(MLHttpRequest, textStatus, errorThrown){
alert(errorThrown);
}
});
});
});
labur_get_url_process
devuleve 0