以下是多种通过代码获取 WordPress 所有文章链接的方法:
1. 基础方法:使用 WP_Query
方法 1.1:获取所有文章的永久链接
<?php
// 获取所有已发布的文章链接
$args = array(
'post_type' => 'post', // 文章类型
'post_status' => 'publish', // 只获取已发布的
'posts_per_page' => -1, // 获取所有文章,无限制
'fields' => 'ids', // 只获取ID,提高性能
);
$query = new WP_Query($args);
$post_links = array();
if ($query->have_posts()) {
while ($query->have_posts()) {
$query->the_post();
$post_links[] = array(
'title' => get_the_title(),
'url' => get_permalink(),
'id' => get_the_ID(),
);
}
wp_reset_postdata();
}
// 输出链接
echo '<ul>';
foreach ($post_links as $link) {
echo '<li><a href="' . esc_url($link['url']) . '">' . esc_html($link['title']) . '</a></li>';
}
echo '</ul>';
?>
方法 1.2:分页获取大量文章
<?php
// 处理大量文章时的分页方法
$posts_per_page = 100; // 每次获取100篇
$paged = 1;
$all_links = array();
do {
$args = array(
'post_type' => 'post',
'post_status' => 'publish',
'posts_per_page' => $posts_per_page,
'paged' => $paged,
'fields' => 'ids',
);
$query = new WP_Query($args);
if ($query->have_posts()) {
foreach ($query->posts as $post_id) {
$all_links[] = array(
'id' => $post_id,
'title' => get_the_title($post_id),
'url' => get_permalink($post_id),
);
}
}
$paged++;
} while ($query->max_num_pages >= $paged);
// 统计总数
echo '总共获取了 ' . count($all_links) . ' 篇文章链接';
?>
2. 高性能方法:使用数据库直接查询
方法 2.1:直接 SQL 查询
<?php
global $wpdb;
$query = "
SELECT ID, post_title, post_name
FROM {$wpdb->posts}
WHERE post_type = 'post'
AND post_status = 'publish'
ORDER BY post_date DESC
";
$posts = $wpdb->get_results($query);
$links = array();
foreach ($posts as $post) {
$permalink = get_permalink($post->ID);
$links[] = array(
'id' => $post->ID,
'title' => $post->post_title,
'url' => $permalink,
'slug' => $post->post_name,
);
}
// 输出为纯文本链接
foreach ($links as $link) {
echo esc_url($link['url']) . "\n";
}
?>
方法 2.2:包含自定义文章类型
<?php
global $wpdb;
// 获取特定文章类型
$post_types = array('post', 'page', 'product'); // 添加需要的文章类型
$placeholders = array_fill(0, count($post_types), '%s');
$placeholders = implode(',', $placeholders);
$query = $wpdb->prepare("
SELECT ID, post_title, post_name, post_type
FROM {$wpdb->posts}
WHERE post_type IN ($placeholders)
AND post_status = 'publish'
ORDER BY post_type, post_date DESC
", $post_types);
$results = $wpdb->get_results($query);
$links_by_type = array();
foreach ($results as $item) {
if (!isset($links_by_type[$item->post_type])) {
$links_by_type[$item->post_type] = array();
}
$links_by_type[$item->post_type][] = array(
'title' => $item->post_title,
'url' => get_permalink($item->ID),
);
}
// 按文章类型输出
foreach ($links_by_type as $type => $type_links) {
echo "<h3>文章类型: {$type} (共" . count($type_links) . "篇)</h3>";
echo '<ul>';
foreach ($type_links as $link) {
echo '<li><a href="' . esc_url($link['url']) . '">' . esc_html($link['title']) . '</a></li>';
}
echo '</ul>';
}
?>
3. 高级功能:生成站点地图样式链接
方法 3.1:生成 XML 站点地图格式
<?php
function generate_post_links_xml() {
$args = array(
'post_type' => array('post', 'page'),
'post_status' => 'publish',
'posts_per_page' => -1,
'fields' => 'ids',
);
$query = new WP_Query($args);
$xml_content = '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
$xml_content .= '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' . "\n";
if ($query->have_posts()) {
foreach ($query->posts as $post_id) {
$post_url = get_permalink($post_id);
$post_modified = get_the_modified_date('c', $post_id);
$post_type = get_post_type($post_id);
// 设置优先级
$priority = ($post_type == 'page') ? '0.8' : '0.6';
$xml_content .= ' <url>' . "\n";
$xml_content .= ' <loc>' . esc_url($post_url) . '</loc>' . "\n";
$xml_content .= ' <lastmod>' . $post_modified . '</lastmod>' . "\n";
$xml_content .= ' <priority>' . $priority . '</priority>' . "\n";
$xml_content .= ' </url>' . "\n";
}
}
wp_reset_postdata();
$xml_content .= '</urlset>';
return $xml_content;
}
// 保存为文件
$xml = generate_post_links_xml();
file_put_contents(ABSPATH . 'custom-sitemap.xml', $xml);
echo '站点地图已生成: ' . site_url('/custom-sitemap.xml');
?>
方法 3.2:生成 JSON 格式
<?php
function get_all_post_links_json() {
$args = array(
'post_type' => 'any', // 所有文章类型
'post_status' => 'publish',
'posts_per_page' => -1,
'fields' => 'ids',
);
$query = new WP_Query($args);
$data = array(
'site_url' => get_site_url(),
'total' => $query->found_posts,
'generated' => current_time('c'),
'posts' => array(),
);
if ($query->have_posts()) {
foreach ($query->posts as $post_id) {
$data['posts'][] = array(
'id' => $post_id,
'title' => html_entity_decode(get_the_title($post_id)),
'url' => get_permalink($post_id),
'type' => get_post_type($post_id),
'date' => get_the_date('c', $post_id),
'modified' => get_the_modified_date('c', $post_id),
'author' => get_the_author_meta('display_name', get_post_field('post_author', $post_id)),
);
}
}
wp_reset_postdata();
return json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
}
// 输出 JSON
header('Content-Type: application/json');
echo get_all_post_links_json();
?>
4. 实用函数封装
方法 4.1:可重用的函数
<?php
/**
* 获取所有文章链接
*
* @param array $args 查询参数
* @param string $format 输出格式 (array, html, text, xml, json)
* @return mixed
*/
function get_all_post_links($args = array(), $format = 'array') {
$defaults = array(
'post_type' => 'post',
'post_status' => 'publish',
'posts_per_page' => -1,
'orderby' => 'date',
'order' => 'DESC',
);
$args = wp_parse_args($args, $defaults);
$query = new WP_Query($args);
$links = array();
if ($query->have_posts()) {
foreach ($query->posts as $post) {
$links[] = array(
'id' => $post->ID,
'title' => get_the_title($post),
'url' => get_permalink($post),
'date' => get_the_date('', $post),
'type' => get_post_type($post),
);
}
}
wp_reset_postdata();
// 根据格式返回
switch ($format) {
case 'html':
$output = '<ul>';
foreach ($links as $link) {
$output .= '<li><a href="' . esc_url($link['url']) . '">' . esc_html($link['title']) . '</a> (' . $link['date'] . ')</li>';
}
$output .= '</ul>';
return $output;
case 'text':
$output = '';
foreach ($links as $link) {
$output .= $link['url'] . "\n";
}
return $output;
case 'xml':
$output = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . '<links>' . "\n";
foreach ($links as $link) {
$output .= ' <link>' . "\n";
$output .= ' <url>' . esc_url($link['url']) . '</url>' . "\n";
$output .= ' <title>' . esc_html($link['title']) . '</title>' . "\n";
$output .= ' </link>' . "\n";
}
$output .= '</links>';
return $output;
case 'json':
return json_encode($links, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
case 'array':
default:
return $links;
}
}
// 使用示例
$all_links = get_all_post_links(array('post_type' => array('post', 'page')), 'html');
echo $all_links;
?>
方法 4.2:短代码版本
<?php
// 添加到 functions.php
add_shortcode('all_post_links', 'all_post_links_shortcode');
function all_post_links_shortcode($atts) {
$atts = shortcode_atts(array(
'type' => 'post',
'limit' => -1,
'format' => 'list', // list, comma, line
), $atts);
$args = array(
'post_type' => $atts['type'],
'post_status' => 'publish',
'posts_per_page' => $atts['limit'],
);
$query = new WP_Query($args);
$output = '';
if ($query->have_posts()) {
$links = array();
while ($query->have_posts()) {
$query->the_post();
$links[] = '<a href="' . get_permalink() . '">' . get_the_title() . '</a>';
}
wp_reset_postdata();
switch ($atts['format']) {
case 'comma':
$output = implode(', ', $links);
break;
case 'line':
$output = implode('<br>', $links);
break;
case 'list':
default:
$output = '<ul><li>' . implode('</li><li>', $links) . '</li></ul>';
}
} else {
$output = '没有找到文章';
}
return $output;
}
// 在文章或页面中使用
// [all_post_links]
// [all_post_links type="page"]
// [all_post_links type="post" limit="10" format="comma"]
?>
5. 优化与注意事项
性能优化建议
<?php
// 1. 使用缓存
function get_all_links_cached() {
$cache_key = 'all_post_links_cache';
$cached = get_transient($cache_key);
if ($cached !== false) {
return $cached;
}
$links = get_all_post_links(); // 使用前面的函数
// 缓存12小时
set_transient($cache_key, $links, 12 * HOUR_IN_SECONDS);
return $links;
}
// 2. 清理缓存
add_action('save_post', 'clear_links_cache');
function clear_links_cache() {
delete_transient('all_post_links_cache');
}
// 3. 限制查询字段,提高性能
function get_all_links_efficient() {
global $wpdb;
$query = "
SELECT ID, post_title
FROM {$wpdb->posts}
WHERE post_type = 'post'
AND post_status = 'publish'
ORDER BY post_date DESC
LIMIT 1000
";
return $wpdb->get_results($query);
}
?>
错误处理
<?php
function get_all_links_safely() {
try {
$args = array(
'post_type' => 'post',
'post_status' => 'publish',
'posts_per_page' => -1,
'no_found_rows' => true, // 提高性能
);
$query = new WP_Query($args);
if (!$query->have_posts()) {
return array('error' => '没有找到文章', 'count' => 0);
}
$links = array();
foreach ($query->posts as $post) {
$permalink = get_permalink($post);
if ($permalink && !is_wp_error($permalink)) {
$links[] = array(
'title' => get_the_title($post),
'url' => $permalink,
);
}
}
wp_reset_postdata();
return array(
'success' => true,
'count' => count($links),
'links' => $links,
);
} catch (Exception $e) {
return array(
'error' => true,
'message' => '获取链接时出错: ' . $e->getMessage(),
);
}
}
?>
6. 使用方法总结
在主题文件中使用
<?php
// 在主题的任意模板文件中
$links = get_all_post_links(); // 使用上面的函数
foreach ($links as $link) {
echo '<a href="' . $link['url'] . '">' . $link['title'] . '</a><br>';
}
?>
创建独立页面
- 在主题目录创建
template-all-links.php:
<?php
/* Template Name: 所有文章链接页面 */
get_header();
?>
<div class="container">
<h1>网站所有文章链接</h1>
<?php echo get_all_post_links(array(), 'html'); ?>
</div>
<?php get_footer(); ?>
- 在后台创建页面,选择此模板
命令行使用(WP-CLI)
如果服务器支持 WP-CLI:
# 导出所有文章链接到文件
wp db query "SELECT CONCAT('"$(wp option get siteurl)"', p.post_name, '/') as url FROM wp_posts p WHERE p.post_type = 'post' AND p.post_status = 'publish'" --skip-column-names > links.txt
注意事项:
- 性能考虑:文章数量过多时,避免在页面加载时实时查询
- 缓存策略:对结果进行缓存,特别是对于大型网站
- 内存限制:大量文章时可能需要增加 PHP 内存限制
- 分页处理:超过 1000 篇文章建议使用分页查询
- 安全考虑:确保输出时使用
esc_url()和esc_html()进行转义
选择哪种方法取决于你的具体需求、文章数量和性能要求。对于大多数网站,使用 WP_Query的方法是最安全、最兼容的选择。


湘公网安备43020002000238