我正在为wordpress创建一个插件OOP。该插件创建了一个名为 teams 的新自定义帖子类型。在团队页面中,可以使用简码[程序]生成一些预设的html代码。此外,我还使用新的元框创建了自定义字段。
然而,问题是:当我进入调用插件的页面时,将团队页面与我需要在我的插件中获取帖子 ID 以检索 get_post_meta() 的排序代码相等。
我尝试了以下方法:
public function __construct(){
// not working
$post;
$post->ID;
// not working
global $wp_query;
$post_id = $wp_query->post->ID;
$post = get_post( $post_id );
// not workiing
echo '<pre>';
print_r('post_id:' . get_the_ID());
echo '</pre>';
}
当我从前端访问页面时,我如何在我的插件中接收自定义帖子 ID(因此调用插件,运行短代码)
我的主类是这样加载的:
function run_plugin() {
$plugin = new MyPlugin();
$plugin->run();
}
run_plugin();
在 MyPlugin 中,构造函数看起来像
public function __construct() {
if ( defined( 'PLUGIN_NAME_VERSION' ) ) {
$this->version = PLUGIN_NAME_VERSION;
} else {
$this->version = '1.0.0';
}
$this->plugin_name = 'MyPlugin';
if(!empty(get_option($this->plugin_name))){
$this->clientID = get_option($this->plugin_name)['client_id'];
}
$this->load_dependencies();
$this->set_locale();
$this->define_admin_hooks();
$this->define_public_hooks();
$this->define_shortcodes();
}
如果您的插件构造函数被过早调用,则发布数据将不会设置并可供使用。
您需要挂钩到在一切准备就绪后运行的WP操作之一。对于帖子数据来说,init
操作应该足够了,但根据您需要的其他内容,您可以挂接到wp_loaded
,因为它直到 WordPress 完全加载后才会运行。
function run_plugin() {
$plugin = new MyPlugin();
$plugin->run();
}
/* run_plugin(); */ // <- instead of this....
add_action( 'wp_loaded','run_plugin' ); // <- ...do this
尝试将帖子定义为全局
global $post