Php wordpress:更改页面模板

Php wordpress:更改页面模板,php,mysql,wordpress,Php,Mysql,Wordpress,通常要在wordpress中更改页面模板,我只需要登录CMS,在编辑特定页面时从下拉菜单中选择页面模板 我的问题是我有大约100页,手动一页一页地更改页面会很麻烦。有没有一种方法可以直接访问数据库并执行一些mysql查询,将所有页面模板改为“新闻模板”而不是“公告模板” 我制作了一个名为news.php的模板,并在其中添加了 <?php /* Template Name: News Template */ ?> 如果您需要将所有页面更改为另一个模板,您还可以通过将其

通常要在wordpress中更改页面模板,我只需要登录CMS,在编辑特定页面时从下拉菜单中选择页面模板

我的问题是我有大约100页,手动一页一页地更改页面会很麻烦。有没有一种方法可以直接访问数据库并执行一些mysql查询,将所有页面模板改为“新闻模板”而不是“公告模板”

我制作了一个名为news.php的模板,并在其中添加了

<?php
  /*
    Template Name: News Template
  */
?>

如果您需要将所有页面更改为另一个模板,您还可以通过将其添加到functions.php,让Wordpress完成这项工作

function temp_func_templates(){

    foreach( get_posts('post_type=page') as $page ) {
        $current_template = get_post_meta( $page->ID, '_wp_page_template', true );
        $new_template = 'news.php';

        if( $current_template != $new_template )
            update_post_meta( $page->ID, '_wp_page_template', $new_template );
    }

}
add_action( 'admin_init', 'temp_func_templates' );
然后在确认代码正常工作后删除该代码。
这将检查每个页面的当前模板数据——如果不是“news.php”,它将更改它

请注意,这将挂钩到管理面板-以避免访问者在每次页面加载时运行这些查询。

只要到WP管理员那里一次-确认它完成了-删除代码。

阅读Wordpress Codex后,我想到了以下内容(我基本上对Frederick的答案进行了修改,因为它对我不起作用)


我有一个新闻页面,其中显示了5条最新新闻,它是我创建的所有新闻页面的父级


所以,我基本上把新闻的所有子页面都改成了一个新的模板。

@Frederick,谢谢你的帮助。假设我有其他应用于其他页面的模板。这不会覆盖他们分配的模板吗?我想我会修改if语句所在的代码,这样它就不会覆盖它了?我希望这样行。您可以添加一些if,以排除不需要设置的所有内容!出于某种原因,它对我不起作用,但我在阅读了WP法典后才明白了这一点。这是一个很小的问题。再次谢谢你,不客气。如果答案对你有用,请也接受。
<?php
  function temp_func_templates(){
    //Note: 26 is the page_id of News page
    $args = array('child_of' => 26, 'depth' => 1);
    $children = get_pages($args);
    foreach( $children as $page ) {
      $current_template = get_post_meta( $page->ID, '_wp_page_template', true );
      $new_template = 'news.php';


      if( $current_template != $new_template  && ($page->post_parent == '26')){
        update_post_meta( $page->ID, '_wp_page_template', $new_template );
      }
    }

  }
  add_action( 'admin_init', 'temp_func_templates' );

?>