问题
i added some image to my wordpress library. now i need to retrieve one of them by name and get it's URL. note that i didn't attach them in any post.
thanks for your attention.
回答1:
A straightforward approach - using a direct SQL SELECT
statement with the WordPress database abstraction API:
$wpdb->get_var(
$wpdb->prepare("
SELECT ID
FROM $wpdb->posts
WHERE post_title = %s
AND post_type = '%s'
", $title, $type)
);
You can incorporate this into a function (you can place in your functions.php file):
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));
}
}
And the in your templates you can call you functions like so:
$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
来源:https://stackoverflow.com/questions/11901499/how-to-get-the-url-of-a-existing-media-in-wordpress