wordpress plugin: query post-ID in plugin?

2019-03-05 21:05发布

hey guys, maybe some of you have experience with programming wordpress plugins. I have a probably rather simpel question, but i couldn't find anything on the web.

<?php
/*
Plugin Name: test
*/

function test($content) {

    echo $post_id;
    return $content;
}

add_filter('the_content', 'test');  
?>

I have a simpel plugin that should echo out the unique ID of every post in it's content. So on my frontpage with 10 posts every post should have it's ID echoed out.

Any idea how to achieve that? thank you!

3条回答
等我变得足够好
2楼-- · 2019-03-05 21:26

You're mixing echo and return - that doesnt work. However, try:

function test($content) 
{
    return "id: ".$post_id."<br/>".$content;
}

also, make sure to use lowercase id, as it is case-sensitive

http://codex.wordpress.org/Function_Reference/get_the_ID might be usefull aswell

查看更多
何必那么认真
3楼-- · 2019-03-05 21:26

Filters should return, not echo.

function test($content) {
    global $post;
    return 'id: ' . $post->ID . '<br />' . $content;
}

In order to look at the post object properties you must bring $post into the scope of the function, that's what this line does..

global $post;

Which then allows the reference to the object's ID, eg.

$post->ID;

See here for help understanding actions and filters.
http://codex.wordpress.org/Plugin_API

Example filter.
http://codex.wordpress.org/Plugin_API#Example

查看更多
我想做一个坏孩纸
4楼-- · 2019-03-05 21:38

My guess is Use global keyword to access post id in function

And also my guess is return and echo both would not work together in function

function test($content) {
        global $post;
        return $post->ID.'<br>'.$content;
    }
查看更多
登录 后发表回答