【问题标题】:How to get the url of a existing media in wordpress如何在wordpress中获取现有媒体的url
【发布时间】:2012-08-07 17:54:13
【问题描述】:

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

感谢您的关注。

【问题讨论】:

    标签: image wordpress get media


    【解决方案1】:

    一种简单的方法 - 使用带有 WordPress 数据库抽象 API 的直接 SQL SELECT 语句:

    $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
    

    【讨论】:

      猜你喜欢
      • 2021-09-15
      • 2014-02-05
      • 2019-09-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-23
      • 1970-01-01
      相关资源
      最近更新 更多