简体   繁体   English

WordPress的:通过jQuery运行PHP脚本

[英]Wordpress: run php script via jquery

I try run php script from external file on wordpress site. 我尝试从wordpress网站上的外部文件运行php脚本。

Example: 例:

jQuery: jQuery的:

jQuery('.button').click(function(){
  jQuery(this).parent('.entry_card').append('<div class="static"></div>');
  jQuery(this).parent('.entry_card').children('.static').load("insert.php");
});

insert.php: insert.php:

<?php 
echo date("d.m.Y h:i:s"); //for testing

echo the_title(); //wordpress post title

if( get_field('xxx') ) { insert_cform('1'); } //some order form
else { insert_cform('2'); }
?>

Date is inserted correctly, but rest of the script don't working. 日期已正确插入,但脚本的其余部分不起作用。 I'm noob in coding, sorry if my question is stupid. 我在编码方面没有菜鸟,对不起,如果我的问题很愚蠢。

Wordpress AJAX isn't handled like that. Wordpress AJAX不是那样处理的。 There's nothing loading your WordPress environment so functions like the_title() don't exist (you're probably getting a fatal error there). 没有任何内容可加载WordPress环境,因此不存在the_title()类的功能(您可能会在此处遇到致命错误)。 Typically you create a plugin and set up your AJAX inside 通常,您创建一个插件并在其中设置AJAX

jQuery(document).ready(function($) {

    var data = {
        'action': 'my_action',
        'whatever': 1234
    };

    // since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php
    $.post(ajaxurl, data, function(response) {
        alert('Got this from the server: ' + response);
    });
});

And then your plugin looks like this 然后你的插件看起来像这样

<?php 

add_action( 'wp_ajax_my_action', 'my_action_callback' );

function my_action_callback() {
    echo the_title();
    die();
}

As @vch said in a comment, if you have a simple php file that you call directly then the wordpress framework is not loaded and you cannot use wordpress functions in that file. 正如@vch在评论中所说,如果您有一个直接调用的简单php文件,则不会加载wordpress框架,因此您无法在该文件中使用wordpress函数。

I think what you want to do is write a wordpress plugin which exposes an ajax action you can then call from your javascript to get the desired data. 我认为您想要做的是编写一个wordpress插件,该插件公开ajax动作,然后您可以从javascript中调用该动作以获取所需的数据。 There is information in the codex about how to create ajax actions in plugins. 法典中包含有关如何在插件中创建ajax操作的信息。

That said, if you call your ajax action you are not necessarily in the wordpress loop, so I'm not sure you can use the_title() anyway - the ajax call (as your .load() ajax call) is a new request so how does the server know which the current post is? 就是说,如果您调用ajax操作,则不一定要在wordpress循环中,所以我不确定无论如何都可以使用the_title() -ajax调用(因为您的.load() ajax调用)是一个新请求,因此服务器如何知道当前帖子是哪个? You might need to get the post id in your main page and set it as data soemwhere and send it in the ajax call. 您可能需要在主页上获取帖子ID,并将其设置为data soemwhere,然后通过ajax调用进行发送。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM