2017-03-19 4 views
0

タイトルには、bookという名前のカスタムポストタイプがあります。 各ユーザーは、その名前の「ブック」タイプが存在する場合にのみ、read_bookという名前の別のカスタム投稿タイプを作成できます。 今、私は、同じタイトルの出現数が最も多い投稿名を取得して、最も読んだ本を表示しようとしています。 これは可能ですか? ありがとうございました!最も読んだ本のカスタムポスト(同じタイトルのトップポストを見つける)

PS:私は名前のBと名前のCと1と名前がA、2と3 read_booksを持っている希望の場合、私は名前A.

編集とブックポストを表示したいと思います:これは、どのように見えるか

// initial query to get the title 
$read_books = new WP_Query(array(
    'post_type' => 'read_book', 
    'posts_per_page' => 1, // only the title is needed, so one post is enough 
    'meta_key' => 'title', // here should happen the magic 
    'orderby' => 'meta_value_num', 
    'order' => 'DESC', 
    'date_query' => array(// optional (most read book from past 30 days) 
     'after' => date('Y-m-d', strtotime('-30 days')), // don't query the whole database 
    ) 
)); 

if ($read_books->have_posts()): 
    while ($read_books->have_posts()): $read_books->the_post(); 
    $book_title = get_the_title; 
    endwhile; 
endif; 

// final query 
$most_read_book = new WP_Query(array(
    'post_type' => 'book', 
    's' => $book_title; // it should be only one book with that title because users can't add custom titles 
    'posts_per_page' => 1, 
)); 

if ($most_read_book->have_posts()): 
    while ($most_read_book->have_posts()): $most_read_book->the_post(); 
    // book info displayed on frontend 
    endwhile; 
endif; 
+1

あなたのやり遂げたことを分かち合ってください。 – uvishere

+0

最新の回答をご覧ください。 meta_keyとorderbyは単なる例です。私はそれが数字を探すために動作しないことを知っています。だから私はここに私の質問を掲載した。 – Mitrescu

答えて

0

私は解決策を見つけましたが、私は最良のものかどうかはわかりません。しかし、それはうまく動作します。 おそらく速いものがあります。

//get the title string 
$booksQuery = new WP_Query(array(
    'post_type' => 'read_book', 
    'orderby' => 'date', 
    'order' => 'DESC', 
    'posts_per_page' => -1, 
    'post_status' => 'publish', 
    'no_found_rows' => true, 
    'date_query' => array(
     'after' => date('Y-m-d', strtotime('-90 days')), 
    ) 
)); 
$allTitles = array(); 
if ($booksQuery->have_posts()): 
    while ($booksQuery->have_posts()): $booksQuery->the_post(); 
     $allTitles[] = get_the_title(); 
    endwhile; 
endif; 
$allTitles = array_count_values($allTitles); // group titles 
asort($allTitles); // sort titles by number of occurrences 
$topTitle = key(array_slice($allTitles, -1, 1, TRUE)); // get the needed title 
$finalTitle = str_replace([' – ', ' — ', ' - '], ' ', $topTitle); // the title is stored with a different character in database, so just remove it from title 

//final query 
$mrQuery = new WP_Query(array(
    's' => $finalTitle, 
    'post_type' => 'book', 
    'posts_per_page' => 1, 
    'post_status' => 'publish', 
    'no_found_rows' => true, 
)); 

// the frontend code here.. 
関連する問題