如何在 WordPress 简码中使用 AJAX? [英] How to Use AJAX in a WordPress Shortcode?

查看:31
本文介绍了如何在 WordPress 简码中使用 AJAX?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个代码来显示随机报价.一个人编写了一个函数来实现所有这些.但是由于某种原因通过 AJAX 更新数据不起作用.当您按下新报价"按钮时,没有任何反应.也许有人知道为什么?以下代码需要修正什么,以便当您点击新报价"时会加载新报价?

PHP

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

 

HTML 结构

在页面内容、小部件或模板文件中:

<p>我宁愿拥有自己的无知,也不愿拥有他人的知识,因为我有很多.<br/>——马克吐温,美国作家剧作家

<a id="newquote" class="button" href="#" title="给我一个新的!">新报价</a>

这显然可以根据自己的喜好进行调整,但就本示例而言,这就是我们要做的.
稍后我们将通过短代码生成上述内容.

jQuery

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

function ajaxQuote() {var theQuote = jQuery.ajax({类型:'POST',url: ajaxParams.themeURI+'js/ajax-load-quote.php',/* 将 ajax 加载的 php 的文件路径作为 $_POST 变量提供 */数据:{文件路径:ajaxParams.filePath},发送前:函数(){ajaxLoadingScreen(true,'#randomquotes');},成功:功能(数据){jQuery('#randomquotes').find('p').remove();jQuery('#randomquotes').prepend(data);},完成:函数(){ajaxLoadingScreen(false,'#randomquotes');}});返回报价;}/* 加载过程中要显示的画面,可选 */功能 ajaxLoadingScreen(switchOn,element) {/* 显示加载屏幕 */如果(开启){jQuery(''+元素).css({'位置':'相对'});var appendHTML = '<div class="附加的ajax-loading-screen"><img src="'+ajaxParams.themeURI+'images/ajax-loader.gif"alt="正在加载..." 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({'显示':'块','可见性':'可见','过滤器':'alpha(不透明度= 100)','-ms-filter': '"progid:DXImageTransform.Microsoft.Alpha(Opacity=100)"',不透明度":1"});} 别的 {/* 隐藏加载屏幕 */jQuery(''+element).children('.ajax-loading-screen').css({'展示': '','可见性':'','筛选': '','-ms-过滤器': '','不透明度':''});jQuery(''+元素).css({'位置': ''});}}/* 通过点击事件触发上面的 */jQuery('#newquotes').click(function() {var theQuote = ajaxQuote();返回假;});

functions.php

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

function random_quote( $atts ) {/* 提取简码参数路径的值 */提取(shortcode_atts(数组('路径' =>get_template_directory_uri() .'/quotes.txt'//默认,如果没有设置), $atts ) );$array = 文件( $path );$r = rand( 0, count($array) - 1 );$output = '

'.'<p>'.$array[$r] .'</p>'.'</div>'.'<a id="newquote" class="button" href="#" title="给我一个新的!">新报价</a>';/* 如果需要,将下面注册的脚本加入队列 */wp_enqueue_script('ajax-quote');/* 提供脚本的文件路径 */wp_localize_script('ajax 引用','ajax参数',大批('文件路径' =>$路径,'themeURI' =>get_template_directory_uri() .'/'));返回 $output;}add_shortcode( 'randomquotes', 'random_quote');/* 注册 js */函数 wpse72974_load_scripts() {如果(!is_admin()){wp_register_script('ajax 引用',get_template_directory_uri() .'/js/ajax-load-quote.js',数组('jquery'),'1.0',真的);}}add_action ('init', 'wpse72974_load_scripts');

如何在 WordPress 中使用 AJAX 更新页面上的内容?

解决方案

好问题!

但是,由于您的代码开始时的做法很糟糕 - require_once('wp-load.php'); -,我决定选择我的工作片段之一并对其进行调整.

观察:

  • 与您的代码不同,没有抓取外部quotes.txt,这里使用Post Type作为源(post),在方法 get_random_post
  • 在给定页面中只能有一个短代码实例,因为它基于特定的元素 ID(#newpost-shortcode#randomposts)
  • 像往常一样,最好为此创建一个插件.按照代码注释进行操作.

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

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' ) );}/*** 短代码输出*/公共函数简码( $atts ){# 第一次发帖if( ! $random_post = $this->get_random_post() )$random_post = __( '无法检索帖子.' );# 准备输出$输出 = sprintf('<div id="randomposts">%s</div><button id="newpost-shortcode" type="button" title="%s">%s</button>',$random_post,__( '给我一个新的!' ),__( '新的随机帖子' ));返回 $output;}/*** ACTION 入队脚本*/公共函数入队(){# jQuery 将作为依赖项加载## 请勿使用与 WP 捆绑的版本以外的其他版本### 如果你这样做,事情就会破裂wp_enqueue_script('ajax-random-post',"{$this->plugin_url}ajax.js",数组('jquery'));# 这里我们将 PHP 值发送给 JSwp_localize_script('ajax-random-post','wp_ajax',大批('ajaxurl' =>admin_url('admin-ajax.php'),'ajaxnonce' =>wp_create_nonce('ajax_post_validation'),'加载' =>'http://i.stack.imgur.com/drgpu.gif'));}/*** AJAX 查询随机发帖**检查安全性并发送正确的响应*/公共函数 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' => __( '无法检索帖子.' ) );别的wp_send_json_success( $random_post );}/*** 辅助功能* 搜索一个随机的帖子类型并返回 post_content*/公共函数 get_random_post(){$array = get_posts(大批('post_type' =>$this->cpt,'数字帖子' =>-1));如果(空($数组))返回假;# 从当前数组中随机选择一个帖子索引号$r = rand( 0, count($array) - 1 );返回 $array[$r]->post_content;}}

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

/** @plugin SO Ajax 简码*/jQuery( 文档 ).ready( 函数( $ ){变量数据 = {动作:'query_rand_post',安全性:wp_ajax.ajaxnonce};var image = '<img src="' + wp_ajax.loading + '" alt="加载中..." width="16" height="16"/>';$( '#newpost-shortcode' ).click( function(e){e.preventDefault();$('#randomposts').html(图片);$.post(wp_ajax.ajaxurl,数据,功能(响应){//错误处理如果(!响应.成功){//没有数据返回,可能是安全错误如果(!响应.数据)$( '#randomposts' ).html( 'AJAX 错误:无响应' );别的$( '#randomposts' ).html( response.data.error );}别的$( '#randomposts' ).html( response.data );});});//结束点击});

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 button "New Quote", nothing happens. Maybe someone knows why? What needs to be fixed in the following code, so that when you click "New quote" a new quote is loaded?

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>';
 ?>

The HTML Structure

In a page content, a widget or a template file:

<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>

This you can obviously adjust to your liking, but for the sake of this example, this is what we're going with.
We will generate the above via a shortcode later.

The 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;
});

functions.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' );

How you can update the content on the page using AJAX in WordPress?

解决方案

Nice question!

But, as your code starts with a bad practice - require_once('wp-load.php'); -, I decided to pick one of my working snippets and adapt it.

Observations:

  • Differently from your code, no external quotes.txt is being grabbed, here a Post Type is used as source (post), in the method get_random_post
  • There can only be one instance of the shortcode in a given page, as it is based on specific element ID's (#newpost-shortcode and #randomposts)
  • As usual, it's better to create a plugin for this. Follow the code comments.

/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
});

这篇关于如何在 WordPress 简码中使用 AJAX?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆