我想让你审查我的示例Wordpress主题index.php代码。
<?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(); ?我想把上面的if语句变成一个函数,就像这样,但我不知道怎么做:
if(action_is_set()){
then_do_the_action();
}else {
//begin content..etc.
}上面的代码有没有更好的结构?我还在学习PHP和Wordpress。求求你,求你帮帮我。谢谢!!。
发布于 2011-08-23 16:03:09
我不认为创建一个函数action_is_set()是值得的。
你最终会得到:
function action_is_set() {
return isset($_GET['action']);
}但是,将您的开关移至functions.php中的函数可能是有益的。
它看起来类似于:
function do_action() {
switch($_GET['action']) {
case 'sendmail':
include('sendmail.php');
break;
}
}或者,您可以通过将内容部分移动到新的包含文件中,使当前页面完全模块化:
<?php
get_header();
switch($_GET['action']) {
case 'sendmail':
include('sendmail.php');
break;
case 'mailsent':
include('thanks.php');
break;
default:
include('content.php');
}
get_footer();
?>我不知道这与WordPress的最佳实践有什么不同,但在切换中设置默认用例是一个很好的实践,特别是在这样的场景中,例如,如果它们转到yourdomain.com/?action=blah,它将什么也不做。
经验法则:永远不要指望他们会按预期使用它;总是假设有人会试图破坏你的代码。
发布于 2011-08-23 13:53:39
您可以在主题下用functions.php编写函数。
https://stackoverflow.com/questions/7156274
复制相似问题