Capslock10
Capslock10

Reputation: 806

Get current post id outside the loop. Wordpress

I am making a plugin for wordpress. And the problem is that, how can I get the current post ID outside the loop?

I have a button on the post, and the post ID should be returned when the button is clicked by the user.

So, do anyway to get the post id?

My plugin dir: wp-content\plugins\updateDatabase\js\connectionDatabase.php

Here is my code: And my url http://localhost:8080/wordpress/?p=1169

        $post_id = $_GET['p'];
        echo $post_id;
        $link = getConnection();

        $bonusPoint = 0;

        $query_sql = "SELECT bonus_point FROM post_data03 WHERE post_id =" .$post_id;
        $result = mysqli_query($link, $query_sql);

        if (mysqli_num_rows($result) > 0) {
                // output data of each row
                while($row = mysqli_fetch_assoc($result)) {
                    $bonusPoint = $row['bonus_point'];
                }
       } else {
                  echo "0 results";
       }

Using $post:

function getBonusPointFromDataPost()
{
        global $wp_query; 
        global $post;
        $post_id = add_action( 'the_post', 'get_post_info' );
        $link = getConnection();
}

GetBonusPointFromDataPost() will be fired when the user clicks the button which on the post page. And at the same time, the $post_id should be returned.

And I make a function to return the $post_id, but it only work when I add the action to it.

function get_post_info() {
        global $wp_query;

        global $post;
        $post_id = $wp_query->post->ID;
        echo $post_id;
        return  $post_id;
    }

How can I return the $post_id when the user clicks the button.

Upvotes: 1

Views: 6553

Answers (1)

ayush
ayush

Reputation: 134

Here it is, use global $post to get the current post object

global $post;
echo $post->ID;

Upvotes: 2

Related Questions