Q.トップページのコンテンツビルダーで「ブログ記事一覧」「写真一覧」を表示する際に、同じユーザーの投稿は1つのみに制限できませんか?
▼変更箇所イメージ

A.コンテンツビルダー内のループ処理を変更することで対応可能です。
トップページには「ブログ記事一覧」「写真一覧」コンテンツを配置することができ、それぞれサイト会員ユーザーが投稿した投稿の一覧がそれぞれ表示されます。
一覧に並ぶ順番は「日付{新しい順)」「日付{古い順)」「ランダム」から選択できますが、「ランダム」以外を選択している場合、たとえば同じユーザーが連続して投稿するタイミングがあった場合など、そのユーザーの投稿ばかりが並ぶことになります。
そこで、一覧のバラエティを持たせるために、同じユーザーの投稿の表示回数を制限するためのカスタマイズ方法を紹介します。
方法1
以下では、コンテンツビルダー内のループ処理に、ユーザーIDとその表示回数を追跡する処理を加えています。
編集するファイル: ホームページ (front-page.php)
編集する箇所: 207行目付近に追加
<div class="p-index-archive p-blog-archive"> <?php while ( $cb_queries[$key]['WP_Query']->have_posts() ) : $cb_queries[$key]['WP_Query']->the_post(); $author = get_user_by( 'id', $post->post_author );
↓ いくつかの箇所に追加挿入
<div class="p-index-archive p-blog-archive">
<?php
// 同じユーザーの記事を表示する最大回数
$desired_count = 1;
// 既に表示したユーザーのIDとその表示回数を追跡する配列
$displayed_authors = array();
while ( $cb_queries[$key]['WP_Query']->have_posts() ) :
$cb_queries[$key]['WP_Query']->the_post();
$author = get_user_by( 'id', $post->post_author );
// 現在の投稿のユーザーIDを取得
$author_id = get_the_author_meta('ID');
// そのユーザーの表示回数をチェック
if (!isset($displayed_authors[$author_id])) {
$displayed_authors[$author_id] = 1;
} elseif ($displayed_authors[$author_id] >= $desired_count) {
// このユーザーの表示回数が上限に達している場合はスキップ
continue;
} else {
// 表示回数を増やす
$displayed_authors[$author_id]++;
}
- 最大回数の数字はお好みで変更してください。
- 投稿数が少なく見える場合は、TCDテーマオプション:コンテンツビルダーの設定で、記事の表示数を変更して調節してください。
方法2
方法1では、表示される処理中にチェックを行っておりましたが、表示対象の記事を取得する処理(クエリ)の作成時にチェックする対応もご紹介します。
編集するファイル: ホームページ (front-page.php)
編集する箇所: 42~47行目を置き換え
$args = array( 'post_status' =>'publish', 'post_type' => $cb_queries[$key]['post_type'], 'posts_per_page' => $cb_content['cb_post_num'], 'ignore_sticky_posts' => true );
↓
$post_ids = [];
$all_users = get_users();
foreach ( $all_users as $user ) {
if ( in_array( 'administrator', $user->roles ) ) {
// 管理者の場合、そのユーザーのすべての投稿IDを取得
$user_posts = get_posts( array(
'author' => $user->ID,
'posts_per_page'=> -1,
'fields' => 'ids',
'post_type' => $cb_queries[$key]['post_type'],
) );
$post_ids = array_merge( $post_ids, $user_posts );
} else {
// 非管理者の場合、そのユーザーの最初の1件の投稿IDのみを取得
$user_post = get_posts( array(
'author' => $user->ID,
'posts_per_page'=> 1,
'fields' => 'ids',
'post_type' => $cb_queries[$key]['post_type'],
) );
$post_ids = array_merge( $post_ids, $user_posts );
}
}
$args = array(
'post__in' => $post_ids,
'post_status' =>'publish',
'post_type' => $cb_queries[$key]['post_type'],
'posts_per_page' => $cb_content['cb_post_num'],
'ignore_sticky_posts' => true
);
この記事は役に立ちましたか?
もし参考になりましたら、下のボタンで教えてください。
今後の記事作成の参考とさせて頂きます!