让 WordPress 子页面自动使用父页面的模板

文 / @WordPress主题

About using WordPress as a CMS and templates

When we use WordPress as a CMS to publish content, we often set templates for pages to adapt to different content. If it is content belonging to a certain category, the category template is often the same. By default, we need to set a template for each page of this category. This can be very cumbersome if there are many sub-pages under a category and you need to click the mouse many times. Is there a way to set the template for the parent page and automatically apply it to the sub-pages?

Of course, there is a solution. By using a function to determine whether a page has a parent page, we can set the parent page's template as the template for this page.

Set the parent page's template as the sub-page's template

function wizhi_use_parent_template(){
    global $post;
    $curr_tmp = get_post_meta($post->ID, '_wp_page_template', true);
    // Get the page template
    if($post->post_parent){
        $parent_tmp = get_post_meta($post->post_parent, '_wp_page_template', true);
        // If there is a parent page, get its template
        update_post_meta($post->ID,'_wp_page_template',$parent_tmp,$curr_tmp);
        // Set the sub-page's template as the parent page's template
    }
}
add_action('save_post', 'wizhi_use_parent_template');

Possible issues of this method

This method is much simpler, but if I need to set a template for a sub-page separately, there will be a problem. No matter how I set it, as soon as I save the article, the sub-page template will be automatically set as the parent page's template.

Is there a way to solve this problem? Of course, there is. We need to first check whether the sub-page has set a template. If it has, use the current template; if it hasn't, automatically use the parent page's template. The specific code is left for savvy netizens to handle.

添加UTHEME为好友
扫码添加UTHEME微信为好友
· 分享WordPress相关技术文章,主题上新与优惠动态早知道。
· 微信端最大WordPress社群,限时免费入群。