在Wordpress插件中获取post-id [英] Get the post-id in Wordpress plugin

查看:699
本文介绍了在Wordpress插件中获取post-id的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在自定义的wordpress插件中获取帖子ID,并且正在使用以下代码:

I'm trying to get the post id inside of my custom wordpress plugin and I'm using the following code:

global $post;
$current_page_id = $post->ID;
var_dump($current_page_id);

但是没有成功.使用var_dump,我可以接听每个呼叫null. 比,如果我添加到模板中,则输出效果更好:

But without any success. With var_dump I'm getting on every call null. Than, if I add to a template than the output works:

add_action('wp_footer', 'test');
function test() {
    global $post;
    $current_page_id = $post->ID;
}

我想在我的插件内部实现的是将当前的帖子ID传递给我的函数之一.像这样:

What I would like to achieve inside of my plugin, is to pass the current post id to one of my functions. So something like:

my_function($base_url, array('variable_to_post' => $post->ID));

推荐答案

如果您需要从wordpress插件获取帖子ID,则可以在wp操作挂钩中运行插件,以访问全局$wp_query对象.

If you need to get post id from wordpress plugin, you can run your plugin in wp action hook, to get access to global $wp_query object.

这是简单的测试解决方案.

Here is simple test solution.

<?php
/*
Plugin Name: Plugin Name
Plugin URI:
Description: Plugin Description
Version: 1.0.0
Author:
Author URI:
*/

if (!defined('WPINC')) {
    die;
}

/**
 * Class MyPlugin
 */
class MyPlugin {
    private $postId;

    /**
     * MyPlugin constructor.
     * @param $wp_query
     */
    public function __construct($wp_query) {
        if ($wp_query && $wp_query->post) {
            $this->postId = $wp_query->post->ID;
        }
    }

    /**
     * Get Post Id
     * @return mixed
     */
    public function getPostId() {
        return $this->postId;
    }
}

/**
 * Start plugin
 */
add_action('wp', function () {
    global $wp_query;
    $myPlugin = new MyPlugin($wp_query);
    echo $myPlugin->getPostId();
});

希望这会对某人有所帮助.

Hope this will be of help for someone.

这篇关于在Wordpress插件中获取post-id的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆