如何在 WordPress 短代码中使用 AJAX?

2024-04-21

我有一个代码来显示随机报价。有人编写了一个函数来实现这一切。但由于某种原因通过AJAX更新数据不起作用。当您按下“新报价”按钮时,什么也没有发生。也许有人知道为什么?以下代码中需要修复什么,以便当您单击“新报价”时加载新报价?

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

HTML 结构

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

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

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

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

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

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


好问题!

但是,由于您的代码以不好的做法开始 -require_once('wp-load.php');-,我决定选择我的一个工作片段并进行调整。

观察结果:

  • 与您的代码不同,无外部quotes.txt正在被抓取,这里使用帖子类型作为源(post),在方法中get_random_post
  • 只能有一个实例给定页面中的短代码,因为它基于特定元素 ID(#newpost-shortcode and #randomposts)
  • 照常,最好创建一个插件 https://wordpress.stackexchange.com/a/72183/12615为了这。按照代码注释操作。

/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'    => 'https://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
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 WordPress 短代码中使用 AJAX? 的相关文章

  • 如何在 Laravel 中基于 application/json 标头加载路由

    我正在使用application json标头来控制我的控制器在收到请求时的行为 我需要在单元测试中的 POST 中包含application json header 我试过了 public function testStore this
  • 为什么我的 Facebook 访问令牌突然停止工作? “OAuthException:验证访问令牌时出错。”

    我有一个 iframe Facebook 应用程序 它使用 Facebook PHP SDK 进行身份验证并进行 api 调用 在身份验证过程中 系统会提示用户输入基本信息和离线访问 如果他们允许我的应用程序访问 Facebook 会将它们
  • 使用月份、年份、星期几和周数计算月份中的某一天

    如何在 PHP 中计算月份中的某一天 并给出月份 年份 星期几和周数 例如 如果我有 2013 年 9 月 星期几是星期五 周数是 2 那么我应该得到 6 2013 年 9 月 6 日是第二周的星期五 实现此目的的一种方法是使用相对格式 h
  • PHP curl exec 在 php 脚本相同域上失败

    我使用 php curl 从同一域 url 中的 php 脚本获取内容 但我收到curl exec 错误 curl 错误代码为 28 或操作超时 经过几天的调试 我发现它可以在 htm 等非脚本页面上工作 但不能在 php 上工作 如果 u
  • 为什么将 MySQL 凭据放在 www 目录之外? [复制]

    这个问题在这里已经有答案了 可能的重复 将核心类放在 Web 根目录之上 好还是坏主意 https stackoverflow com questions 3648739 putting core classes above the web
  • ZipArchives 存储绝对路径

    我可以使用相对路径压缩文件吗 例如 zip gt addFile c wamp www foo file txt ZIP 应该具有如下目录结构 foo gt file txt and not wamp gt www gt foo gt fi
  • 不使用 PHP 提交联系表单

    我还是一名学生 今天我们的讲师告诉我们 无需使用 mailto 函数即可提交联系我们表单的唯一方法是使用 PHP 我发誓去年另一位讲师向我们展示了一种仅使用 javascript 的方法 是否可以使用基本表单和 javascript 提交反
  • 将 Node.js(用于实时通知)添加到现有 PHP 应用程序

    我有一个现有的 PHP 应用程序 我需要向其中添加实时通知 为了实现这一点 我安装了node js 打算添加socket io以实现所有实时功能 然而 尽管在过去的三个小时里研究并试图弄清楚如何将两者结合起来 但我发现自己并没有更接近于获得
  • MYSQL:SQL查询获取自增字段的值

    我有一张桌子 主键是id及其自动递增 现在 当我插入新记录时 我需要获取更新记录的 id 我怎样才能做到这一点 如果我使用查询 select max id from table name 执行后我可以获得id 但我能确定它是刚刚插入的记录的
  • 如果一个多维数组中的子数组与另一个多维数组不同,则覆盖该子数组

    我坚持这个问题 真的不知道如何解决 我有两个多维数组 需要将第二个数组中的每个 entry id 与第一个数组进行匹配 然后需要检查第二个数组中的每个 file no 是否在数据库 第一个数组 中 并且 status 是否与第一个数组匹配
  • 如何解决“无法加载PEM客户端证书,OpenSSL错误:02001003:系统库:fopen:没有这样的进程”错误?

    如果这个问题很愚蠢 请原谅 但我是这个领域的新手 我需要通过 SSL 从 Drupal 7 站点连接到服务 我有一个扩展名为 p12 的文件及其密码 另外 我使用 PHP 7 1 1 和 Windows 7 64x 我使用以下命令将 p12
  • 无需 cron 在后台发送邮件

    我想知道是否有一种方法可以运行 PHP 循环 以便在后台向订阅者发送几百封电子邮件 我的目标是格式化新闻通讯 单击发送 然后关闭浏览器或更改页面 当然 发送电子邮件的实际过程将在后台运行 不会因浏览器关闭而中断 我知道这可以通过 cron
  • 具有挑战性的问题 - 使用 PHP 对 XML 数据进行排序

    我有 xml 文件 其中包含大量产品数据 我需要根据我的字段 ProductRange 的数据对我的产品进行排序 ProductRange urldecode GET Range XML 文件数据
  • jquery ajax加载后丢失CSS

    大家知道如何解决 load Ajax 请求后的 css 问题吗 例如 如果我想从网页加载 DIV 在我的 Ajax 请求之后 container load path to div div id 我丢失了与该 div 关联的所有 css 和脚
  • Php 转换 GMT 格式的时间

    我有这个字符串2012 06 27 16 17 06我想将其转换为 GMT 格式 我怎样才能做到这一点 多谢 Use gmdate http php net manual en function gmdate php 使用以下命令将当前日期
  • PHP strtotime() 未返回正确的月份

    由于当前月份 年份是 2012 年 1 月 为什么以下代码返回 2011 年 12 月而不是 2011 年 11 月 echo date F Y strtotime 2 months 如果有影响的话 这是在 PHP 5 3 0 上 要获得您
  • 在 PHP 中设置 HTTP 响应代码(在 Apache 下)

    给出以下两种在 PHP 中设置 HTTP 响应代码的方法 具体来说 在 Apache 下 方法一 http response code 404 方法二 header HTTP 1 0 404 Not Found 我的问题是 除了这个事实之外
  • node-mongodb-native的插入性能

    我正在使用 MongoDB 测试 Node js 的性能 我知道其中每一个都很好 彼此独立 但我正在尝试一些测试来感受它们 我遇到了这个问题 但无法确定来源 问题 我正在尝试在单个 Node js 程序中插入 1 000 000 条记录 它
  • 如何使用 PHP 查找字符串中字符的序列模式?

    假设我有随机的文本块 EAMoAAQAABwEBAAAAAAAAAAAAAAABAgMFBgcIBAkBAQABBQEBAAAAAAAAAAAAAAAGAgMEBQcBCBAAAQMDAgMEBQcIBQgGCwEAAQACAxEEBSEG
  • 间歇性 PHP 抽象类错误

    我已经为此奋斗了一段时间 但无法弄清楚 也许其他人也有 或者 Slim PHP Apache 等这里有更深层次的问题 在正常工作几个小时后 我的 Slim 安装将开始给出所有路线均如此 致命错误 类 Slim Collection 包含 1

随机推荐