deroccha
deroccha

Reputation: 1183

Get the post-id in Wordpress plugin

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);

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;
}

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));

Upvotes: 1

Views: 6450

Answers (2)

Janiis
Janiis

Reputation: 1576

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.

Upvotes: 4

kussberg
kussberg

Reputation: 559

It is possible, when you are using this in your plugin:

add_action('wp_head','getPageId');

And declare following function:

function check_thankyou(){
    if(!is_admin()){
        global $wp_query;
        $postid = $wp_query->post->ID;
        echo $postid;
    }
}

Upvotes: 1

Related Questions