I would like you to review on my sample WordPress theme index.php code.
<?php
/*
Template name: Homepage
*/
get_header();
?>
<?php
if(isset($_GET['action'])):
$action = $_GET['action'];
switch($action){
case "sendmail": include("sendmail.php"); break;
case "mailsent" : include("thanks.php"); break;
}
else:
?>
<!-------// Begin Content ---------->
<?php if (have_posts()): ?>
<?php while(have_posts()): the_post(); ?>
<tr>
<td class="contentarea">
<h1><?php the_title(); ?></h1>
<p> <?php the_content(); ?></p>
</td>
</tr>
<?php endwhile; ?>
<?php else: ?>
<tr>
<td class="contentarea">
<h1>Page not Found!</h1>
<p>Sorry, you are looking a page that is not here! </p>
<?php get_search_form(); ?>
</td>
</tr>
<?php endif; ?>
<!-------// End Content ---------->
<tr>
<!--begin contact form -->
<td class="contactarea" height="200">
<?php include("contact_area.php"); ?>
</td>
<!--end contact form -->
</tr>
<?php endif;?>
<?php get_footer(); ?
I want to turn my if statement above as a function something like but I don’t know how:
if(action_is_set()){
then_do_the_action();
}else {
//begin content..etc.
}
Is there a better structure of my code above??I’m still learning both PHP and WordPress.
Please , please help. Thanks!!.
I don’t feel it would be worth the effort to create a function action_is_set().
You would end up with:
Moving your switch to a function inside functions.php could be beneficial however.
That would look something similar to:
Or you can make this current page completely modular by moving the content section to a new include file:
I don’t know how this goes with the best practices for WordPress, but it is a good practice to have a default case in a switch especially in a scenario where it would do nothing if for instance they went to yourdomain.com/?action=blah
Rule of thumb: Never expect they will use it as intended; always assume that someone will try to break your code.