简体   繁体   English

wordpress 错误:调用插件中未定义的函数

[英]wordpress error : Call to undefined function in plugin

I have been writing a function using the Shortcode Exec PHP plugin and the function works great when I run it inside the editor.我一直在使用 Shortcode Exec PHP 插件编写一个函数,当我在编辑器中运行它时,该函数运行良好。

When I move it to a plugin I begin to see errors in the log such as this:当我将它移动到插件时,我开始在日志中看到错误,例如:

PHP Fatal error: Call to undefined function wp_create_category()

I realize that this is because of lack of includes, etc.我意识到这是因为缺少包含等。

What is the correct way to include the built-in wordpress functions for a plugin?为插件包含内置 wordpress 功能的正确方法是什么?

My plugin uses the following wordpress functions我的插件使用以下 wordpress 函数

wp_create_category
username_exists
wp_generate_password
wp_create_user
wp_insert_post
update_post_meta
add_post_meta

Use below code, working fine , i have tested使用下面的代码,工作正常,我已经测试过

   require_once(ABSPATH . 'wp-config.php'); 
   require_once(ABSPATH . 'wp-includes/wp-db.php'); 
   require_once(ABSPATH . 'wp-admin/includes/taxonomy.php'); 

try including this to your file and let me know then --尝试将其包含在您的文件中,然后告诉我-

require_once(WORDPRESS_HOME. 'wp-config.php'); 
require_once(WORDPRESS_HOME. 'wp-includes/wp-db.php'); 
require_once(WORDPRESS_HOME. 'wp-admin/includes/taxonomy.php'); 

I know this is very old question, but somehow noone mentioned solution I have in mind.我知道这是一个非常古老的问题,但不知何故没有人提到我想到的解决方案。

I think the correct way of doing this is by using correct init hook in your plugin.我认为这样做的正确方法是在你的插件中使用正确的 init 钩子。 Adding require_once() seems like hack to me.添加 require_once() 对我来说似乎是黑客。

So some functions are being loaded only for admin area and some are only loaded for frontend.所以有些功能只为管理区域加载,有些功能只为前端加载。 So depending on those use correct hook in your plugin.所以取决于那些在你的插件中使用正确钩子的人。

add_action('init', function () {}

or要么

add_action('admin_init', function () {}

You can have both of them in one plugin of course.当然,您可以在一个插件中同时使用它们。

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

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