插件中重写wp_new_user_notification后,如何运行WP_Query?
解决在重写的wp_new_user_notification中使用WP_Query的问题
我之前也碰到过类似的情况,其实导致WP_Query失效的原因大多和执行时机、查询参数或者全局状态有关,下面给你一步步梳理解决方案:
1. 先确认重写函数的时机是否正确
wp_new_user_notification是WordPress的可重载函数,必须在plugins_loaded钩子之后定义,不然WordPress会优先使用默认的内置函数。如果你的重写代码直接放在插件最顶部,很可能因为加载太早,WP_Query依赖的核心组件还没初始化完成。
正确的重载姿势应该是把自定义函数包裹在plugins_loaded钩子里:
add_action('plugins_loaded', function() { // 先检查默认函数是否存在,避免报错 if (function_exists('wp_new_user_notification')) { remove_function('wp_new_user_notification'); } function wp_new_user_notification(int $user_id, string $deprecated = null, string $notify = '') { // 先获取用户信息,方便后续邮件内容使用 $user = get_user_by('id', $user_id); // 这里开始调用WP_Query查询内容 $query_args = array( 'post_type' => 'post', // 要查询的内容类型,比如自定义文章类型就改这里 'posts_per_page' => 3, // 取3篇最新文章 'post_status' => 'publish', // 只查已发布的 'orderby' => 'date', 'order' => 'DESC' ); $custom_query = new WP_Query($query_args); // 处理查询结果 $recent_posts = ''; if ($custom_query->have_posts()) { while ($custom_query->have_posts()) { $custom_query->the_post(); // 把文章标题和链接拼成邮件里的列表项 $recent_posts .= sprintf("<li><a href='%s'>%s</a></li>", get_permalink(), get_the_title()); } // 一定要重置全局post变量!不然会影响后续的WordPress逻辑 wp_reset_postdata(); } // 接下来是你的自定义邮件内容组装和发送逻辑 $message = sprintf("欢迎你,%s!\n\n最近的文章:\n<ul>%s</ul>", $user->display_name, $recent_posts); wp_mail($user->user_email, '欢迎注册我们的网站', $message); } });
2. 检查WP_Query的参数细节
有时候查询失效只是参数写错了,比如post_type拼写错误、忘了指定post_status(默认是publish,但如果你的内容是草稿或其他状态就需要明确设置)。可以先简化参数做测试,比如只查最新1篇公开文章,确认能拿到结果再扩展。
3. 调试排查小技巧
如果还是没结果,可以加几行调试代码,看看查询的SQL语句和返回结果:
$custom_query = new WP_Query($query_args); // 输出生成的SQL语句,直接复制到数据库里执行就能知道问题在哪 echo $custom_query->request; // 查看查询到的帖子数组 var_dump($custom_query->posts);
(调试完记得删掉这些代码,别留在生产环境里)
替代方案:用get_posts()简化操作
如果觉得WP_Query太繁琐,也可以用get_posts(),它是WP_Query的封装,直接返回帖子对象数组,使用起来更简洁:
$recent_posts_array = get_posts(array( 'post_type' => 'post', 'posts_per_page' => 3, )); $recent_posts = ''; foreach ($recent_posts_array as $post) { setup_postdata($post); $recent_posts .= sprintf("<li><a href='%s'>%s</a></li>", get_permalink(), get_the_title()); } wp_reset_postdata();
内容的提问来源于stack exchange,提问作者Akhilesh
相关产品推荐
相关产品推荐

