array( orderby, order ). */ const SORTS = array( 'newest' => array( 'date', 'DESC' ), 'oldest' => array( 'date', 'ASC' ), 'title' => array( 'title', 'ASC' ), 'modified' => array( 'modified', 'DESC' ), 'comments' => array( 'comment_count', 'DESC' ), ); /** @var int Widgets rendered so far on this request. */ private static $instances = 0; /** * Turn raw shortcode/block/REST attributes into a safe, complete config. * * @param array $raw Raw attributes. * @return array */ public static function normalize_config( $raw ) { $raw = is_array( $raw ) ? $raw : array(); // Empty shortcode/block attributes mean "use the setting". $raw = array_filter( $raw, static function ( $value ) { return null !== $value && '' !== $value; } ); $post_types = AFSAdmin::viewable_post_types(); $post_type = isset( $raw['post_type'] ) ? sanitize_key( $raw['post_type'] ) : ''; if ( ! isset( $post_types[ $post_type ] ) ) { $post_type = AFSAdmin::afs_retrieve( '_general_post_type' ); if ( ! isset( $post_types[ $post_type ] ) ) { $post_type = 'post'; } } $taxonomy = isset( $raw['post_tax'] ) ? sanitize_key( $raw['post_tax'] ) : sanitize_key( AFSAdmin::afs_retrieve( '_general_post_taxonomy' ) ); if ( 'none' === $taxonomy || '' === $taxonomy || ! is_object_in_taxonomy( $post_type, $taxonomy ) ) { $taxonomy = ''; } // "terms" is the clear name; filter_type (1.0.x) and filter_by (documented in the 1.0.x readme) mean the same thing. $terms = array(); foreach ( array( 'terms', 'filter_type', 'filter_by' ) as $attr ) { if ( ! empty( $raw[ $attr ] ) ) { $terms = is_array( $raw[ $attr ] ) ? $raw[ $attr ] : explode( ',', (string) $raw[ $attr ] ); break; } } $terms = array_values( array_unique( array_filter( array_map( 'sanitize_title', array_slice( $terms, 0, 50 ) ) ) ) ); $terms = array_values( array_diff( $terms, array( 'all' ) ) ); if ( '' === $taxonomy ) { $terms = array(); } $per_page = isset( $raw['posts_per_page'] ) ? absint( $raw['posts_per_page'] ) : 0; if ( ! $per_page ) { $per_page = absint( AFSAdmin::afs_retrieve( '_general_posts_per_page' ) ); } $per_page = min( 100, max( 1, $per_page ? $per_page : 10 ) ); $orderby = isset( $raw['orderby'] ) ? sanitize_key( $raw['orderby'] ) : 'date'; $orderby = in_array( $orderby, array( 'date', 'title', 'modified' ), true ) ? $orderby : 'date'; $order = ( isset( $raw['order'] ) && 'ASC' === strtoupper( (string) $raw['order'] ) ) ? 'ASC' : 'DESC'; $design = AFS_Design::resolve( isset( $raw['design'] ) ? $raw['design'] : '' ); if ( isset( $raw['layout'] ) ) { $layout = sanitize_key( $raw['layout'] ); } elseif ( AFS_Design::has_own_markup( $design ) ) { // A design with its own item markup starts in the layout it was drawn for unless the feed says otherwise. $layout = AFS_Design::default_layout( $design ); } else { $layout = AFSAdmin::afs_retrieve( '_general_layout' ); } $layout = 'grid' === $layout ? 'grid' : 'list'; $bool = static function ( $key, $default ) use ( $raw ) { return isset( $raw[ $key ] ) && '' !== $raw[ $key ] ? wp_validate_boolean( $raw[ $key ] ) : $default; }; $cards = AFS_Card::normalize_options( $raw, $design ); return array_merge( $cards, array( 'post_type' => $post_type, 'taxonomy' => $taxonomy, 'terms' => $terms, 'per_page' => $per_page, 'orderby' => $orderby, 'order' => $order, 'layout' => $layout, 'show_tabs' => $bool( 'show_tabs', 1 === (int) AFSAdmin::afs_retrieve( '_general_show_filters' ) ), 'show_views' => $bool( 'show_views', 1 === (int) AFSAdmin::afs_retrieve( '_general_views' ) ), 'show_search' => $bool( 'show_search', true ), 'show_months' => $bool( 'show_months', true ), 'show_years' => $bool( 'show_years', true ), // Opt-in helpers (off unless the shortcode, block or setting turns them on, so existing output is unchanged). 'show_sort' => $bool( 'show_sort', 1 === (int) AFSAdmin::afs_retrieve( '_general_show_sort' ) ), 'show_chips' => $bool( 'show_chips', 1 === (int) AFSAdmin::afs_retrieve( '_general_show_chips' ) ), // classic (the 2.0 look) or modern; the markup is the same, only a class and a stylesheet differ. 'design' => $design, // Starting values for the filters. 'search' => isset( $raw['search'] ) ? sanitize_text_field( $raw['search'] ) : '', 'month' => isset( $raw['filter_months'] ) ? self::clean_month( $raw['filter_months'] ) : 0, 'year' => isset( $raw['filter_years'] ) ? self::clean_year( $raw['filter_years'] ) : 0, 'page' => isset( $raw['offset'] ) ? max( 1, absint( $raw['offset'] ) ) : 1, ) ); } /** * Validate the visitor's current filter choices against a config. * * @param array $raw Keys: s, term, month, year, paged, layout, sort. * @param array $config Normalized config (supplies the defaults). * @return array */ public static function normalize_state( $raw, $config ) { $raw = is_array( $raw ) ? $raw : array(); $term = isset( $raw['term'] ) ? sanitize_title( $raw['term'] ) : ''; if ( '' === $config['taxonomy'] || 'all' === $term ) { $term = ''; } elseif ( $config['terms'] && ! in_array( $term, $config['terms'], true ) ) { $term = ''; } $layout = isset( $raw['layout'] ) ? sanitize_key( $raw['layout'] ) : $config['layout']; $sort = isset( $raw['sort'] ) ? sanitize_key( $raw['sort'] ) : ''; return array( 's' => isset( $raw['s'] ) ? sanitize_text_field( $raw['s'] ) : $config['search'], 'term' => $term, 'month' => isset( $raw['month'] ) ? self::clean_month( $raw['month'] ) : $config['month'], 'year' => isset( $raw['year'] ) ? self::clean_year( $raw['year'] ) : $config['year'], 'paged' => isset( $raw['paged'] ) ? min( 100000, max( 1, absint( $raw['paged'] ) ) ) : $config['page'], 'layout' => in_array( $layout, array( 'list', 'grid' ), true ) ? $layout : $config['layout'], // '' means the feed's own order; anything that is not a known choice is ignored. 'sort' => isset( self::SORTS[ $sort ] ) ? $sort : '', ); } private static function clean_month( $value ) { $value = absint( $value ); return ( $value >= 1 && $value <= 12 ) ? $value : 0; } private static function clean_year( $value ) { $value = absint( $value ); return ( $value >= 1000 && $value <= 9999 ) ? $value : 0; } /** * The query for a config + state. * * @return WP_Query */ public static function query( $config, $state ) { return AFS_Query::run( $config, $state ); } /** Terms shown as tabs (WP_Term[]). */ private static function tab_terms( $config ) { if ( ! $config['taxonomy'] ) { return array(); } // Cached per taxonomy and invalidated whenever any term changes (core bumps the terms change counter). $cache_key = 'afs_tabs_' . $config['taxonomy'] . '_' . wp_cache_get_last_changed( 'terms' ); $terms = wp_cache_get( $cache_key, 'afs' ); if ( false === $terms ) { $terms = get_terms( array( 'taxonomy' => $config['taxonomy'], 'orderby' => 'term_id', ) ); if ( is_wp_error( $terms ) ) { return array(); } wp_cache_set( $cache_key, $terms, 'afs', DAY_IN_SECONDS ); } $list = array(); foreach ( $terms as $term ) { if ( 'uncategorized' === $term->slug ) { continue; } if ( $config['terms'] && ! in_array( $term->slug, $config['terms'], true ) ) { continue; } $list[] = $term; } return $list; } /** Years that have published posts of a type, newest first. */ private static function years( $post_type ) { global $wpdb; $key = 'afs_years_' . $post_type . '_' . wp_cache_get_last_changed( 'posts' ); $years = wp_cache_get( $key, 'afs' ); if ( false === $years ) { // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery -- Cached just below; no core API lists archive years for one post type. $years = $wpdb->get_col( $wpdb->prepare( "SELECT DISTINCT YEAR(post_date) FROM {$wpdb->posts} WHERE post_type = %s AND post_status = 'publish' ORDER BY 1 DESC", $post_type ) ); $years = array_map( 'absint', $years ); wp_cache_set( $key, $years, 'afs', DAY_IN_SECONDS ); } return $years; } /** * A landmark label that stays unique when several feeds share a page. * * @param string $label Base label. * @param int $instance 1-based feed number on the page. * @return string */ private static function label( $label, $instance ) { return $instance > 1 ? sprintf( '%s %d', $label, $instance ) : $label; } /** The page URL without this plugin's query args. */ public static function current_url() { global $wp; // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Public, read-only filter state. $query = map_deep( wp_unslash( $_GET ), 'sanitize_text_field' ); $url = add_query_arg( $query, user_trailingslashit( home_url( $wp->request ) ) ); return remove_query_arg( self::URL_KEYS, $url ); } /** Visitor state from the query string (used for the first widget on a page). */ public static function request_state() { // phpcs:disable WordPress.Security.NonceVerification.Recommended -- Public, read-only filter state; validated in normalize_state(). $get = map_deep( wp_unslash( $_GET ), 'sanitize_text_field' ); // phpcs:enable $state = array(); foreach ( array( 'afs_s' => 's', 'afs_term' => 'term', 'afs_month' => 'month', 'afs_year' => 'year', 'afs_page' => 'paged', 'afs_layout' => 'layout', 'afs_sort' => 'sort', ) as $param => $key ) { if ( isset( $get[ $param ] ) && is_scalar( $get[ $param ] ) ) { $state[ $key ] = $get[ $param ]; } } return $state; } /** URL for a state: only non-default bits are added. */ private static function url_for( $base, $state, $overrides = array() ) { $state = array_merge( $state, $overrides ); $args = array(); if ( '' !== $state['s'] ) { $args['afs_s'] = $state['s']; } if ( $state['term'] ) { $args['afs_term'] = $state['term']; } if ( $state['month'] ) { $args['afs_month'] = $state['month']; } if ( $state['year'] ) { $args['afs_year'] = $state['year']; } if ( $state['paged'] > 1 ) { $args['afs_page'] = $state['paged']; } if ( ! empty( $state['sort'] ) ) { $args['afs_sort'] = $state['sort']; } return add_query_arg( $args, $base ); } /** * Full widget: filters plus the first page of results. * * @param array $config Normalized config. * @param array $state Normalized state. * @param bool $syncs_url Whether this widget mirrors its state into the address bar. * @return string HTML. */ public static function render_widget( $config, $state, $syncs_url = false ) { ++self::$instances; $n = self::$instances; $id = 1 === $n ? 'afs-wrapper' : 'afs-wrapper-' . $n; // 1.x element IDs, only on the first feed (IDs must be unique). Part of the compatibility layer. $legacy = 1 === $n && AFS_Compat::enabled(); $base = self::current_url(); // The two designs with their own markup mark the feed root when filters are active and when chips are on, so the // stylesheet can show a Reset button only when it is the one way to clear the filters. The script keeps it current. $discovery = AFS_Design::is_discovery( $config['design'] ); $root_extra = ''; if ( $discovery ) { $root_extra .= $config['show_chips'] ? ' afs-has-chips' : ''; // The Resource Library is always a list, so its switch is hidden and the feed has no switch to make room for. $root_extra .= $config['show_views'] && AFS_Design::LIBRARY !== $config['design'] ? ' afs-has-switch' : ''; $root_extra .= self::has_active_filters( $state ) ? ' afs-is-filtered' : ''; } $client = array( 'post_type' => $config['post_type'], 'post_tax' => $config['taxonomy'], 'terms' => implode( ',', $config['terms'] ), 'posts_per_page' => $config['per_page'], 'orderby' => $config['orderby'], 'order' => $config['order'], 'layout' => $config['layout'], ); // Only when on, so the markup of every existing feed is unchanged. The script passes it on to the REST route. if ( $config['show_chips'] ) { $client['show_chips'] = '1'; } elseif ( 1 === (int) AFSAdmin::afs_retrieve( '_general_show_chips' ) ) { // The feed turned the chips off while the site setting has them on. The results route falls back to the setting // for anything it is not told, so "off" has to be sent or the first update would switch them on. $client['show_chips'] = '0'; } // A design with its own item markup must produce the same items on page load and through the REST route, so the // design and its card options travel with every request. Classic and Modern send nothing extra (see below). if ( AFS_Design::has_own_markup( $config['design'] ) ) { $client = array_merge( $client, array( 'design' => $config['design'] ), AFS_Card::client_options( $config ) ); } elseif ( AFS_Design::has_own_markup( AFS_Design::resolve( '' ) ) ) { // A Classic or Modern feed on a site whose own design is one of the new ones must say so: left out, the results // route would fall back to the site design and render that design's items inside this feed. On every other site // nothing extra is sent, so a Classic or Modern feed's markup stays exactly as it was. $client['design'] = $config['design']; } $tabs = array(); if ( $config['show_tabs'] ) { $tabs = self::tab_terms( $config ); if ( count( $tabs ) < 2 && ! ( 1 === count( $tabs ) && ! $config['terms'] ) ) { $tabs = array(); } } ob_start(); ?>
%s
', sprintf( /* translators: 1: first result number, 2: last result number, 3: total results. */ esc_html__( 'Displaying %1$s to %2$s (of %3$s)', 'ajax-filter-search' ), '' . esc_html( number_format_i18n( $first ) ) . '', '' . esc_html( number_format_i18n( $last ) ) . '', '' . esc_html( number_format_i18n( $found ) ) . '' ) ); } // An empty result in the new designs has one clear action below the message, so its chips drop their own Clear all. $chips_html = $config['show_chips'] ? self::chips( $config, $state, $base, $instance, ! ( $own && ! $query->have_posts() ) ) : ''; if ( $own ) { // A design with its own markup groups the active filters and the result count in one bar above the items. if ( '' !== $chips_html || '' !== $count_html ) { echo ''; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Escaped where built. } } else { echo $chips_html; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Escaped in chips(). } if ( $query->have_posts() ) { // A design with its own item markup supplies its own item wrapper classes and has no table header. $options = $own ? AFS_Card::template_options( $config ) : array(); if ( $own ) { if ( ! empty( $options['show_image'] ) ) { AFS_Card::prime( $query ); } } else { echo ''; } echo '' . esc_html__( 'No results found.', 'ajax-filter-search' ) . '
'; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Escaped in empty_message(). if ( $config['show_chips'] && self::has_active_filters( $state ) ) { printf( '', esc_url( self::url_for( $base, $state, self::cleared_filters() ) ), esc_html__( 'Clear all filters', 'ajax-filter-search' ) ); } } return array( 'html' => ob_get_clean(), 'found' => $found, 'pages' => $pages, ); } /** * The empty result of the new designs: what was searched for, and what to do next. Classic and Modern keep "No results found." * * @param array $state Normalized state. * @return string HTML, escaped. */ private static function empty_message( $state ) { if ( '' !== $state['s'] ) { /* translators: %s: the visitor's search text. */ $title = sprintf( __( 'No results for ā%sā.', 'ajax-filter-search' ), $state['s'] ); } elseif ( self::has_active_filters( $state ) ) { $title = __( 'No results match these filters.', 'ajax-filter-search' ); } else { $title = __( 'No results found.', 'ajax-filter-search' ); } $hint = self::has_active_filters( $state ) ? ' ' . esc_html__( 'Try a different word or clear the filters.', 'ajax-filter-search' ) . '' : ''; return '' . esc_html( $title ) . '' . $hint . '
'; } /** Labels for the sort choices. */ private static function sort_labels() { return array( 'newest' => __( 'Newest', 'ajax-filter-search' ), 'oldest' => __( 'Oldest', 'ajax-filter-search' ), 'title' => __( 'A to Z', 'ajax-filter-search' ), 'modified' => __( 'Recently updated', 'ajax-filter-search' ), 'comments' => __( 'Most commented', 'ajax-filter-search' ), ); } /** The sort choice that equals the feed's own order, or '' when it matches none of them. */ private static function default_sort( $config ) { foreach ( self::SORTS as $key => $pair ) { if ( $pair[0] === $config['orderby'] && $pair[1] === $config['order'] ) { return $key; } } return ''; } /** The sort select. data-default lets the script leave the default out of the address bar. */ private static function sort_select( $id, $config, $state ) { $default = self::default_sort( $config ); $selected = $state['sort'] ? $state['sort'] : $default; $html = sprintf( ''; } private static function has_active_filters( $state ) { return '' !== $state['s'] || $state['term'] || $state['month'] || $state['year']; } /** State overrides that clear every filter (the sort and layout are not filters and are kept). */ private static function cleared_filters() { return array( 's' => '', 'term' => '', 'month' => 0, 'year' => 0, 'paged' => 1, ); } /** * Active filters as removable chips, plus Clear all. Each chip is a plain link, so it works without JavaScript; * the script turns a click into a fetch. */ private static function chips( $config, $state, $base, $instance, $with_clear = true ) { if ( ! self::has_active_filters( $state ) ) { return ''; } global $wp_locale; $chips = array(); if ( '' !== $state['s'] ) { /* translators: %s: the visitor's search text. */ $chips['s'] = sprintf( __( 'Search: %s', 'ajax-filter-search' ), $state['s'] ); } if ( $state['term'] ) { $term = $config['taxonomy'] ? get_term_by( 'slug', $state['term'], $config['taxonomy'] ) : false; $chips['term'] = $term ? $term->name : $state['term']; } if ( $state['month'] ) { $chips['month'] = $wp_locale->get_month( $state['month'] ); } if ( $state['year'] ) { $chips['year'] = (string) $state['year']; } $empty = array( 's' => '', 'term' => '', 'month' => 0, 'year' => 0, ); $out = '