목표
wp_insert_post
, save_post
, deleted_post
등 워드프레스의 훅(hook) 을 이용해, 콘텐츠가 변경될 때마다 자동으로 sitemap.xml
을 파일로 자동 생성하도록 합니다.
1. sitemap.xml 자동 생성 PHP 함수 만들기
functions.php
또는 별도 플러그인에 아래 코드를 추가합니다:
php복사편집function generate_custom_sitemap() {
// 사이트맵 파일 경로
$sitemap_file = ABSPATH . 'sitemap.xml';
// 사이트 기본 URL
$site_url = get_site_url();
// 포스트 및 페이지 가져오기
$args = array(
'post_type' => array('post', 'page'),
'post_status' => 'publish',
'posts_per_page' => -1,
);
$query = new WP_Query($args);
// 사이트맵 시작
$sitemap = '<?xml version="1.0" encoding="UTF-8"?>' . PHP_EOL;
$sitemap .= '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' . PHP_EOL;
if ($query->have_posts()) {
while ($query->have_posts()) {
$query->the_post();
$url = get_permalink();
$lastmod = get_the_modified_time('Y-m-d\TH:i:sP');
$sitemap .= " <url>\n";
$sitemap .= " <loc>{$url}</loc>\n";
$sitemap .= " <lastmod>{$lastmod}</lastmod>\n";
$sitemap .= " <changefreq>weekly</changefreq>\n";
$sitemap .= " <priority>0.8</priority>\n";
$sitemap .= " </url>\n";
}
wp_reset_postdata();
}
$sitemap .= '</urlset>';
// 파일로 저장
file_put_contents($sitemap_file, $sitemap);
}
2. 워드프레스 Hook 에 연결하기
다음 훅들을 사용해 콘텐츠 변경 시 자동 실행되도록 합니다:
// 새 게시물 추가 또는 수정 시
add_action('save_post', 'generate_custom_sitemap');
// 게시물 삭제 시
add_action('deleted_post', 'generate_custom_sitemap');
이 훅들을 통해 워드프레스에서 게시물이 생성/수정/삭제될 때마다 sitemap.xml
이 자동으로 덮어써집니다.
3. 퍼미션 확인
file_put_contents()
가 ABSPATH . 'sitemap.xml'
위치에 쓸 수 있으려면 해당 디렉토리에 웹 서버 쓰기 권한이 있어야 합니다.
sudo chown www-data:www-data /var/www/html
sudo chmod 755 /var/www/html
위 예시는
/var/www/html
기준이며, 실제 워드프레스 설치 경로에 맞게 조정하세요.
4. Google Search Console 제출
https://mydomain.com/sitemap.xml
로 접근 가능한지 확인하고, Google Search Console에 이 URL을 제출하세요.
결과
- 워드프레스에서 글을 쓰거나 지울 때마다 sitemap.xml이 자동 갱신됩니다.
- 구글봇이 재방문 시 항상 최신 정보를 가져가게 됩니다.
- 별도 플러그인 없이도 완전히 자동화된 사이트맵 생성이 가능합니다.
Leave a Reply