我正在尝试将ajax操作传递给/wp-admin/admin-ajax.php,但是我似乎无法调用任何使用类封装命名空间的函数。我收到以下错误:
Warning: call_user_func_array() expects parameter 1 to be a valid callback, class 'PHP_faq_backend' not found in /wp-includes/plugin.php
我的行动如下:
add_action('wp_ajax_edit_form', array('PHP_faq_backend', 'edit_form'));
显然我不想通过修改admin-ajax.php文件来强制执行此操作,但是如何加载我的类文件以便该操作可以正常工作?
答案 0 :(得分:2)
确保将您的类文件包含在Wordpress主题(functions.php)或插件中的某个位置。
我通常使用这样的东西;
<?php
class Some_Class {
public function __construct() {
//logged in users
add_action('wp_ajax_some_method', array($this,'some_method'));
//non logged in users
add_action('wp_ajax_nopriv_some_method', array($this,'some_method'));
}
public function some_method(){
//check nonce values etc
if ( ! isset( $_REQUEST['some_nonce'] ) || ! wp_verify_nonce( $_REQUEST['some_nonce'], 'class_some_nonce' ) ) {
wp_die(__('Naughty', 'some-class-textdomain'));
}
//proceed with post data validation - then execute method
}
}
$some_class_instance = new Some_Class();
?>
以上是用于在类实例中注册操作。
答案 1 :(得分:0)
错误消息的最后一部分是您的第一个线索。我在WP的多个版本上遇到了同样的问题。在某些环境中,安装将无法识别第三方类。您可以尝试解决此问题:
我发现的一个解决方案始终有效:
这种方法可以通过几种不同的方式实现;首先,您可以定义一个驻留在当前主题目录中的插件目录 - 这样可以将所有文件保存在一起;第二种是走正常路线并在wp-content/plugins/my-skeleton-plugin
下创建一个插件文件夹。如果你采用这种方法,这是一个让你入门的骨架插件:
<?php
/*
Plugin Name: Skeleton Plugin Base
Plugin URI: http://www.yourdomain.com
Description: This is a base plugin to use as a template for other plugins.
Author: Author Name
Version: v0.0.1
Author URI: http://www.yourdomain.com
*/
# +------------------------------------------------------------------------+
# PLUGIN URL AND PATH CONSTANTS
# +------------------------------------------------------------------------+
/**
* Don't depend on WP to always provide a consistent directory/path to use.
* Extrapolate one the location of this file. The reason for this is that some
* themes might re-locate the plugins and themes directory to another folder
* and therefore break the normal WP structure.
*/
define( DS, DIRECTORY_SEPARATOR, true );
$PLUGIN_URL = WP_PLUGIN_URL . DS . str_replace( basename( __FILE__ ),'', plugin_basename(__FILE__) );
$PLUGIN_DIR = dirname(__FILE__);
define( MY_PLUGIN_URL, $PLUGIN_URL, true );
define( MY_PLUGIN_DIR, $PLUGIN_DIR, true );
# +------------------------------------------------------------------------+
# INCLUDES
# +------------------------------------------------------------------------+
/**
* Include the plugin.
*/
// Use include() if you prefe
include_once( MY_PLUGIN_DIR . '/inc/classes/my_skeleton_plugin.class.php' );
try
{
/**
* Initialize the plugin
*/
}
catch( Exception $e )
{
throw $e;
}