ajax php die,【Wordpress】使用 admin-ajax.php 实现ajax请求 | 碎念

写在前面:

最近想给自己的博客实现一个 站内搜索 功能,期望整个过程异步实现。这样用户体验度更好。

遇到问题:

如何实现文章的模糊匹配?

wordpress 如何提供接口?

页面如何实现异步请求接口数据,并完成页面的渲染?

问题1 – 模糊搜索:

大胆尝试:

wordpress 原生自带有一个 wp_query 函数,它支持的参数非常完善灵活,实现整个网站与数据库的交互。比如调用最新文章、热门文章、自定义文章类型文章循环输出等。

在官方手册中也有介绍到:wp_query,支持多种 sql 语句的 比较符号:

c3e9b639700e12ac389b7e3b64130159.png

看!他说可以支持 like 或者 regexp 这种比较符号。

于是我们试一试:

Shell

$args = [

'posts_per_page' => -1, // 每页数量 -1 不限制数量

'ignore_sticky_posts' => 1, //

'post_type' => 'post', //

'post_status' => 'publish', // 已经发布的文章

'meta_query' => [

[

'key' => 'post_title',

'value' => 'Mac',

// 'compare' => 'REGEXP',

'compare' => 'LIKE',

],

],

];

$result = new WP_Query($args);

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

$args=[

'posts_per_page'=>-1,//每页数量-1不限制数量

'ignore_sticky_posts'=>1,//

'post_type'=>'post',//

'post_status'=>'publish',//已经发布的文章

'meta_query'=>[

[

'key'=>'post_title',

'value'=>'Mac',

//'compare'=>'REGEXP',

'compare'=>'LIKE',

],

],

];

$result=newWP_Query($args);

Shell

// 判断查询的结果,检查是否有文章

if ( $result->have_posts() ) :

// 通过查询的结果,开始主循环

while ( $result->have_posts() ) :

$result->the_post(); //获取到特定的文章

// 要输出的内容,如标题、日期等

endwhile;

endif;

1

2

3

4

5

6

7

8

9

10

11

//判断查询的结果,检查是否有文章

if($result->have_posts()):

//通过查询的结果,开始主循环

while($result->have_posts()):

$result->the_post();//获取到特定的文章

//要输出的内容,如标题、日期等

endwhile;

endif;

但是很遗憾,不知道是我的姿势不对,就是不起作用?? 如果有大佬解决了,望不吝赐教!

转换思路:

其实在数据库使用 like 的查询效率是非常低,所以我们可以把这一部分的逻辑由 php 自己实现。

Shell

if ($result->have_posts()) {

while ($result->have_posts()) {

$result->the_post();

global $post;

$post_title = get_the_title();

// mb_stripos 不区分大小 判断字符串中是否存在另一个字符串

if (mb_stripos($post_title, $keyword)) {

$articles[] = [

'id' => get_the_ID(),

'post_name' => $post->post_name,

'post_title' => $post_title,

'post_date' => $post->post_date,

];

}

}

}

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

if($result->have_posts()){

while($result->have_posts()){

$result->the_post();

global$post;

$post_title=get_the_title();

//mb_stripos不区分大小判断字符串中是否存在另一个字符串

if(mb_stripos($post_title,$keyword)){

$articles[]=[

'id'=>get_the_ID(),

'post_name'=>$post->post_name,

'post_title'=>$post_title,

'post_date'=>$post->post_date,

];

}

}

}

所以,我们可以看到,通过 PHP 的 mb_stripos 可以实现字符串的模糊匹配,这样就可以筛选出我们想要的结果。

问题2 – 接口对接:

上面我们已经实现了文章的模糊匹配,接下来就要提供一个接口,来实现与前端的交互。所以,我们将会用到 wordpress 自带的 admin-ajax.php 文件。

实现原理:

要使用 admin-ajax.php 请求必然首先就是遇到如何使用 wordrpess 的钩子 hook 来做过滤。

Shell

//wp_ajax_nopriv_ 效验用户为未登录是启用的方法

add_action( 'wp_ajax_nopriv_search', 'search' );

//wp_ajax_ 效验用户为已登录是启用的方法

add_action( 'wp_ajax_search', 'search' );

1

2

3

4

//wp_ajax_nopriv_效验用户为未登录是启用的方法

add_action('wp_ajax_nopriv_search','search');

//wp_ajax_效验用户为已登录是启用的方法

add_action('wp_ajax_search','search');

具体接口:

我们看到上面 search 这个是我们要定义的搜索函数,逻辑就要用到了刚刚介绍的 模糊匹配,

但是其中几点需要注意到的是:

header(“Content -Type: application/json”); // 指定返回头

wp_die() //接口响应结束用这个函数结尾,否则会一直走到这个当前页面最下面,多返回一个 0;

需要将下面的代码添加到if( is_user_logged_in() ) 这个代码之前!!!!

Shell

/ 文章搜索

function search()

{

$keyword = $_GET['keyword'] ?? $_GET['keyword'];

// 指定返回头

header("Content -Type: application/json");

if (empty($keyword)) {

echo $response = (json_encode([], JSON_UNESCAPED_UNICODE));

wp_die();

}

$args = [

'posts_per_page' => -1,

'ignore_sticky_posts' => 1,

'post_type' => 'post',

'post_status' => 'publish',

];

$result = new WP_Query($args);

$articles = [];

if ($result->have_posts()) {

while ($result->have_posts()) {

$result->the_post();

global $post;

$post_title = get_the_title();

if (mb_stripos($post_title, $keyword) !== false) {

$articles[] = [

'id' => get_the_ID(),

'post_name' => $post->post_name,

'post_title' => $post_title,

'post_date' => $post->post_date,

];

}

}

}

wp_reset_query();

echo $response = (json_encode($articles, JSON_UNESCAPED_UNICODE));

wp_die();

}

add_action( 'wp_ajax_nopriv_search', 'search' );

add_action( 'wp_ajax_search', 'search' );

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

/文章搜索

functionsearch()

{

$keyword=$_GET['keyword']??$_GET['keyword'];

//指定返回头

header("Content -Type: application/json");

if(empty($keyword)){

echo$response=(json_encode([],JSON_UNESCAPED_UNICODE));

wp_die();

}

$args=[

'posts_per_page'=>-1,

'ignore_sticky_posts'=>1,

'post_type'=>'post',

'post_status'=>'publish',

];

$result=newWP_Query($args);

$articles=[];

if($result->have_posts()){

while($result->have_posts()){

$result->the_post();

global$post;

$post_title=get_the_title();

if(mb_stripos($post_title,$keyword)!==false){

$articles[]=[

'id'=>get_the_ID(),

'post_name'=>$post->post_name,

'post_title'=>$post_title,

'post_date'=>$post->post_date,

];

}

}

}

wp_reset_query();

echo$response=(json_encode($articles,JSON_UNESCAPED_UNICODE));

wp_die();

}

add_action('wp_ajax_nopriv_search','search');

add_action('wp_ajax_search','search');

调用方式:

上面我们用了 wordpress 的钩子函数,所以我们调用的时候用参数 action ,后面拼接相对应的 function

效果展示:

c724cbb3b9e531666846ac6502326bdf.png

问题3 – 异步渲染

其实很简单,前两部已经完成大部分的工作。我们只需要添加一个监听输入框值变化的事件,使用 JQuery 的 ajax 请求接口就OK了。

Shell

$("#input-search").bind("input propertychange", function (event) {

search();

});

// 搜索文章

function search() {

var host = document.location.host;

var protocol = document.location.protocol;

var keyword = $("#input-search").val();

if (keyword.length > 0) {

$.ajax({

type: "GET",

url: protocol + '//' + host + "/wp-admin/admin-ajax.php?action=search&keyword=" + keyword,

data: {},

dataType: "json",

success: function (data) {

addArticle(data);

},

error: function (data) {

console.log(data);

}

});

}

}

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

$("#input-search").bind("input propertychange",function(event){

search();

});

//搜索文章

functionsearch(){

varhost=document.location.host;

varprotocol=document.location.protocol;

varkeyword=$("#input-search").val();

if(keyword.length>0){

$.ajax({

type:"GET",

url:protocol+'//'+host+"/wp-admin/admin-ajax.php?action=search&keyword="+keyword,

data:{},

dataType:"json",

success:function(data){

addArticle(data);

},

error:function(data){

console.log(data);

}

});

}

}

上面我们可以看到,这样可以正确拿到接口返回的数据,接下来就是最重要的数据拼装。

由于我们没有框架去做,只能将 Html 标签 与 Js 语法进行拼接。

我们这里是用了正则表达式 ,写了一个规则,可以通过 键值 格式化我们定义好的字符串,来人上代码!

Shell

String.prototype.format = function () {

if (arguments.length === 0) {

return this;

}

var param = arguments[0];

var s = this;

if (typeof (param) == 'object') {

for (var key in param)

s = s.replace(new RegExp("\\{" + key + "\\}", "g"), param[key]);

return s;

} else {

for (var i = 0; i < arguments.length; i++)

s = s.replace(new RegExp("\\{" + i + "\\}", "g"), arguments[i]);

return s;

}

};

// 示例:

var str1 = "hello {0}".format("world"); //log hello world

var str1 = "我叫{0},性别{1}".format("美男子", "男"); //log 我叫美男子,性别男

var user = {name: "美男子",sex: "男",age: 20};

var str2 = "我叫{name},性别{sex},今年{age}岁".format(user); //我叫美男子,性别男,今年20

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

String.prototype.format=function(){

if(arguments.length===0){

returnthis;

}

varparam=arguments[0];

vars=this;

if(typeof(param)=='object'){

for(varkeyinparam)

s=s.replace(newRegExp("\\{"+key+"\\}","g"),param[key]);

returns;

}else{

for(vari=0;i

s=s.replace(newRegExp("\\{"+i+"\\}","g"),arguments[i]);

returns;

}

};

//示例:

varstr1="hello {0}".format("world");//loghelloworld

varstr1="我叫{0},性别{1}".format("美男子","男");//log我叫美男子,性别男

varuser={name:"美男子",sex:"男",age:20};

varstr2="我叫{name},性别{sex},今年{age}岁".format(user);//我叫美男子,性别男,今年20

下面我利用上面的这个 函数,格式化我们要渲染的每个元素。

Shell

var item = "

\n" +

" {show_date} \n" +

" —\n" +

" {post_title} \n" +

" ";

var fix = {

'id': article['id'],

'show_date': show_date,

'post_date': article['post_date'],

'post_title': article['post_title'],

'post_link': protocol + '//' + host + '/' + article['post_name']

};

$("#articles").append(item.format(fix));

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

varitem="

\n"+

"         {show_date} \n"+

"        —\n"+

"         {post_title} \n"+

"    

";

varfix={

'id':article['id'],

'show_date':show_date,

'post_date':article['post_date'],

'post_title':article['post_title'],

'post_link':protocol+'//'+host+'/'+article['post_name']

};

$("#articles").append(item.format(fix));

是不是整个流程就已经很流畅了!!!

效果演示:

4095a23035665795d39cc248a960d245.gif

阅读终点,创作起航,您可以撰写心得或摘录文章要点写篇博文。去创作
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
首先,在 WordPress 主题的 functions.php 文件中添加以下代码片段: ```php // 添加 AJAX 功能 add_action( 'wp_enqueue_scripts', 'add_ajax_script' ); function add_ajax_script() { wp_enqueue_script( 'ajax-script', get_template_directory_uri() . '/js/ajax-comments.js', array('jquery') ); wp_localize_script( 'ajax-script', 'ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) ); } ``` 这将在 WordPress 的前端页面上添加所需的 JavaScript 文件,其中包括 ajax-comments.js。然后,在主题文件夹中创建一个新文件夹 js,并在其中创建一个新文件 ajax-comments.js,并添加以下代码: ```javascript jQuery(document).ready(function($) { // 当提交评论表单时执行以下操作 $('#commentform').submit(function(){ var form_data = $(this).serialize(); // 序列化表单数据 $.ajax({ type: 'POST', url: ajax_object.ajax_url, // 使用 wp-admin/admin-ajax.php 进行 AJAX 请求 data: form_data + '&action=add_comment', // 将表单数据添加到请求中,并指定操作 success: function(response){ $('#commentform')[0].reset(); // 清空表单 $('.comment-list').append(response); // 将新评论添加到评论列表中 } }); return false; // 防止表单提交 }); }); ``` 这将在评论表单提交时使用 AJAX 进行异步请求,并在成功后将新评论添加到评论列表中。最后,在 functions.php 文件中添加以下代码以处理 AJAX 请求: ```php // 处理 AJAX 请求 add_action( 'wp_ajax_add_comment', 'add_comment_callback' ); add_action( 'wp_ajax_nopriv_add_comment', 'add_comment_callback' ); function add_comment_callback() { $comment_data = array( 'comment_post_ID' => $_POST['comment_post_ID'], 'comment_author' => $_POST['author'], 'comment_author_email' => $_POST['email'], 'comment_author_url' => $_POST['url'], 'comment_content' => $_POST['comment'], 'comment_type' => '', 'comment_parent' => $_POST['comment_parent'], 'user_id' => get_current_user_id(), 'comment_author_IP' => $_SERVER['REMOTE_ADDR'], 'comment_agent' => $_SERVER['HTTP_USER_AGENT'], 'comment_date' => current_time( 'mysql' ), 'comment_approved' => 1, ); $comment_id = wp_insert_comment( $comment_data ); // 插入新评论 $comment = get_comment( $comment_id ); // 获取新评论的信息 include( locate_template( 'comment.php', false, false ) ); // 加载评论模板并显示新评论 die(); // 终止脚本 } ``` 这将使用 wp_insert_comment() 函数将新评论插入 WordPress 数据库,并使用 comment.php 模板文件来显示新评论。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值