- When the user enters to edit/create a post through the Wordpress admin, the metabox is created,
labur_add_metabox
which contains aninput de tipo text
empty space and a button. - The action
labur_init
in which a js file is registered (labur.js
) is also executed. - The file
labur.js
is executed when the user clicks on the buttonid=button_labur_get_url
- From
labur.js
the function is executedlabur_get_url_process
which must collect the url of the current post and return it to the js file.
labur.php code
//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 oflabur.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
returns 0
If you are in the WordPress admin section you should not use $post->ID but $_REQUEST["post"] .
The $post->ID is used as long as $post is loaded with the element generated by other functions like wp_query or get_posts.
The solution happens using
isset
inlabur_get_url_process
labur_ìnit
Send thelabur.js
an objectAjax
with thepost_id
and theaction
to execute.labur.js
receives the parameters and executeslabur_get_url_process
and then writes the result in ainput
conid=labur_shortened_url
labur.php code:
Code
labur.js