How to get the url of a existing media in wordpress

牧云@^-^@ 提交于 2020-01-02 08:57:44

问题


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

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