正如标题所说,我有一个名为book的自定义帖子类型。 仅当存在具有该名称的“book”帖子类型时,每个用户才能创建另一个名为read_book的自定义帖子类型。 所以现在我试图通过获得具有相同标题的出现次数最多的帖子名称来显示阅读量最大的书籍。 那可能吗 ? 谢谢!
PS:如果我有3个名为A的read_books,2名为B,1名为C,我想显示名为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;
答案 0 :(得分: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..