2016-03-21 45 views
1

我創建了一個WordPress主題,並創建了一個選項面板,其中包含側邊欄位置(無,左,右)的設置,但我也爲每個頁面文章添加了一個設置(默認,左,右,無),這會覆蓋一般選項。使用函數減少重複

爲了使這個工作在我的index.php頁面上,我有以下代碼;

<?php get_header(); ?> 

<?php  

// Sidebar position selected on the page/post 
$IndivSidebarPosition = get_field('sidebar'); 

// Default sidebar position for the site. 
$DefaultSidebarPosition = sprintf(get_theme_mod('graviton_sidebar_position')) ; 

if($IndivSidebarPosition == 'left' || $IndivSidebarPosition == 'right') { 

    $SidebarPosition = $IndivSidebarPosition; 

} else { 

    $SidebarPosition = $DefaultSidebarPosition; 
} 


?> 

    <div class="container"> 

     <div class="row"> 

      <?php if ($IndivSidebarPosition != 'none' and $DefaultSidebarPosition != 'none') { 

     echo '<div class="wrapper">'; 
      echo '<div class="col-xs-12 col-sm-3 col-md-3 sidebar '.$SidebarPosition.'-sidebar">'; 
        get_sidebar(); ?> 

       </div> 

       <div class="col-xs-12 col-sm-12 col-md-9 feature"> 

        <div class="col-xs-12 col-sm-12 col-md-12 page-style"> 

        <?php 

         if(have_posts()): 

          while(have_posts()): the_post(); ?> 

          <div class="col-xs-12 col-sm-12-col-md-12"> 

           <?php the_content(); ?> 

          </div> 

          <?php endwhile; 

         endif; 

        ?> 

        </div> 
       </div> 

      </div> 

      <?php } else { ?> 


      <div class="col-xs-12 col-sm-12 col-md-12 page-style"> 

      <?php 

       if(have_posts()): 

        while(have_posts()): the_post(); ?> 

        <div class="col-xs-12 col-sm-12-col-md-12"> 

         <?php the_content(); ?> 

        </div> 

        <?php endwhile; 

       endif; 

      ?> 

      </div> 

      <?php } ?> 

     </div> 

    </div> 

<?php get_footer(); ?> 

代碼工作正常,但是,我必須將它複製到多個頁面和頁面模板,我認爲這將是一個很大的重複,特別是一些模板要複雜得多。我認爲分配$ SidebarPosition的第一塊文本可以在function.php文件中生成一個函數。但我不明白如何創建一個可以不顯示重複的主div塊(包含類頁面樣式/特徵的塊)的函數。

任何想法?

+0

其實,這是一個完美的用例的**子模板**。請參閱[get_template_part](https://developer.wordpress.org/reference/functions/get_template_part/)文檔,也許這篇文章:https://kovshenin.com/2013/get_template_part/ –

+0

@cale_b我已經考慮了get_template,但我看不到這會如何工作。 – Naz

回答

0

您可以使用模板文件並在需要時調用它們。例如,您可以在一個文件中包含您需要的渲染或特定的PHP + HTML代碼,並在需要時包含它。您每次需要輸出時都需要調用該函數,但所有內容都包含在一個文件中。要做到這一點,請點擊此鏈接:

https://developer.wordpress.org/reference/functions/get_template_part/

+0

我已經考慮過get_template,但是我看不出如何工作。我是「得到」的是什麼? – Naz