【问题标题】:How to get the medium size post thumbnail url in wordpress?如何在 wordpress 中获取中等大小的帖子缩略图 url?
【发布时间】:2014-10-28 01:43:55
【问题描述】:

到目前为止我发现了什么:

我有一个这样的查询:

$categories=get_category_by_slug('my_category_slug')
$posts_array = get_posts( array('category'=>$categories->cat_ID, 'numberposts' => -1 ));
foreach($posts_array as $post_array){
    $queried_post = get_post($post_array->ID);
    //I can get the source file link this way: wp_get_attachment_url( get_post_thumbnail_id($queried_post->ID))
}

但是源文件太大了。 the_post_thumbnail( medium ) 之类的函数对我不起作用,因为它不仅仅是 url。这是一个带有图像标签包装器等的 url。那么有没有办法获取到中(或小)大小文件的链接?

也可以在functions.php中设置主题支持和post-thumbnail行之后的post-thumbnail大小:

add_theme_support( 'post-thumbnails' );
set_post_thumbnail_size( 300, 300 );

我没有尝试过,但我不想设置所有缩略图的大小。

【问题讨论】:

    标签: php wordpress thumbnails


    【解决方案1】:

    使用wp_get_attachment_image_src(get_post_thumbnail_id($post_array->ID), 'medium')

    这将返回一个包含此图像的 URL、宽度、高度和裁剪模式的数组。

    编辑:更新以添加完整代码:

    $categories = get_category_by_slug('my_category_slug');
    $posts_array = get_posts( array('category' => $categories->term_id, 'numberposts' => -1 ));
    foreach($posts_array as $post_array){
        if( has_post_thumbnail($post_array->ID) ) {
            $image_arr = wp_get_attachment_image_src(get_post_thumbnail_id($post_array->ID), 'medium');
            $image_url = $image_arr[0]; // $image_url is your URL.
        }
    }
    

    【讨论】:

    • 谢谢,但是 wp_get_attachment_image_src($post_array->ID, "medium") 和 wp_get_attachment_image_src($queried_post->ID, "medium") 不起作用
    • 啊,我明白了。 $post_array 是您的帖子,而不是您的附件。我已经编辑了上面的代码 - 请随意尝试一下。
    • 我刚刚测试过它——它有效。我在上面编辑了我的答案,向您展示了您应该使用的完整代码。 $image_url 将包含中等大小的图片 URL。
    • 是的,对不起,我想我第一次使用 wp_get_attachment_image_src() 并且懒得 var_dump 它。它只是没有返回一个字符串。其他时候我使用了旧函数的 wp_get_attachment_url() 。我一头雾水,对不起。但你是对的!效果很好!非常感谢! :)
    • @DrunkenMaster 否 - 您只需确保使用正确的帖子 ID 而不是 $post_array->ID。如果您处于循环中,您可以在那里使用get_the_ID()
    猜你喜欢
    • 1970-01-01
    • 2014-03-12
    • 1970-01-01
    • 2015-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-25
    • 2013-07-17
    相关资源
    最近更新 更多