How to get the url of a existing media in wordpress

与世无争的帅哥 提交于 2019-12-06 14:05:34

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!