WordPress文章与页面互换

有些时候可能准备将一个或多个页面转换为文章,可以参考下面的方法。

将代码添加到当前主题函数模板functions.php中:

单个页面转换为文章

// 页面的ID
$page_id = 123;

// 设置页面为文章
$post = array(
    'ID' => $page_id,
    'post_type' => 'post',
    'post_status' => 'publish'
);

// 使用wp_update_post函数更新页面
$updated_post_id = wp_update_post( $post );

// 检查是否成功转换
if( !is_wp_error($updated_post_id) ) {
    echo "页面已转换为文章,新文章ID:" . $updated_post_id;
} else {
    echo "转换失败:" . $updated_post_id->get_error_message();
}

多个页面转换为文章

// 指定的页面ID列表
$page_ids_to_convert = array(123, 456, 789); // 替换为你想要转换的页面ID

// 遍历每个页面ID
foreach ($page_ids_to_convert as $page_id) {
    // 设置页面为文章
    $post = array(
        'ID' => $page_id,
        'post_type' => 'post',
        'post_status' => 'publish' // 或者你想要的其他状态
    );

    // 使用wp_update_post函数更新页面
    $updated_post_id = wp_update_post($post);

    // 检查是否成功转换
    if (!is_wp_error($updated_post_id)) {
        echo "页面ID " . $page_id . " 已成功转换为文章ID " . $updated_post_id . "<br>";
    } else {
        echo "页面ID " . $page_id . " 转换失败: " . $updated_post_id->get_error_message() . "<br>";
    }
}

所有页面批量转换为文章

// 获取所有页面的ID列表
$args = array(
    'post_type' => 'page',
    'posts_per_page' => -1, // 检索所有页面
    'post_status' => 'any' // 检索所有状态的页面
);

$pages = new WP_Query($args);

// 遍历每个页面并转换为文章
while ($pages->have_posts()) : $pages->the_post();
    $page_id = get_the_ID();

    // 设置页面为文章
    $post = array(
        'ID' => $page_id,
        'post_type' => 'post',
        'post_status' => 'publish' // 或者你想要的其他状态
    );

    // 使用wp_update_post函数更新页面
    $updated_post_id = wp_update_post($post);

    // 检查是否成功转换
    if (!is_wp_error($updated_post_id)) {
        echo "页面ID " . $page_id . " 已转换为文章ID " . $updated_post_id . "<br>";
    } else {
        echo "页面ID " . $page_id . " 转换失败: " . $updated_post_id->get_error_message() . "<br>";
    }

endwhile;

// 重置查询
wp_reset_query();

同理,将文章转换为页面

// 文章的ID
$post_id = 456;

// 设置文章为页面
$post = array(
    'ID' => $post_id,
    'post_type' => 'page',
    'post_status' => 'publish' // 或者你想要的其他状态
);

// 使用wp_update_post函数更新文章
$updated_post_id = wp_update_post($post);

// 检查是否成功转换
if (!is_wp_error($updated_post_id)) {
    echo "文章已转换为页面,新页面ID:" . $updated_post_id;
} else {
    echo "转换失败:" . $updated_post_id->get_error_message();
}

如果嫌使用代码麻烦,可以考虑使用WordPress文章类型转换插件:Post Type Switcher

WordPress文章与页面互换
WordPress本身不能直接将页面转换到正常的文章,除了复制内容重新发表外,别无它法,而通过Post Type Switc...
672

该插件不仅能将页面和文章相互转换,还能转换自定义文章类型。

本站文章大部分始于原创,用于个人学习记录,可能对您有所帮助,仅供参考!

weinxin
我的微信
版权声明
本站原创文章转载请注明文章出处及链接,谢谢合作!
 
知更鸟
评论  3  访客  3
    • 小笑
      小笑 1

      技术教程

      • 奇派空间
        奇派空间 1

        谢谢分享比较实用的教程。

        • 1920
          1920 1

          这个有用,拿来试试。

        匿名

        发表评论

        匿名网友
        :?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

        拖动滑块以完成验证