I am creating a WordPress theme and I have created an options panel with a setting for the sidebar location (none,left,right), but I have also added a setting to each page post (default,left,right,none) which overrides the general options.
To make this work on my index.php page I have the following code;
<?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(); ?>
The code works fine, however, I would have to copy this to several pages and page templates and I think that would be a lot of duplication, especially since some templates are much more complex. I think that the first block of text that is assigning the $SidebarPosition can be made a function in the function.php file. But I can’t understand how I can create a function that would display the main div block (the one that contains the classes page-style/feature) without repetition.
Any ideas?
You can use template files and call them whenever you need them. For example, you can have in a file just the render or specific PHP + HTML code that you need in one file, and the include it whenever you need. You would still need to call the function each time you want the output, but everything is contained in one single file. To achieve this, please follow this link:
https://developer.wordpress.org/reference/functions/get_template_part/