2012-08-10 58 views

回答

5

直接的方法 - 使用直接的SQL语句SELECT与WordPress的数据库抽象API:

$wpdb->get_var(
    $wpdb->prepare(" 
     SELECT ID 
      FROM $wpdb->posts 
      WHERE post_title = %s 
       AND post_type = '%s' 
    ", $title, $type) 
); 

您可以纳入一个函数这个(你可以在functions.php文件的地方):

function get_post_by_title($title, $type = 'post') { 
    global $wpdb; 

    $post_id = $wpdb->get_var(
     $wpdb->prepare(" 
      SELECT ID 
       FROM $wpdb->posts 
       WHERE post_title = %s 
        AND post_type = '%s' 
     ", $title, $type) 
    ); 

    if(!empty($post_id)) { 
     return(get_post($post_id)); 
    } 
} 

而且在模板中,你可以打电话给你的功能,像这样:

$attachment = get_post_by_title('Filename', 'attachment'); 
echo $attachment->guid; // this is the "raw" URL 
echo get_attachment_link($attachment->ID); // this is the "pretty" URL 
+0

谢谢亲爱的Mihai Stancu。你完成了炉排! – 2012-08-10 12:32:24

相关问题