在wordpress中检查id的存在

Igo*_*rra 4 php wordpress

我有一个id:

$id = 151;
Run Code Online (Sandbox Code Playgroud)

我想检查这样的存在:

$content = get_post($id);
if ($content)
    echo "post $id already exists";
else
    echo "post $id does not exists or was deleted";
Run Code Online (Sandbox Code Playgroud)

但在WP论坛上似乎总是更喜欢问DB:

global $wpdb;
$post_exists = $wpdb->get_row("SELECT * FROM $wpdb->posts WHERE id = '" . $id . "'", 'ARRAY_A');
if ($post_exists)
    echo "post $id exists";
else
    echo "post $id does not exist";
Run Code Online (Sandbox Code Playgroud)

那么哪种方法最好?的确,我更喜欢第一个的轻松.

小智 27

我认为最好是尽可能少地直接查询数据库

您可以使用get_post_status()函数.

如果帖子不存在,则返回false

if ( get_post_status ( $post_id ) ) {
    // do stuff
}
Run Code Online (Sandbox Code Playgroud)

或者,确保帖子发布

if ( 'publish' == get_post_status ( $post_id ) ) {
    // do stuff
}
Run Code Online (Sandbox Code Playgroud)

http://codex.wordpress.org/Function_Reference/get_post_status

  • 我检查了get_post_status的来源,它使用了get_post。为什么不直接使用`null!== get_post($ post_id)`? (2认同)
  • @Michelle我也这么想,但它返回了一堆额外的数据。按照 csag 的建议去做不是一样干净吗?无论哪种方式都是干净的,并且使用 Wordpress 而不是 wpdb。:) (2认同)

小智 6

if( is_null(get_post($id))){

      echo "post $id does not exists or was deleted";

}else{

       echo "post $id already exists";

}
Run Code Online (Sandbox Code Playgroud)

  • 请注意,使用此方法,垃圾箱中的帖子仍被视为存在。 (3认同)

dld*_*dnh -1

我认为如果他们给你一个调用的函数,你就调用它;使用数据库来处理函数未提供的内容。