向函数添加If Else

时间:2016-10-26 作者:Dan Bruce

这是我的代码,但我只想在当前类别有子类时回显代码。

<?php
$terms = get_terms([
    \'taxonomy\' => get_queried_object()->taxonomy,
    \'parent\' => get_queried_object_id(),
]);
echo \'<div style="height: 200px; text-transform: uppercase; border:1px solid #666666; padding:10px; overflow-y: scroll;">
<div class="breaker-small">Refine Search</div>\';
foreach ($terms as $term) {
    echo \'<p class="filters"><a href="\' . get_term_link($term) . \'">\' . $term->name . \'</a></p>\';
}
echo \'</div>
<br />\';
?>
所以,如果

$terms = get_terms([
    \'taxonomy\' => get_queried_object()->taxonomy,
    \'parent\'   => get_queried_object_id(),
]));
True-然后运行echo。

2 个回复
最合适的回答,由SO网友:CodeMascot 整理而成

您可以像下面这样编写此代码-

<?php
$element = get_queried_object_id();
if (!empty($element)) {
    $terms = get_terms([
        \'taxonomy\' => $element->taxonomy,
        \'parent\' => $element,
    ]);
    echo \'<div style="height: 200px; text-transform: uppercase; border:1px solid #666666; padding:10px; overflow-y: scroll;">
    <div class="breaker-small">Refine Search</div>\';
    foreach ($terms as $term) {
        echo \'<p class="filters"><a href="\' . get_term_link($term) . \'">\' . $term->name . \'</a></p>\';
    }
    echo \'</div><br />\';
} else {
    // Do something
} 
?>

SO网友:mukto90

使用count() 计算中的条目数$terms. 这是代码-

<?php 
    $terms = get_terms([
        \'taxonomy\' => get_queried_object()->taxonomy,
        \'parent\'   => get_queried_object_id(),
        ]);
    echo \'<div style="height: 200px; text-transform: uppercase; border:1px solid #666666; padding:10px; overflow-y: scroll;">
    <div class="breaker-small">Refine Search</div>\';

    if( count( $terms ) ) :

    foreach ( $terms as $term) {
        echo \'<p class="filters"><a href="\' . get_term_link( $term ) . \'">\' . $term->name . \'</a></p>\';  
    }

    endif;

    echo \'</div>
    <br />\';
?>
[未测试]

相关推荐

如何在Functions.php中链接style.css

我是WordPress的新手;我刚开始学习WordPress。我想把风格联系起来。函数中的css。php,但我无法解决这里可能存在的问题。谁能给我指出正确的方向吗?指数php<?php get_header(); ?> <?php if ( have_posts() ) { while ( have_posts() ) { the_post();