How to Use AJAX in a WordPress Shortcode?

后端 未结 5 1390
心在旅途
心在旅途 2020-11-22 08:51

I have a code to display a random quote. One person wrote a function to implement all of this. But the update data via AJAX for some reason does not work. When you press the

5条回答
  •  不知归路
    2020-11-22 09:18

    Here sample plugin as answer to the question. Using ajaxurl at frontend.

    so-random-quotes.php

     plugin_dir_path( __FILE__ ).'quotes.txt',
            ), $atts );
    
            // shortcode replacement
            $out = sprintf(
                        '
    %s
    New Quote', 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)]; } }

    quote-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');
        });
    });
    

提交回复
热议问题