这个问题特别适用于wordpress,但我不相信它是一个wordpress特定的问题。当我尝试创建“sample_widget”类型的新对象时,我收到了一个类未找到错误。代码如下:
global $wpdb;
require_once(dirname(__FILE__) . '/../../../wp-load.php'); // Instantiate all the wordpress stuff, we are three subfolders removed from the /wp folder.
require_once(dirname(__FILE__) . '/../../../wp-includes/script-loader.php'); // Instantiate all the wordpress stuff, we are three subfolders removed from the /wp folder.
class sample_widget extends WP_Widget {
public $widgetName = "sample_widget";
public function __construct() {
parent::__construct(
$this->widgetName, // Base ID
__('sample_widget', 'wpb_widget_domain'), // Name
array( 'description' => __('sample_widget', 'wpb_widget_domain'), ) // Args
);
} // end of constructor
public function whoami() {
echo "This widget is called:" . $this->widgetName;
}
public function widget( $args, $instance ) {
echo "Widget stuff.";
} // end of widget function
public function form( $instance ) {
echo "Form stuff.";
}
public function update( $new_instance, $old_instance ) {
$instance = array();
return $instance;
}
} // end of class.
add_action( 'widgets_init', function() {
register_widget( 'sample_widget' );
});
function test_widget() {
$obj = new sample_widget();
echo "Who am I? " . $obj->whoami();
}
结果:致命错误:/ 我的档案中找不到“sample_widget”类
我在同一个文件中创建了另一个基类,并从中派生出来,没有任何问题。其他类实例化工作正常。不知道我做错了什么。
此外:
$obj = new WP_Widget();
工作正常。
答案 0 :(得分:0)
要在wordpress中使用外部文件,您应该将其添加到顶部:
<?php define('WP_USE_THEMES', false); require('../../../wp-load.php'); ?>