Php 对象函数作为WordPress中add_shortcode()的回调
我创建了一个类来构建自定义的post类型,并试图包括一种为该post类型插入特定短代码的方法,但我似乎无法获取add_shortcode()的回调函数来从创建的对象内部获取函数 我有类似的想法:Php 对象函数作为WordPress中add_shortcode()的回调,php,wordpress,class,object,Php,Wordpress,Class,Object,我创建了一个类来构建自定义的post类型,并试图包括一种为该post类型插入特定短代码的方法,但我似乎无法获取add_shortcode()的回调函数来从创建的对象内部获取函数 我有类似的想法: class custom_post_type { public $post_type_name; function __construct($id,$options) { //builds the custom post type, etc $this
class custom_post_type {
public $post_type_name;
function __construct($id,$options) {
//builds the custom post type, etc
$this->post_type_name = $id;
$shortcode = new build_shortcode($id,$options);
}
public function shortcode_handler($atts) {
return $this->post_type_name;
}
}
class build_shortcode {
function __construct($id,$options) {
add_shortcode( $options['shortcode_name'] , array( $id ,'shortcode_handler') );
}
}
$options = array(); // a bunch of variables would be defined here to use in the classes
$post_type = new custom_post_type('post_type',$options);
但是当我使用[show cpt name]短代码时,它不会运行该函数。
我知道他们在法典中给出了使用类的示例,例如:
add_shortcode( $options['shortcode_name'] , array( 'custom_post_type' ,'shortcode_handler'));
但这并不是我想要的,因为我希望回调函数使用创建的特定对象的值
这可能实现吗?据我所知,我认为不可能。为什么要传递id?$id将是对象名,在本例中为“post_type”,因为我想访问$post_type中的函数。在类之外,它类似于$post\u type->shortcode\u处理程序($atts);我认为不可能,但我不确定。顺便说一句,短代码不能有相同的名称。所以每次创建自定义的\u post\u类型的对象时,都会使用相同的名称创建相同的短代码,对吗?(在您的示例中,show cpt name)短代码的名称实际上在$options数组中,因此它们不会有相同的名称,因为也会有代码来控制它,但我忽略了它,因为它与这里的问题无关。我将更新示例代码以举例说明如何使用。谢谢