如何在wordpress中获取现有媒体的网址

Ami*_*ari 2 media wordpress get image

我在wordpress库中添加了一些图像.现在我需要通过名称检索其中一个并获取它的URL.请注意,我没有在任何帖子中附上它们.

感谢您的关注.

Mih*_*ncu 5

一种直接的方法 - 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)