如何在Wordpress中获取其标题的附件ID?

时间:2014-09-09 21:55:27

标签: wordpress wp-query

这不起作用:

$args = array( 
    "post_per_page" => 1,
    "post_type" => "attachment", 
    "post_title" => trim( "My Attachment" )
);

//This is empty
$get_posts = new WP_Query( $args );

我知道附件存在该帖子标题,因为按ID搜索会返回一个post_title = "My Attachment"的对象。

如何通过帖子标题找到附件?

1 个答案:

答案 0 :(得分:2)

抱歉抱歉... 您可以使用类WPDB的直接查询..

global $wpdb;
$str= "My Attachment";
$posts = $wpdb->get_results( "SELECT * FROM $wpdb->posts WHERE post_title = '$str' ", OBJECT ); 
if ( $posts ){
    foreach ( $posts as $post ){
        echo $post->post_title;
    }
}

但要注意!保护您的代码免受SQL注入攻击 在http://codex.wordpress.org/Class_Reference/wpdb#Protect_Queries_Against_SQL_Injection_Attacks

中阅读更多内容