WP PLUGIN アーカイブページの投稿表示順設定

・管理画面メニュー(サブメニュー)の修正
・1ページ表示件数の追加
・pre_get_postするクエリの追加
・検索用設定の追加
This commit is contained in:
2021-05-06 21:09:35 +09:00
parent 05b5fa91aa
commit 803c742a9f
8 changed files with 773 additions and 234 deletions
+106
View File
@@ -0,0 +1,106 @@
<?php
if ( ! defined( 'ABSPATH' ) ) {
exit;
} // Exit if accessed directly
if ( ! trait_exists( 'APOP_ORDER_SETTING' ) ) {
trait APOP_ORDER_SETTING {
public function set_query() {
add_action( 'pre_get_posts', array( $this, 'apop_posts_per_page' ), 1 );
}
public function apop_posts_per_page( $query ) {
if ( is_admin() || ! $query->is_main_query() ) {
return;
}
if ( is_home() ) {
return;
}
if ( is_search() ) {
$this->set_per_page( $query, 'search' );
$this->set_search_orderby( $query );
}
if ( is_category() ) {
$cat = get_category_by_slug( $query->query_vars['category_name'] );
$this->set_per_page( $query, 'category' );
$this->set_orderby( $query, $cat->term_id, 'category', 'cat' );
}
if ( is_tag() ) {
$tag = get_term_by( 'slug', $query->query_vars['tag'], 'post_tag' );
$this->set_per_page( $query, 'tag' );
$this->set_orderby( $query, $tag->term_id, 'post_tag', 'tag' );
}
if ( is_tax() ) {
$this->set_per_page( $query, 'tax' );
$this->set_orderby( $query, get_queried_object_id(), 'tax', 'tax' );
}
}
private function set_per_page( $query, $target ) {
$per_page_option = get_option( '_apop_per_page' );
if ( ! isset( $per_page_option[ $target ] ) ) {
return;
}
if ( $per_page_option[ $target ] == 'default' ) {
return;
}
$query->set( 'posts_per_page', $per_page_option[ $target ] );
}
private function set_search_orderby( $query ) {
$apop_search_order = get_option( '_apop_search_order' ) ?? 1;
if ( $apop_search_order == 2 ) {
$query->set( 'meta_key', '_apop_post_search' );
$query->set( 'orderby', array( 'meta_value_num' => 'ASC' ) );
}
}
private function set_orderby( $query, $id, $target, $order_key ) {
$order_settings = get_option( '_apop_' . $order_key . '_order' );
if ( isset( $order_settings['target_cat'][ $id ] ) && $order_settings['target_cat'][ $id ] == 1 ) {
$sort_meta_key = '_apop_post_' . $target . '_' . $id;
$query->set( 'meta_key', $sort_meta_key );
$query->set( 'orderby', array( 'meta_value_num' => 'ASC' ) );
}
}
public static function get_orderby( $id, $target, $order_key ): ?array {
$order_settings = get_option( '_apop_' . $order_key . '_order' );
if ( isset( $order_settings['target_cat'][ $id ] ) && $order_settings['target_cat'][ $id ] == 1 ) {
$sort_meta_key = '_apop_post_' . $target . '_' . $id;
return array(
'meta_key' => $sort_meta_key,
'orderby' => array( 'meta_value_num' => 'ASC' )
);
}
return null;
}
public static function get_per_page( $target ) {
$per_page_option = get_option( '_apop_per_page' );
if ( ! isset( $per_page_option[ $target ] ) ) {
return;
}
if ( $per_page_option[ $target ] == 'default' ) {
return;
}
return array( 'posts_per_page' => $per_page_option[ $target ] );
}
}
}