Attachment Archives

添付ファイルのアーカイブを表示します

WordPressでは標準機能で、添付画像アーカイブというのはありませんが 少し工夫をすると表示できるようです。

注意事項

以下のコードを、functions.phpに追加したら

  • 設定/パーマリンク設定で なにも変更せずに 更新ボタンを押してください。パーマリンクをフラッシュするためです。
  • カスタム投稿アーカイブリンクを取得する get_post_type_archive_link( 'attachment' )は、多分falseを返すので使えません
    $post_type_obj->has_archive が falseになるため

    http://example.com/wp-37/?post_type=attachment

    または、カテゴリーアーカイブURLのカhttp://example.com/wp/archives/category/artworkをhttp://example.com/wp/archives/attachedに変更する等して、アーカイブURLを見つけてください

functions.php

add_filter( 'register_post_type_args', 'rd_change_default_post_type_args', 10, 2 );

function rd_change_default_post_type_args( $args, $post_type ) {

	if ( $post_type== 'attachment' ) {
		
		$args[ 'has_archive' ]= true;
		$args[ 'rewrite' ]	= array( 'slug'=> 'attached' );
	}

	return $args;
}

add_action( 'pre_get_posts', 'rd_attachment_archve_post_status' );

function rd_attachment_archve_post_status( $wp_query ) {
	
	if ( !is_admin() && $wp_query->is_main_query() ) {

		if ( !is_singular() && $wp_query->get( 'post_type' )== 'attachment' ) {
			
			$wp_query->set( 'post_status', 'inherit' );
		}
	}
}

2018/10/22 追記

$wp_query->set(‘post__not_in’, $exclude);

をセットすることで、アーカイブに表示する添付ファイルの種類を制限することができます。

以下のコードは表示するアーカイブを、添付ファイルだけに限定する例です。

応用すれば、特定のファイルタイプのみ表示するといった事もできるかもしれませんね

add_filter( 'register_post_type_args', 'rd_change_default_post_type_args', 10, 2 );

function rd_change_default_post_type_args( $args, $post_type ) {

	if ( $post_type== 'attachment' ) {

		$args[ 'has_archive' ]= true;
		$args[ 'rewrite' ]	= array( 'slug'=> 'attached' );
	}

	return $args;
}

add_action( 'pre_get_posts', 'rd_attachment_archve_post_status' );

function rd_attachment_archve_post_status( $wp_query ) {

	if ( !is_admin() && $wp_query->is_main_query() ) {

		if ( !is_singular() && $wp_query->get( 'post_type' )== 'attachment' ) {

			$wp_query->set( 'post_status', 'inherit' );
			$exclude= exclude_attached_file_ids();
			$wp_query->set('post__not_in', $exclude);
		}
	}
}

function exclude_attached_file_ids(){
	
	$attachments= get_posts(array('post_type'=>'attachment','numberposts'=> -1));
	
	foreach( $attachments as $attachment ) {
		if( $attachment->post_parent== 0 ) {
			$ids[]= $attachment->ID; 
		}
		
	}

	return $ids;
}

[emulsion_relate_posts]