programing

가장 최근 댓글로 워드프레스 게시물 주문하기

newstyles 2023. 9. 26. 22:03

가장 최근 댓글로 워드프레스 게시물 주문하기

최근 댓글로 워드프레스 게시물을 주문하고 싶습니다.WP_Query 객체를 사용하는 것은 불가능하며 쉽게 작성할 수 있는 맞춤형 $wpdb 쿼리가 필요한 것으로 알고 있습니다.하지만 이 객체를 실행하기 위해 루프를 설정하는 방법을 모르겠습니다.

누가 도와줄 수 있습니까?

할당

select wp_posts.*, max(comment_date) as max_comment_date
from $wpdb->posts wp_posts
right join $wpdb->comments
on id = comment_post_id
group by ID
order by max_comment_date desc
limit 10

query 달러 정도로.10이나 쿼리 자체를 만지작거릴 수 있습니다.(저는 SQL 최적화 닌자가 아닙니다.)그러면 당신의 코드는 마치

<?php
     $results = $wpdb->get_results($query) or die('!');
     foreach ($results as $result):
?>
[insert template here]
<?php endforeach ?>

이 패턴은 코덱스에 의해 더 깊이 다루어지고 있습니다.

저는 네이티브 WP의 좀 더 단순한 기능을 사용했습니다.도움이 되고 누군가가 계속 발전할 수 있기를 바랍니다.get_comments를 이용한 최신 댓글 게시물의 댓글 내용 및 작성자와 함께 게시물의 제목 및 발췌본을 간략화하여 보여드립니다.

    $args = array(
        'status' => 'approve',
        'number' => 6,
        'order' => 'DESC'
    );
    $comments = get_comments($args);

    foreach($comments as $comment) : $count++;

            $post_args = array(
                'post_type' => 'post',
                'p' => $comment->comment_post_ID,
                'posts_per_page' => 1
                );

            $posts = get_posts($post_args);

            foreach($posts as $post) : setup_postdata($post);

                the_title();
                the_excerpt();

            endforeach;

        echo $comment->comment_content;     
        echo $comment->comment_author;

    endforeach;

좋아요 여러분.

좋은 답들이 많이 나오긴 했지만 아무도 시간을 내어 테스트를 하지는 않았습니다.

Hao Lian은 첫 번째 최고의 원본 답변에 대한 공로를 인정받지만 안타깝게도 그의 코드는 댓글이 없는 게시물을 보여주지 않습니다.

키타르 선장은 올바른 경로로 가고 있지만, 그의 코드는 모든 게시물과 첨부 파일을 개별적으로 보여줄 것입니다.

여기 캡틴 키타르의 변형된 버전이 있지만 결과는 '포스트' 유형으로 제한됩니다.(초안을 받지 않기 위해!!) 출판되었습니다.

    select wp_posts.*,
    coalesce(
        (
            select max(comment_date)
            from $wpdb->comments wpc
            where wpc.comment_post_id = wp_posts.id
        ),
        wp_posts.post_date
    ) as mcomment_date
    from $wpdb->posts wp_posts
    where post_type = 'post'
    and post_status = 'publish' 
    order by mcomment_date desc
    limit 10

이것은 오래된 질문이지만, 저는 같은 문제가 있었고 이것을 할 수 있는 훨씬 더 깨끗한 방법을 찾았기 때문에 누구에게나 도움이 될까 봐 여기에 글을 올립니다.

posts_clause 필터를 사용하는 경우 메인 쿼리를 수정하고 The Loop과 모든 정규 루프 함수를 계속 사용할 수 있습니다.

function intercept_query_clauses( $pieces ) {
    global $wpdb;

    $pieces['fields'] = "wp_posts.*,
    (
        select max(comment_date)
        from " . $wpdb->comments ." wpc
        where wpc.comment_post_id = wp_posts.id AND wpc.comment_approved = 1
    ) as mcomment_date";
    $pieces['orderby'] = "mcomment_date desc";

    return $pieces;
}

add_filter( 'posts_clauses', 'intercept_query_clauses', 20, 1 );

sql을 내 목적에 맞게 약간 바꿨지만, 일반적인 개념은 동일합니다.

Hao Lian의 답변의 부록으로 다음 쿼리를 사용할 경우:

select wp_posts.*,
coalesce(
    (
        select max(comment_date)
        from $wpdb->comments wpc
        where wpc.comment_post_id = wp_posts.id
    ),
    wp_posts.post_date
) as mcomment_date
from $wpdb->posts wp_posts
order by mcomment_date desc
limit 10

이는 아직 댓글이 없는 게시물에 혼합하여 post_date, max(댓글_date) 순으로 정렬합니다.

Hao Lian이 제안한 코드는 우리가 POST를 당기는 것을 피하기 위해 아래의 WHERE 조항을 추가해야 한다는 것을 제외하고는 완벽하게 작동합니다.comment_count = 0, 이 상황은 스팸 댓글로 인해 발생합니다.

추가할 WHERE 절은 다음과 같습니다.

WHERE comment_approved = '1' AND comment_type = '' AND post_password = ''

where 절을 추가한 후 코드를 완성하면 다음과 같습니다.

select wp_posts.*, max(comment_date) as comment_date
from wp_posts 
right join wp_comments on id = comment_post_id
WHERE comment_approved = '1' AND comment_type = '' AND post_password = ''
group by ID    
order by comment_date desc
limit 6

다음과 같이 WP_Comment_Query를 WP_Query와 결합하여 수행할 수 있습니다.

// For performance, limit the number of queried comments, 
// but make it be something big enough to account for "duplicate" posts.

$comments_query = new WP_Comment_Query;
$comments = $comments_query->query( array(   'number' => '100'  ) );

if ( $comments ) {
    foreach ( $comments as $comment ) {

// You'll want to convert the dates from string to integer so you can sort them out later
$comment_utf = strtotime($comment->comment_date);

// Build an array of post IDs with the date of the last published comment
$latest_comments[$comment->comment_post_ID] = $comment_utf;
    }}

// Sort the array by date
arsort($latest_comments); foreach ($latest_comments as $key => $value) {    $posts_ordered[] = $key; }

// The nice thing is that WP_Query will remove duplicates by default
$args = array ( 'posts_per_page'         => '10',   'post__in'  => $posts_ordered, 'orderby' => 'post__in');
$query = new WP_Query( $args );
if ( $query->have_posts() ) {
    while ( $query->have_posts() ) {
        $query->the_post();

// Do your stuff (add the template or whatever)

// If you want to add the comment itself, use this:
$comments = get_comments(array('number' => '1', 'post_id' => $post->ID));
foreach($comments as $comment) :
    echo $comment->comment_content;
endforeach;

// That's about it
    }}
wp_reset_postdata();

저는 최대 기능에 추가하면 결과가 엉망이 될 것이라고 생각합니다.MySQL은 각각의 것에서 최대치를 끌어내지 못할 것입니다.풀세트에서 최대한 당겨질 겁니다.결과를 얻을 수 있는 쿼리는 다음과 같습니다.

select wp_posts.*, comment_date
from $wpdb->posts wp_posts
right join $wpdb->comments
on id = comment_post_id
group by ID
order by comment_date desc
limit 10

그런 다음 WP 규칙을 따르려면 이를 사용한 다음 대부분의 템플릿이 사용하고 있는 기능(루프 기준)을 사용할 수 있습니다.

$results = $wpdb->get_results($query) or die('!');
     foreach ($results as $post):
    setup_postdata($post);

승인 여부에 관계없이 사용자 지정 게시물 유형 '질문'에 대한 최신 의견 3개를 확인할 수 있습니다.

global $wpdb;

$results = $wpdb->get_results(
    "
    SELECT wp_posts.ID, MAX(comment_date) AS max_comment_date
    FROM wp_posts
    RIGHT JOIN wp_comments
    ON id = comment_post_id
    WHERE wp_posts.post_type = 'question'
    AND wp_posts.post_status = 'publish'
    GROUP BY ID
    ORDER BY max_comment_date DESC
    LIMIT 3
    "
);

foreach ($results as $result) {
    $posts_arr[] = $result->ID;
}

$args = array(
    'post_type' => 'question',
    'post__in'  => $posts_arr,
    'orderby'  => 'post__in',
);

$the_query = new WP_Query( $args );

Lucian's BEAUTIFUL 솔루션을 사용하여 기존 WP_Query를 변경/필터링하여 최신 댓글로 게시물을 정렬해야 했습니다.테스트하고 완벽하게 작동하는 코드는 다음과 같습니다.

$comments_query = new WP_Comment_Query;
$comments       = $comments_query->query( array(   'number' => '100'  ) );

if ( $comments ) {
  foreach ( $comments as $comment ) {
    $comment_utf = strtotime($comment->comment_date);
    $latest_comments[$comment->comment_post_ID] = $comment_utf;
  }

  // Sort the array by date
  arsort( $latest_comments );
  foreach( $latest_comments as $key => $value ) {
    $posts_ordered[] = $key;
  }

  $query->set( 'post__in', $posts_ordered );
  $query->set( 'orderby', 'post__in' );
}

add_shortcode('show_recent_comments_posts','show_recent_comments_posts');
 function show_recent_comments_posts(){
     ob_start();
     global $wpdb;

$results = $wpdb->get_results("select * from $wpdb->comments where comment_approved = 1 order by comment_date desc");

foreach ($results as $result) {
    $posts_arr[] = $result->comment_post_ID;
}

 $paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1;
$args = array(
    'post_type' => 'post',
    'post__in'  => array_unique($posts_arr),
    'orderby'  => 'post__in',
    'posts_per_page' => 12,
    'paged' => $paged,
            'post_status'=>'publish',
);

$the_query = new WP_Query( $args );

if ($the_query->have_posts()) {
   ?> 
<section class="cards-wrapper"><?php
 while ($the_query->have_posts()) {
  $the_query->the_post();
 $args = array('i'=>$i);
get_template_part('content_gals', '', $args );

}
?></section>
 <div class="pagination">
    <?php 
        echo paginate_links( array(
            'base'         => str_replace( 999999999, '%#%', esc_url( get_pagenum_link( 999999999 ) ) ),
            'total'        => $the_query->max_num_pages,
            'current'      => max( 1, get_query_var( 'paged' ) ),
            'format'       => '?paged=%#%',
            'show_all'     => false,
            'type'         => 'plain',
            'end_size'     => 2,
            'mid_size'     => 1,
            'prev_next'    => true,
            'prev_text'    => sprintf( '<i></i> %1$s', __( 'Prev', 'text-domain' ) ),
            'next_text'    => sprintf( '%1$s <i></i>', __( 'Next', 'text-domain' ) ),
            'add_args'     => false,
            'add_fragment' => '',
        ) );
    ?>
</div><?php
}
    
return ob_get_clean();
 }

언급URL : https://stackoverflow.com/questions/698438/ordering-wordpress-posts-by-most-recent-comment