2

カスタム フィールドを使用して画像の URL を選択しています。

私のクライアントはすべての画像を挿入してアップロードしているので、これは非常に単純である必要があります。そのため、裏方で処理しようとしているのです。

私が遭遇した問題は、ロード時間を本当に遅くしているフルサイズの画像の URL にあるすべてです。

フルサイズの URL に基づいてサムネイルやその他の画像サイズを挿入する方法はありますか?

私はこれを試してみましたが、私が抱えている問題は、いくつかの画像が同じ歯列を持っていないことです.

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

1 に答える 1

3

wp_get_attachment_image_src()さまざまなサイズの画像を取得するには、wordpress のネイティブ関数に頼るのが最善だと思います。ただし、そのためには、URL ではなく、添付ファイル ID が必要です。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];
}

フランキー・ジャレットに感謝。

次に、他のサイズを簡単に取得できます。

$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="" />';
于 2016-08-10T12:12:06.420 に答える