所以我仍然掌握着WordPress自定义帖子类型以及如何将它们集成到现有模板中,但我有一个简单的问题,即我提出的代码是否可以简化?
我需要从一个特定模板调用多个页面,并且我添加了条件语句来调用每个页面及其相应的自定义帖子类型代码,但我基本上重复了每个条件语句的大部分代码,所以我想知道是否有办法简化这段代码:
<div class="row">
<?php if (is_page(165)) {
$args = array(
'post_type' => 'restaurant',
'paged'=>$paged,
'orderby'=>'title',
'order'=>'ASC',
'tax_query' => array(
array(
'taxonomy' => 'restaurant_category',
'field' => 'slug',
'terms' => 'sooke'
)
)
);
$restaurants = new WP_Query( $args );
if( $restaurants->have_posts() ) {
while( $restaurants->have_posts() ) {
$restaurants->the_post();
?>
<div class="col-sm-4 col-md-4">
<h1><?php the_title() ?></h1>
<?php the_content() ?>
</div>
<?php
}
}
else {
echo 'No Restaurants';
}
} ?>
</div>
<div class="row">
<?php if (is_page(12)) {
$args = array(
'post_type' => 'restaurant',
'paged'=>$paged,
'orderby'=>'title',
'order'=>'ASC',
'tax_query' => array(
array(
'taxonomy' => 'restaurant_category',
'field' => 'slug',
'terms' => 'chilliwack'
)
)
);
$restaurants = new WP_Query( $args );
if( $restaurants->have_posts() ) {
while( $restaurants->have_posts() ) {
$restaurants->the_post();
?>
<div class="col-sm-4 col-md-4">
<h1><?php the_title() ?></h1>
<?php the_content() ?>
</div>
<?php
}
}
else {
echo 'No Restaurants';
}
} ?>
</div>
如果有一种简化此代码的方法,以便我不会一次又一次地重复代码,我真的很感谢帮助这样做,这样我就可以学习如何以及如何不使用自定义帖子创建条件语句将来键入代码。提前谢谢!
对于Dk-Macadamia(导致白屏的更新代码)
<?php $terms=array('165'=>'sooke','12'=>'chilliwack');
//now check it
if(has_term($terms))
{ ?>
<div class="row">
<?php
foreach($terms as $key=>$val)
{
if(is_page($key)) {
$args = array(
'post_type' => 'restaurant',
'paged'=>$paged,
'orderby'=>'title',
'order'=>'ASC',
'tax_query' => array(
array(
'taxonomy' => 'restaurant_category',
'field' => 'slug',
'terms' => $val
)
)
); ?>
</div>
答案 0 :(得分:0)
我认为您正在寻找has_terms(),您可以在代码中尝试: 因为你正在研究自定义模板,所以你可以设置一个像这样的手动数组。
$terms=array('165'=>'sooke','12'=>'chilliwack');
//now check it
if(has_term($terms))
{ ?>
<div class="row">
<?php
foreach($terms as $key=>$val)
{
if(is_page($key)) {
$args = array(
'post_type' => 'restaurant',
'paged'=>$paged,
'orderby'=>'title',
'order'=>'ASC',
'tax_query' => array(
array(
'taxonomy' => 'restaurant_category',
'field' => 'slug',
'terms' => $val
)
)
);
答案 1 :(得分:0)
使用switch语句
switch ($slug_name)
case 1 : 'chilliwack'
my_func('chilliwack');
break;
and so on ....
// here is function
<?php
function my_func($slug) {
$args = array(
'post_type' => 'restaurant',
'paged'=>$paged,
'orderby'=>'title',
'order'=>'ASC',
'tax_query' => array(
array(
'taxonomy' => 'restaurant_category',
'field' => 'slug',
'terms' => "$slug"
)
)
);
$restaurants = new WP_Query( $args );
if( $restaurants->have_posts() ) {
while( $restaurants->have_posts() ) {
$restaurants->the_post();
?>
<div class="col-sm-4 col-md-4">
<h1><?php the_title() ?></h1>
<?php the_content() ?>
</div>
<?php
}
}
else {
echo 'No Restaurants';
}
}
?>
</div>