image - 如何在wordpress中获取现有媒体的url

标签 image wordpress get media

我向我的 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/

相关文章:

python - 如何从图片中提取单词的单个图像?

python - 如何使用 Pillow 读取原始 RGBA4444 图像?

javascript - 在 WooCommerce 中 2 秒后自动关闭迷你购物车下拉菜单

css - 自定义 CSS 以创建 WordPress 下拉菜单

java - 如何在 Java 中设置 GET 请求中的参数

java - 从套接字读取二进制数据

javascript - 使用图像映射时鼠标悬停时图像闪烁javascript

html - 主页链接到 Wordpress 中的仪表板

c - Posix 线程消费者无法正确打印

c# - 如何将图像保存到文件系统?