使用URL在WordPress中调整图像大小

时间:2014-12-15 05:35:40

标签: wordpress wordpress-theming

我需要在一些帖子中调整一些图片的大小。我可以使用Types plugin获取存储在postmeta中的图片网址 所以使用postmeta我可以获取URL,但是如何调整特定帖子类型的图像大小?

1 个答案:

答案 0 :(得分:4)

首先,您必须从图片网址中找到附加的图片ID。要从图片网址获取附加图片ID,请在主题functions.php文件中添加以下功能:

function pn_get_attachment_id_from_url( $attachment_url = '' ) {
    global $wpdb;

    $attachment_id = false;

    // If there is no url, return.
    if ('' == $attachment_url)
        return;

    // Get the upload directory paths
    $upload_dir_paths = wp_upload_dir();

    // Make sure the upload path base directory exists in the attachment URL, to verify that we're working with a media library image
    if (false !== strpos($attachment_url, $upload_dir_paths['baseurl'])) {

        // If this is the URL of an auto-generated thumbnail, get the URL of the original image
        $attachment_url = preg_replace('/-\d+x\d+(?=\.(jpg|jpeg|png|gif)$)/i', '', $attachment_url);

        // Remove the upload path base directory from the attachment URL
        $attachment_url = str_replace($upload_dir_paths['baseurl'] . '/', '', $attachment_url);

        // Finally, run a custom database query to get the attachment ID from the modified attachment URL
        $attachment_id = $wpdb->get_var($wpdb->prepare("SELECT wposts.ID FROM $wpdb->posts wposts, $wpdb->postmeta wpostmeta WHERE wposts.ID = wpostmeta.post_id AND wpostmeta.meta_key = '_wp_attached_file' AND wpostmeta.meta_value = '%s' AND wposts.post_type = 'attachment'", $attachment_url));
    }

    return $attachment_id;
}

有关详细信息,请参阅网址 - https://philipnewcomer.net/2012/11/get-the-attachment-id-from-an-image-url-in-wordpress/

然后我们需要在function.php中使用图像大小调整功能:

add_image_size( 'latestproperty_thumb', 370,293,true );

要获取图片附件ID,请使用:

$attachid = pn_get_attachment_id_from_url($url);

安装完成后https://wordpress.org/plugins/regenerate-thumbnails/。然后转到工具 - >重新生成缩略图并重新生成所有缩略图。

之后使用它来获取重新生成的图像URL:

$src = wp_get_attachment_image_src($attachid, 'latestproperty_thumb');