一种直接的方法 - SELECT在WordPress数据库抽象API中使用直接SQL 语句:
$wpdb->get_var(
$wpdb->prepare("
SELECT ID
FROM $wpdb->posts
WHERE post_title = %s
AND post_type = '%s'
", $title, $type)
);
Run Code Online (Sandbox Code Playgroud)
您可以将其合并到一个函数中(您可以放在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));
}
}
Run Code Online (Sandbox Code Playgroud)
在您的模板中,您可以将这些功能称为:
$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
Run Code Online (Sandbox Code Playgroud)