我向我的 WordPress 库添加了一些图像。现在我需要按名称检索其中之一并获取它的 URL。请注意,我没有将它们附加在任何帖子中。
感谢您的关注。
最佳答案
一种简单的方法 - 使用直接 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
关于image - 如何在wordpress中获取现有媒体的url,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11901499/