2017-10-16 229 views
0

我正在为wordpress创建一个插件OOP。该插件创建一个称为团队的新自定义帖子类型。在团队页面中,可以使用shortcode [程序]来生成一些预先定义的html代码。此外,我用新的元框创建自定义字段。WordPress的获得帖子ID

然而,问题是:当我进入调用该插件的页面时,我需要在我的插件中获取发布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(); 
    } 
+0

我很困惑 - 为什么你有两个构造函数? – FluffyKitten

+0

还有相同的但不同的尝试来解决这个问题 – Bham

回答

0

尝试定义岗位作为全球像

global $post 
+0

global $ post是空的。 – Bham

+0

也尝试在函数定义挂钩后获取postID。但仍然没有postID。 – Bham

1

如果你的插件的构造函数获取调用太早,后数据不会被设置和准备使用。

您需要将所有事情准备好后才能运行的WPs操作挂钩。 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