<?php
/**
 * Plugin Name: Unlimited Posts For Admins
 * Description: Allow administrators to view all posts on the posts archive page.
 * Version:     1.0.0
 * Update URI:  false
 * Plugin URI:  https://aus.social/@peterwilsoncc/111094215185643333
 */

namespace PWCC\UnlimitedPostsForAdmins;

/**
 * Parse the querystring parameter to allow viewing all posts.
 *
 * This function is hooked into the `pre_get_posts` action.
 *
 * Allow admins to view all posts on archive pages by appending
 * `?unlimited` to the URL.
 *
 * @param WP_Query $wp_query The query object.
 */
function parse_querystring_parameter( $wp_query ) {
	if ( is_admin() || ! $wp_query->is_main_query() || ! $wp_query->is_archive() ) {
		return;
	}

	/*
	 * Only allow users with the export capability to view all posts.
	 *
	 * This capability isn't perfect but listing all posts is a form of
	 * export so it's a close enough match. By default, only site admins
	 * have this capability.
	 */
	if ( ! current_user_can( 'export' ) ) {
		return;
	}

	if ( ! isset( $_GET['unlimited'] ) ) {
		return;
	}

	$wp_query->set( 'posts_per_page', -1 );
}
add_action( 'pre_get_posts', __NAMESPACE__ . '\\parse_querystring_parameter' );