【问题标题】:wordpress image size based on url基于 url 的 wordpress 图像大小
【发布时间】:2011-03-30 14:08:52
【问题描述】:

我正在使用自定义字段来选择图片的网址。

我的客户正在插入和上传所有图像,所以这需要非常简单。这就是为什么我试图在幕后处理它。

我遇到的问题是全尺寸图片的 url 中的所有内容,这确实减慢了加载时间。

有没有办法可以根据完整大小的 url 插入缩略图或其他图像大小?

我已经尝试过这种方法,但我遇到的问题是一些图像没有相同的牙列,所以这需要更加动态地完成。

<? $reduceimage = str_replace('.jpg', '-330x220.jpg' , $defaultimage); ?>

【问题讨论】:

  • 这需要多动态?您是否需要将图像修剪到特定宽度? -330x220.jpg 是否会使用一些 WP 魔法自动将图像转换为缩略图?您可以使用/您知道图像的文件系统路径吗?
  • 我有完整尺寸图片的绝对网址。我的问题是我希望显示最大宽度为 330 和最大高度为 220 的中型图像。问题是其中一些图像在由 wordpress 上传/调整大小时未达到最大宽度或高度图像方面收音机。例如,许多图像是 330x220,但其他图像的尺寸中等 - 330 × 247。
  • 在这些情况下您希望发生什么?根本没有调整大小?
  • 如果可能的话,我希望图像仍然可以调整大小,但如果不是,我想全尺寸图像必须这样做。
  • 您可以使用getimagesize() 执行此操作,但在每次请求远程 URL 时实时执行此操作非常缓慢。如果您有机会获得文件路径,应该很容易

标签: image wordpress dynamic size reduction


【解决方案1】:

我认为最好依靠 wordpress 的原生 wp_get_attachment_image_src() 函数来获取不同大小的图像。但要这样做,您需要附件 ID,而不是 url。 url转id的函数:

function fjarrett_get_attachment_id_by_url( $url ) {

    // Split the $url into two parts with the wp-content directory as the separator
    $parsed_url  = explode( parse_url( WP_CONTENT_URL, PHP_URL_PATH ), $url );

    // Get the host of the current site and the host of the $url, ignoring www
    $this_host = str_ireplace( 'www.', '', parse_url( home_url(), PHP_URL_HOST ) );
    $file_host = str_ireplace( 'www.', '', parse_url( $url, PHP_URL_HOST ) );

    // Return nothing if there aren't any $url parts or if the current host and $url host do not match
    if ( ! isset( $parsed_url[1] ) || empty( $parsed_url[1] ) || ( $this_host != $file_host ) ) {
        return;
    }

    // Now we're going to quickly search the DB for any attachment GUID with a partial path match

    // Example: /uploads/2013/05/test-image.jpg
    global $wpdb;
    $attachment = $wpdb->get_col( $wpdb->prepare( "SELECT ID FROM {$wpdb->prefix}posts WHERE guid RLIKE %s;", $parsed_url[1] ) );

    // Returns null if no attachment is found
    return $attachment[0];
}

感谢Frankie Jarrett

那么你就可以轻松搞定其他尺寸了:

$medium_image = wp_get_attachment_image_src( fjarrett_get_attachment_id_by_url($image_link), 'medium');

如果您需要此图片的链接:

$medium_image_link = $medium_image[0];
$html = '<img src="'.$medium_image_link.'" alt="" />';

【讨论】:

    猜你喜欢
    • 2020-09-01
    • 1970-01-01
    • 2014-10-29
    • 2014-09-05
    • 2017-10-06
    • 1970-01-01
    • 1970-01-01
    • 2013-11-13
    • 2020-11-14
    相关资源
    最近更新 更多