【问题标题】:Call different sidebar in one page template with if statement wordpress使用 if 语句 wordpress 在一个页面模板中调用不同的侧边栏
【发布时间】:2015-12-30 05:45:31
【问题描述】:

我有 1 个单独的帖子页面模板,它将显示 2 个不同的分类术语,我喜欢为这 2 个不同的术语调用 2 个不同的侧边栏。这个帖子模板是“single-recipe.php”,我称之为“content-single_recipe.php”。在“content-single_recipe.php”中,我根据条件语句的不同条款调用了 2 个不同的侧边栏:

SINGLE-RECIPE.PHP

    while ( have_posts() ) : the_post(); 
        get_template_part( 'content', 'single_recipe' ); 
    endwhile; // end of the loop. 

CONTENT-SINGLE_RECIPE.PHP

    php the_content();       

    // Here are code for sidebars:
        $term = get_the_term_list($post->ID, 'recipe_type'); 

        if ( $term = 'salad' ){
            dynamic_sidebar('sidebar-salad');
        }elseif($term = 'sandwich'){            
            dynamic_sidebar('sidebar-sandwich' );
        }

但是,无论 $term 是什么,它总是称为“sidebar-salad”。

【问题讨论】:

    标签: php wordpress


    【解决方案1】:

    get_the_term_list 为您提供 HTML 术语列表。请改用has_term。比较是用==,而不是=。由于您使用=,即为变量赋值,因此您首先使用的if 将始终为真。

    if( has_term( 'salad', 'recipe_type', $post->ID ) ){
        dynamic_sidebar('sidebar-salad');
    }
    elseif( has_term( 'sandwich', 'recipe_type', $post->ID ) ){
        dynamic_sidebar('sidebar-sandwich');
    }
    

    【讨论】:

    • 我试过了,还是不行。如果我使用get_term(),当我尝试回显 $term 时,没有结果。但如果我使用get_the_term_list(),我可以回显结果。我也把=改成==,在if语句中,没有结果。
    • 是的。我为此使用了错误的功能。对不起。修复了我的代码,请重试。
    • 是的,它现在运行良好。顺便说一句,请问$post->ID 到底是什么意思?谢谢。
    • 它只是给出当前的帖子 ID。
    【解决方案2】:
     // Sidebars
     if(is_front_page())
        $op_sidebar_id = __('Sidebar Home','options');
    // Single page and post type sidebars
    elseif(is_attachment())
        $op_sidebar_id = __('Sidebar Attachment','options');
    elseif(is_single())
        $op_sidebar_id = __('Sidebar Single','options');
    elseif(is_page())
        $op_sidebar_id = __('Sidebar Page','options');
    else
        $op_sidebar_id = __('Sidebar Home','options');
    

    之后,我添加了带有变量集的普通小部件部分:

    // 如果使用无侧边栏模板 if(is_page_template('no-sidebar.php')) : 回声''; // 否则,显示侧边栏 别的 : 回声“”;

        if(function_exists('dynamic_sidebar') &&   
      dynamic_sidebar($op_sidebar_id)) :
        else :
        // Default to Home page sidebar if no widgets are set
            if(function_exists('dynamic_sidebar') && dynamic_sidebar(__('Sidebar
       Home','options'))) :
            else : _e('Add content to your sidebar through the widget control  
       panel.','options');
            endif;
        endif;
        echo '</div>';
      endif;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多