Comment utiliser AJAX dans un Shortcode WordPress?

j'ai un code pour afficher une citation aléatoire. Une personne a écrit une fonction pour mettre en œuvre tout cela. Mais les données de mise à jour via AJAX pour une raison quelconque ne fonctionne pas. Quand vous appuyez sur le bouton "nouvelle citation", rien ne se passe. Peut-être que quelqu'un sait pourquoi? Ce qui doit être fixé dans le code suivant, de sorte que lorsque vous cliquez sur "devis" un nouveau devis est chargé?

The PHP

/wp-content/themes/%your_theme%/js/ajax-load-quote.php

 <?php
 /* uncomment the below, if you want to use native WP functions in this file */
// require_once('../../../../wp-load.php');

 $array = file( $_POST['file_path'] ); // file path in $_POST, as from the js
 $r = rand( 0, count($array) - 1 );

 return '<p>' . $array[$r] . '</p>';
 ?>

la Structure HTML

dans un contenu de page, un widget ou un fichier de modèle:

<div id="randomquotes">
    <p>I would rather have my ignorance than another man’s knowledge,
       because I have so much more of it.<br />
       -- Mark Twain, American author & Playwright</p>
</div>
<a id="newquote" class="button" href="#" title="Gimme a new one!">New Quote</a>

cela, vous pouvez évidemment vous ajuster à votre goût, mais pour le plaisir de cet exemple, c'est ce que nous allons avec.

Nous générerons ce qui précède via un shortcode plus tard.

jQuery

/wp-content/themes/%your_theme%/js/ajax-load-quote.js

function ajaxQuote() {
    var theQuote = jQuery.ajax({
        type: 'POST',
        url: ajaxParams.themeURI+'js/ajax-load-quote.php',
        /* supplying the file path to the ajax loaded php as a $_POST variable */
        data: { file_path: ajaxParams.filePath },
        beforeSend: function() {
            ajaxLoadingScreen(true,'#randomquotes');
        },
        success: function(data) {
            jQuery('#randomquotes').find('p').remove();
            jQuery('#randomquotes').prepend(data);
        },
        complete: function() {
            ajaxLoadingScreen(false,'#randomquotes');
        }
    });
    return theQuote;
}
/* Loading screen to be displayed during the process, optional */
function ajaxLoadingScreen(switchOn,element) {
    /* show loading screen */
    if (switchOn) {
        jQuery(''+element).css({
            'position': 'relative'
        });
        var appendHTML = '<div class="ajax-loading-screen appended">
            <img src="'+ajaxParams.themeURI+'images/ajax-loader.gif"
                alt="Loading ..." width="16" height="16" /></div>';
        if( jQuery(''+element).children('.ajax-loading-screen').length === 0 ) {
            jQuery(''+element).append(appendHTML);
        }
        jQuery(''+element).children('.ajax-loading-screen').first().css({
            'display': 'block',
            'visibility': 'visible',
            'filter': 'alpha(opacity=100)',
            '-ms-filter': '"progid:DXImageTransform.Microsoft.Alpha(Opacity=100)"',
            'opacity': '1'
        });
    } else {
        /* hide the loading screen */
        jQuery(''+element).children('.ajax-loading-screen').css({
            'display': '',
            'visibility': '',
            'filter': '',
            '-ms-filter': '',
            'opacity': ''
        });
        jQuery(''+element).css({
            'position': ''
        });
    }
}
/* triggering the above via the click event */
jQuery('#newquotes').click( function() {
    var theQuote = ajaxQuote();
    return false;
});

des fonctions.php

/wp-content/themes/%your_theme%/functions.php

function random_quote( $atts ) {
    /* extracts the value of shortcode argument path */
    extract( shortcode_atts( array(
        'path' => get_template_directory_uri() . '/quotes.txt' // default, if not set
    ), $atts ) );
    $array = file( $path );
    $r = rand( 0, count($array) - 1 );
    $output = '<div id="randomquotes">' .
            '<p>' . $array[$r] . '</p>' .
        '</div>' .
        '<a id="newquote" class="button" href="#" title="Gimme a new one!">New Quote</a>';
    /* enqueue the below registered script, if needed */
    wp_enqueue_script( 'ajax-quote' );
    /* supplying the file path to the script */
    wp_localize_script(
        'ajax-quote',
        'ajaxParams',
        array(
            'filePath' => $path,
            'themeURI' => get_template_directory_uri() . '/'
        )
    );
    return $output;
}
add_shortcode( 'randomquotes', 'random_quote');
/* register the js */
function wpse72974_load_scripts() {
    if ( ! is_admin() ) {
        wp_register_script(
           'ajax-quote', 
            get_template_directory_uri() . '/js/ajax-load-quote.js',
            array( 'jquery' ),
            '1.0',
            true
        );
    }
}
add_action ( 'init', 'wpse72974_load_scripts' );

comment mettre à jour le contenu sur la page en utilisant AJAX dans WordPress?

62
demandé sur brasofilo 2012-11-21 21:39:16

5 réponses

Belle question!

mais, comme votre code commence par une mauvaise pratique - require_once('wp-load.php'); -, j'ai décidé de choisir un de mes extraits de travail et de l'adapter.

Observations :

  • différemment de votre code , aucun quotes.txt externe est saisi, ici un type de poteau est utilisé comme source ( post ), dans la méthode get_random_post
  • il ne peut y avoir qu'une seule instance du shortcode dans une page donnée, car elle est basée sur des ID d'éléments spécifiques ( #newpost-shortcode et #randomposts )
  • comme d'habitude, il est préférable de créer un plugin pour cela. Suivez les commentaires du code.

/wp-content/plugins/so-ajax-shortcode/so-ajax-shortcode.php

<?php
/**
 * Plugin Name: (SO) Ajax Shortcode
 * Description: Demonstration of WordPress Ajax working as a shortcode.
 * Plugin URI:  http://stackoverflow.com/a/13614297/1287812
 * Version:     2013.10.25
 * Author:      Rodolfo Buaiz
 * Author URI:  https://wordpress.stackexchange.com/users/12615/brasofilo
 * License:     GPLv3
 */

add_action(
    'plugins_loaded',
    array ( B5F_SO_13498959::get_instance(), 'plugin_setup' )
);

class B5F_SO_13498959
{
    private $cpt = 'post'; # Adjust the CPT
    protected static $instance = NULL;
    public $plugin_url = '';
    public function __construct() {}

    public static function get_instance()
    {
        NULL === self::$instance and self::$instance = new self;
        return self::$instance;
    }

    /**
     * Regular plugin work
     */
    public function plugin_setup()
    {
        $this->plugin_url = plugins_url( '/', __FILE__ );
        add_shortcode( 'randomposts', array( $this, 'shortcode') );
        add_action( 'wp_enqueue_scripts', array( $this, 'enqueue' ) );
        add_action( 'wp_ajax_query_rand_post', array( $this, 'query_rand_post' ) );
        add_action( 'wp_ajax_nopriv_query_rand_post', array( $this, 'query_rand_post' ) );
    }

    /**
     * SHORTCODE output
     */
    public function shortcode( $atts ) 
    {
        # First post
        if( ! $random_post = $this->get_random_post() )
            $random_post = __( 'Could not retrieve a post.' );
        # Prepare output
        $output = sprintf(
            '<div id="randomposts">%s</div>
             <button id="newpost-shortcode" type="button" title="%s">%s</button>',
            $random_post,
            __( 'Gimme a new one!' ),
            __( 'New random post' )
        );
        return $output;
    }

    /**
     * ACTION Enqueue scripts
     */
    public function enqueue() 
    {
        # jQuery will be loaded as a dependency
        ## DO NOT use other version than the one bundled with WP
        ### Things will BREAK if you do so
        wp_enqueue_script( 
             'ajax-random-post',
             "{$this->plugin_url}ajax.js",
             array( 'jquery' )
        );
        # Here we send PHP values to JS
        wp_localize_script( 
             'ajax-random-post',
             'wp_ajax',
             array( 
                 'ajaxurl'      => admin_url( 'admin-ajax.php' ),
                 'ajaxnonce'   => wp_create_nonce( 'ajax_post_validation' ),
                 'loading'    => 'http://i.stack.imgur.com/drgpu.gif'
            ) 
        );
    }

    /**
     * AJAX query random post
     * 
     * Check for security and send proper responses back
     */
    public function query_rand_post()
    {
        check_ajax_referer( 'ajax_post_validation', 'security' );
        $random_post = $this->get_random_post();
        if( !isset( $random_post ) )
            wp_send_json_error( array( 'error' => __( 'Could not retrieve a post.' ) ) );
        else
            wp_send_json_success( $random_post );
    }

    /**
     * AUX FUNCTION 
     * Search a random Post Type and return the post_content
     */
    public function get_random_post()
    {
        $array = get_posts( 
            array( 
                  'post_type' => $this->cpt,
                  'numberposts' => -1 
            ) 
        );
        if( empty( $array ) )
            return false;

        # Select a random post index number from the current array
        $r = rand( 0, count($array) - 1 );
        return $array[$r]->post_content;
    }
}

/wp-content/plugins/so-ajax-shortcode / ajax.js

/* 
 * @plugin SO Ajax Shortcode
 */

jQuery( document ).ready( function( $ ) 
{ 
     var data = {
         action: 'query_rand_post',
         security: wp_ajax.ajaxnonce
     };
     var image = '<img src="' + wp_ajax.loading + '" alt="Loading ..." width="16" height="16" />';

    $( '#newpost-shortcode' ).click( function(e) 
    {
        e.preventDefault();
        $( '#randomposts' ).html( image );
        $.post( 
            wp_ajax.ajaxurl, 
            data,                   
            function( response )
            {
                // ERROR HANDLING
                if( !response.success )
                {
                    // No data came back, maybe a security error
                    if( !response.data )
                        $( '#randomposts' ).html( 'AJAX ERROR: no response' );
                    else
                        $( '#randomposts' ).html( response.data.error );
                }
                else
                    $( '#randomposts' ).html( response.data );
            }
        ); 
    }); // end click
});
60
répondu brasofilo 2017-04-13 12:37:28

voici un exemple de plugin comme réponse à la question. Utilisation d ' ajaxurl chez frontend.

soi-aléatoire-citations.php

<?php
/*
Plugin Name: SO Random Quotes
Plugin URI: http://azzrael.ru
Description: Reference to /q/how-to-use-ajax-in-a-wordpress-shortcode-22791/"%s">%s</div><a id="newquote" class="button" href="#" title="Gimme a new one!">New Quote</a>',
                    self::DOM_TARGET,
                    $this->getQuote($got['path'])
               );

        // loading js
        // jquery depends
        wp_enqueue_script('sorandquo-js', plugin_dir_url( __FILE__ ).'quote-loader.js', array('jquery'));
        // passing to js needed vars
        wp_localize_script( 'sorandquo-js', 'ajaxParams',
            array(
                'path'      => $got['path'], // path to qoutes file
                'targetDom' => '#'.self::DOM_TARGET, // dom path to put resulting qoute
                'ajaxurl'   => admin_url( 'admin-ajax.php'), // for frontend ( not admin )
                'action'    => self::AJAX_ACTION, //
            )
        );

        // render shortcode replacement
        return $out;
    }

    /**
     * Ajax Callback
     */
    public function getQuoteAjax(){
        echo $this->getQuote($_POST['path']);
        die();
    }

    /**
     * Getting random Qoute from the file
     * @param $path
     * @return mixed
     */
    public function getQuote($path){
        $quotesFile = is_file($path) ? file_get_contents($path):"File {$path} not found";
        $quotesArr = $quotesFile ? explode("\n", $quotesFile):['Quotes File is empty'];
        return $quotesArr[array_rand($quotesArr)];
    }

}

citation-loader.js

jQuery.noConflict();
jQuery(document).ready(function($) {
    $(document).on('click', '#newquote', function (e) {
        e.preventDefault();

        $.post(ajaxParams.ajaxurl, {
            'action':ajaxParams.action,
            'path'  :ajaxParams.path
        }, function (ret) {
            $(ajaxParams.targetDom).html(ret);
        }, 'html');
    });
});
5
répondu Azzrael 2016-12-25 19:26:02

WordPress shortcode même fonction comme où vous donnez des paramètres,

pour créer une requête ajax, vous pouvez utiliser jQuery.ajax ou xmlhttp dans votre fichier d'en-tête ou de fonction avec add_action wp_head hook.

vous devez créer ajax.php dans votre dossier thématique et en haut du fichier, vous devez inclure wp-load.php. et placez toutes vos fonctions ajax de manière appropriée.

0
répondu Arsalan Azhar 2013-11-13 07:56:33

le sélecteur utilisé dans la gâchette ne correspond pas au bouton ID.

changer jQuery('#newquotes') en jQuery('#newquote')

0
répondu Dedering 2017-09-28 15:03:15

Ajouter cette fonction dans la fonction.php:

<?php
    add_action('wp_head','ajaxurl');
    function ajaxurl()
    {
    ?>
        <script type="text/javascript">
        var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
        </script>
    <?php
    }?>
-2
répondu Heena Patel 2017-07-11 12:15:33