Collect url from the post in wordpress

1
  • When the user enters to edit / create a post using the Wordpress admin, the metabox labur_add_metabox is created, which contains a input de tipo text empty and a button.
  • The action labur_init is also executed in which a js file is registered ( labur.js ).
  • The labur.js file is executed when the user clicks on the id=button_labur_get_url button
  • From 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

        
    asked by aldakur 12.04.2017 в 09:55
    source

    2 answers

    0

    The solution passes using isset in labur_get_url_process

  • labur_ìnit Send labur.js an object Ajax with post_id and action to execute.
  • The labur.js receives the parameters and executes labur_get_url_process to then write the result in a input with id=labur_shortened_url
  • Code of labur.php:

    <?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 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() {
        if(isset($_POST['postID'])) 
        {
          $post_id = $_POST['postID'];
          $post_url = get_permalink($post_id);
          echo $post_url;
        }
    
        exit();
    }
    
    /**
     * 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'); 
    
        global $post;
        $post_id = $post->ID;
        wp_localize_script('labur-js', 'MyAjax', array(
          'post_id' => $post_id,
          'action'=> 'labur_get_url' // labur_get_url es la acción pero sin el prefijo wp_ajax. Esta acción ejecutará la función labur_get_url_process
        ));
    
    }
    
    ?>
    

    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: {
                    postID: MyAjax.post_id, 
                    action: MyAjax.action 
                },
                success: function(data, textStatus, XMLHttpRequest){
                    $('#labur_shortened_url').val(data);
                },
                error: function(MLHttpRequest, textStatus, errorThrown){
                    alert(errorThrown);
                }
            });
        });
    });
    
        
    answered by 24.04.2017 / 10:50
    source
    0

    If you are in the Wordpress administration section you should not use $ post- & ID; $ _ REQUEST ["post"] .

    The $ post-> ID is used as long as $ post is loaded with the element generated by other functions such as wp_query or get_posts.

        
    answered by 14.04.2017 в 04:04