본문 바로가기
PHP & WP

[WordPress] 포스트가 작성된 날짜(post_date)를 기간으로 검색하기

by 펜네임 2022. 5. 19.

구현하고 싶은 것

게시글을 작성일이라는 조건으로 검색하고 싶었다.

이 때, 시작일과 종료일을 두어서 기간 내에 작성된 게시글을 모두 검색해야 했다.

 

먼저 아래 화면처럼 시작일과 종료일을 가진 검색조건을 만들어줬다.

 

 

 

1. HTML

<input type="text" id="start_date" name="start_date" value="'.$_REQUEST['start_date'].'" placeholder="시작일" class="datepicker" readonly>
<input type="text" id="end_date" name="end_date" value="'.$_REQUEST['end_date'].'" placeholder="종료일" class="datepicker" readonly>

 

내가 수정하는 사이트에 이미 테마가 적용되어 있기 때문인지, WP에서 원래 제공하는 것인지는 모르겠지만

text 타입의 input이라도 특정 class일 경우 클릭 시에 달력이 나오게 하는 css와 js가 있었다.

같은 코드를 썼을 때 위의 화면처럼 달력이 보이지 않는다면,

input type="date"로 적고 달력 사용 시 input창 우측의 아이콘을 클릭하면 된다.

 

 

2. PHP 코드

    // 시작일이나 종료일이 비어있지 않을 때
    if ( ! empty($_REQUEST['start_date']) || ! empty($_REQUEST['end_date']) ) :
    
        $args = [
            'fields' => 'ids',	// 컬럼 중 id만 가져옴
            'post_status' => 'publish',
            'posts_per_page' => - 1,	// 갯수제한 없이 조회
            'date_query' => [	// post_date를 조회하는 조건
                [
                    'after'     => $_REQUEST['start_date'],
                    'before'    => $_REQUEST['end_date'],
                    'inclusive' => true             // 조건에 등호를 붙여줌
                ]
            ]
        ];
        
        $post_ids = get_posts($args);   // 검색된 post_id들을 array로 받음

 

'post_date'를 조건으로 검색하는 방법을 아무리 찾아도 나오지 않았는데, 작성법이 전혀 달라서였다.

그리고 특정일 단 하루가 아닌 기간을 검색하는 방법은 WP 공식 문서에서야 찾을 수 있었다.

where 조건식에 등호(=)를 붙이는 법도 마찬가지였다.

 

 

3. 결과 쿼리

SELECT cw_posts.ID
FROM cw_posts
WHERE 1=1
AND ( ( cw_posts.post_date >= '2022-05-03 00:00:00'
AND cw_posts.post_date <= '2022-05-03 23:59:59' ) )
AND ((cw_posts.post_status = 'publish'))
ORDER BY cw_posts.post_date DESC

 

php 소스를 수정하고, 포스트가 원하는대로 잘 검색된 것을 확인했다!

 

 

참고사이트

https://wordpress.stackexchange.com/questions/310394/how-to-get-posts-on-a-specific-date-wp-query

https://developer.wordpress.org/reference/classes/wp_query/

 

WordPress Developer Resources | Official WordPress Developer Resources

Official WordPress developer resources including a code reference, handbooks (for APIs, plugin and theme development, block editor), and more.

developer.wordpress.org

 

댓글