is_main_query() ) { return; } if ( PostType::POST_TYPE !== $query->get( 'post_type' ) ) { return; } if ( $query->get( 'orderby' ) ) { return; // Respect an explicit column sort or search. } $query->set( 'orderby', 'meta_value_num' ); $query->set( 'meta_key', Meta::META_ORDER ); // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_key $query->set( 'order', 'ASC' ); // Include FAQs that have no order meta yet (treated as 0). $query->set( 'meta_query', // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query array( 'relation' => 'OR', array( 'key' => Meta::META_ORDER, 'compare' => 'EXISTS', ), array( 'key' => Meta::META_ORDER, 'compare' => 'NOT EXISTS', ), ) ); $query->set( 'posts_per_page', 500 ); } /** * Enqueue the sortable script on the FAQ list screen. * * @param string $hook Current admin page. * @return void */ public function enqueue( $hook ) { if ( 'edit.php' !== $hook ) { return; } $screen = function_exists( 'get_current_screen' ) ? get_current_screen() : null; if ( ! $screen || PostType::POST_TYPE !== $screen->post_type ) { return; } if ( ! current_user_can( 'edit_others_posts' ) ) { return; } $js = ACCORDION_FAQ_PATH . 'assets/admin/js/reorder.js'; wp_enqueue_script( 'accordion-faq-reorder', ACCORDION_FAQ_URL . 'assets/admin/js/reorder.js', array( 'jquery', 'jquery-ui-sortable' ), is_readable( $js ) ? (string) filemtime( $js ) : ACCORDION_FAQ_VERSION, true ); wp_localize_script( 'accordion-faq-reorder', 'AccordionFaqReorder', array( 'ajax' => admin_url( 'admin-ajax.php' ), 'action' => self::ACTION, 'nonce' => wp_create_nonce( self::NONCE ), 'saving' => __( 'Saving order…', 'accordion-faq-plugin' ), 'saved' => __( 'Order saved.', 'accordion-faq-plugin' ), 'failed' => __( 'Could not save the new order.', 'accordion-faq-plugin' ), ) ); } /** * Persist a new manual order (AJAX). * * @return void */ public function save() { if ( ! check_ajax_referer( self::NONCE, 'nonce', false ) ) { wp_send_json_error( array( 'message' => 'bad_nonce' ), 403 ); } if ( ! current_user_can( 'edit_others_posts' ) ) { wp_send_json_error( array( 'message' => 'forbidden' ), 403 ); } $ids = isset( $_POST['order'] ) ? array_map( 'absint', (array) wp_unslash( $_POST['order'] ) ) : array(); $ids = array_values( array_filter( $ids ) ); if ( empty( $ids ) ) { wp_send_json_error( array( 'message' => 'empty' ), 400 ); } $position = 1; foreach ( $ids as $id ) { if ( PostType::POST_TYPE !== get_post_type( $id ) ) { continue; } update_post_meta( $id, Meta::META_ORDER, $position ); $position++; } wp_send_json_success( array( 'count' => count( $ids ) ) ); } }