首页 > 解决方案 > 如何通过更改“首页”设置来强制主页重定向并禁用 Wordpress 网站上的主标题?

问题描述

我想要一个名为“placeholder-home”的空白页面,带有 slug“/placeholder-home”,当设置为首页时(在 WP 阅读设置中),将标题更改为基本内容并强制子页面重定向到主页.

标签: phpwordpresswordpress-theming

解决方案


为此,我使用 slug“placeholder-home”创建了一个空白页面。下面的方法在 header.php 和 functions.php 文件中将首页的 ID 与“placeholder-home”的 ID 进行比较。如果匹配,则进行更改。

在 header.php 中,启用菜单更改:

<header>
       <?php
    //Gets the placeholder page's pagename
    $placeholderpage_slug = get_page_by_path( 'placeholder-home' );
    //then gets the ID from the placeholder's pagename
    $placeholderpage_id = $placeholderpage_slug->ID;
    
    //Gets the ID of the current front page
    $frontpage_id = get_option('page_on_front');
    
    if ( $frontpage_id == $placeholderpage_id ): ?>
            <!-- Nav for site under development -->
      <nav class="dev_site_nav">
    
         <div>
    <h3>Website under development</h3><p>Please check back later</p>
    </div>
    
    </nav>
    
      <?php else: ?>
           <!-- Nav for normal site -->
      <nav class="main_site_nav">
<!-- the content of your main navigation -->
    </nav>
            <?php endif; ?>
    </header>

在functions.php中,强制重定向到主页:

//Redirects when 'placeholder-home' is set as front page
add_action( 'template_redirect', 'redirect_to_homepage' );

function redirect_to_homepage() {
        $placeholderp_slug = get_page_by_path( 'placeholder-home' );
    $placeholderp_id = $placeholderp_slug->ID;
    $homep_id = get_option('page_on_front');
    
    if ( ! is_page( $homep_id ) && $homep_id == $placeholderp_id ) {                                                                                
         wp_redirect( home_url( 'index.php?page_id=' . $placeholderp_id ) ); 
    }
    exit();
}

可能有一个更优雅的解决方案,所以我欢迎评论。


推荐阅读