概述
这里的例子插件作为问题的答案。在前面使用ajaxurl。
所以-随机-引号.php<?php /*
Plugin Name: SO Random Quotes
Plugin URI: http://azzrael.ru
Description: Reference to http://stackoverflow.com/questions/13498959/how-to-use-ajax-in-a-wordpress-shortcode
Version: 1.0.0
Author: Azzrael
Author URI: http://azzrael.ru
*/new SoRandomQuotes();/**
* Class SoRandomQuotes
*/class SoRandomQuotes{
const SHORTCODE_KEY = 'randomquotes'; // usage [randomquotes path='/path/to/file/another.quotes.csv']
const AJAX_ACTION = 'so_getnewquote'; // ajax action
const DOM_TARGET = 'randomquotes'; // dom element to put the quotes
/**
* SoRandomQuotes constructor.
* init actions
*/
function __construct() {
// adding shortcode
add_shortcode('randomquotes', array($this, 'addShortcode'));
// adding ajax callbacks
add_action( 'wp_ajax_'.self::AJAX_ACTION, array($this, 'getQuoteAjax')); // admin
add_action( 'wp_ajax_nopriv_'.self::AJAX_ACTION, array($this, 'getQuoteAjax')); // front
}
/**
* Shortcode callback
* @param $atts
* @return string
*/
public function addShortcode($atts){
// getting path value from shortcode atts
$got =shortcode_atts( array(
'path' => plugin_dir_path( __FILE__ ).'quotes.txt',
), $atts );
// shortcode replacement
$out = sprintf(
'
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)];
}}
报价-loader.jsjQuery.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');
});});
最后
以上就是糊涂白昼为你收集整理的wordpress调用ajax刷新,如何在WordPress短代码中使用Ajax?的全部内容,希望文章能够帮你解决wordpress调用ajax刷新,如何在WordPress短代码中使用Ajax?所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复