【问题标题】:Wordpress get post idWordpress 获取帖子 ID
【发布时间】:2017-10-18 13:32:40
【问题描述】:

我正在为 wordpress 创建一个插件 OOP。该插件创建了一个新的自定义帖子类型,称为团队。在团队页面中,可以使用简码 [程序] 生成一些默认的 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();
    }

【问题讨论】:

  • 我很困惑 - 为什么你有两个构造函数?
  • 解决这个问题的方法相同但尝试不同

标签: php wordpress custom-post-type shortcode


【解决方案1】:

如果您的插件构造函数被调用得太早,则帖子数据将无法设置并准备好使用。

您需要挂钩在一切准备就绪后运行的 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

【讨论】:

    【解决方案2】:

    尝试将帖子定义为全局类

    global $post
    

    【讨论】:

    • 全局 $post 为空。
    • 函数定义钩子后也尝试获取postID。但仍然没有 postID。
    猜你喜欢
    • 2011-06-21
    • 2010-12-04
    • 1970-01-01
    • 2017-04-23
    • 2020-06-12
    • 1970-01-01
    • 1970-01-01
    • 2011-03-12
    • 2013-10-11
    相关资源
    最近更新 更多