Making WordPress.org

Changeset 14236


Ignore:
Timestamp:
12/04/2024 08:26:43 PM (8 weeks ago)
Author:
coffee2code
Message:

Photo Directory, User: More concise approach to prevent 404s for users who have not contributed any photos.

Props ryelle.
See https://github.com/WordPress/wporg-photo-directory/issues/31.

File:
1 edited

Legend:

Unmodified
Added
Removed
  • sites/trunk/wordpress.org/public_html/wp-content/plugins/photo-directory/inc/user.php

    r14235 r14236  
    5353    public static function init() {
    5454        // Show empty state page for users without contributed photos.
    55         add_action( 'template_redirect', [ __CLASS__, 'allow_empty_authors' ] );
    56     }
    57 
    58     /**
    59      * Allows the author template to load for users who have not contributed any photos.
    60      */
    61     public static function allow_empty_authors() {
    62         global $wp_query;
    63 
    64         if ( is_404() && get_query_var( 'author' ) ) {
    65             $author_id = get_query_var( 'author' );
    66             if ( ! $author_id ) {
    67                 return;
    68             }
    69 
    70             $authordata= get_userdata( $author_id );
    71             if ( ! $authordata ) {
    72                 return;
    73             }
    74 
    75             $wp_query->is_author = true;
    76             $wp_query->is_archive = true;
    77             $wp_query->is_404 = false;
    78 
    79             // Set global authordata variable to allow use of core user template functions.
    80             $GLOBALS['authordata'] = $authordata;
    81         }
     55        add_action( 'pre_handle_404', [ __CLASS__, 'prevent_author_404s' ], 10, 2 );
     56    }
     57
     58    /**
     59     * Prevents 404s for all author pages.
     60     *
     61     * By default, core will only prevent 404s on empty author archives
     62     * if the author is a member of the site. This preempts the handler
     63     * to prevent 404s for all author pages.
     64     *
     65     * @param bool     $preempt  Whether to short-circuit default header status handling. Default false.
     66     * @param WP_Query $query WordPress Query object.
     67     * @return bool
     68     */
     69    public static function prevent_author_404s( $preempt, $query ) {
     70        if ( ! $query->is_main_query() ) {
     71            return $preempt;
     72        }
     73
     74        $author = $query->get( 'author' );
     75        if ( $query->is_author && is_numeric( $author ) && $author > 0 ) {
     76            return true;
     77        }
     78
     79        return $preempt;
    8280    }
    8381
Note: See TracChangeset for help on using the changeset viewer.