web-dev-qa-db-ja.com

現在のページの添付ファイルが…より小さい場合、親ページの添付ファイルを照会する

現在のページの添付ファイルをクエリするためにWPQueryget_children($query_images_args)を使用しています。現在のページに添付ファイルが割り当てられていない場合は、親ページの画像をクエリします。

これは私が望む方法では機能しますが、私が目指しているものがもう1つあります。私はすでにフォーラムで同じ質問を(同じコードサンプルで)尋ねました。 https://wordpress.stackexchange.com/questions/62624/only-get-attachments-that-are-associated-with-a-gallery ただしこの質問で私は同じ問題に取り組むために異なるアプローチを求めます。

$query_images_args = array(
        'post_type' => 'attachment',
        'post_mime_type' =>'image',
        'post_status' => 'inherit',
        'posts_per_page' => -1,
        'post_parent' => $post->ID
    );

    $attachments = get_children($query_images_args);

    if ( empty($attachments) ) {
        $query_images_args = array(
            'post_type' => 'attachment',
            'post_mime_type' =>'image',
            'post_status' => 'inherit',
            'posts_per_page' => -1,
            'post_parent' => $post->post_parent
        );
    }

    $query_images = new WP_Query( $query_images_args );
    $images = array();
    foreach ( $query_images->posts as $image) {
        $images[] = wp_get_attachment_image_src( $image->ID, 'large');
    }

現在のページの添付画像を照会していますが、現在のページに画像が割り当てられていない場合は、親ページの画像を照会します。さらに、私は大きな画像に対してのみ追加のフィルタ処理をしています。

しかし、現在のページに「小さい」画像しかない場合は、親ページの画像を照会することが可能かどうかわかりません。

そのため、本質的に、現在の投稿に画像がある場合は「大きい」画像のみを取得し、現在の投稿に画像がない場合は親ページの「大きい」画像のみを取得したいと思います。

それを行う方法についての任意のアイデア!

2
mathiregister

現在のページに「小さい」画像しかないかどうかをどのように定義しているのか、よくわかりません。しかし、その答えはwp_get_attachment_image_src関数の中にあると思います。この関数は画像のURLだけでなく幅と高さも返します。

それで、あなたは300ピクセル以上の幅の画像だけに興味があるとしましょう。まず、これをあなたのfunctions.phpファイルに追加してください:

function return_my_big_images( $id ) {

    $query_images_args = array(
        'post_type' => 'attachment',
        'post_mime_type' => 'image',
        'post_status' => 'inherit',
        'posts_per_page' => -1,
        'post_parent' => $id
    );

    $attachments = get_children( $query_images_args );

    $big_images = array();
    foreach( $attachments as $image ) {
        $image_src = wp_get_attachment_image_src( $image->ID, 'full' );
        if ( $image_src[1] > 300 ) // $image_src[1] is where pixel width is stored
            $big_images[] = $image_src[0]; // $image_src[0] is its url
    }

    return $big_images;

}

それから、上記のコードの代わりに、これを追加できます。

global $post;

// return all images bigger than 300px wide attached to current post
$big_images = return_my_big_images( $post->ID );

// if none, return images bigger than 300px wide attached to post parent
if ( empty( $big_images ) )
    $big_images = return_my_big_images( $post->post_parent );
4
SeventhSteel