【问题标题】:Add a class to the body - PHP Wordpress在正文中添加一个类 - PHP Wordpress
【发布时间】:2017-12-05 07:50:48
【问题描述】:

我正在尝试在 WordPress 主题的正文中添加一个类,这样当页面上没有帖子时,它就不会显示搜索栏。我现在在我的functions.php 中查找某个页面,如果没有帖子。

<?php
add_filter( 'body_class', 'custom_class' );
function custom_class( $classes ) {
    if(strpos($_SERVER['REQUEST_URI'], 'agent') !== false ){
        $classes[] = 'noSearchBar';
    }
    if(!have_posts() ){
      $classes[] = 'noSearchBar';
    }
    return $classes;
}
?>

这适用于大多数页面,但在某些页面上它使用不同的模板,因此而不是像这样使用have_posts 调用帖子:

<?php
   global $wp_query;

   if ( have_posts() ) :
       while ( have_posts() ) : the_post();

           get_template_part('template-parts/property-for-listing');

       endwhile;
       wp_reset_postdata();
   else:
       ?>
<h4><?php esc_html_e('Sorry No Results Found', 'houzez') ?></h4>
<?php
   endif;
   ?>

它是这样提出来的:

<?php
   global $wp_query, $paged;
   if(!$fave_prop_no){
       $posts_per_page  = 9;
   } else {
       $posts_per_page = $fave_prop_no;
   }
   $latest_listing_args = array(
       'post_type' => 'property',
       'posts_per_page' => $posts_per_page,
       'paged' => $paged,
       'post_status' => 'publish'
   );

   $latest_listing_args = apply_filters( 'houzez_property_filter', $latest_listing_args );

   $latest_listing_args = houzez_prop_sort ( $latest_listing_args );
   $wp_query = new WP_Query( $latest_listing_args );

   if ( $wp_query->have_posts() ) :
       while ( $wp_query->have_posts() ) : $wp_query->the_post();

           get_template_part('template-parts/property-for-listing');

       endwhile;
   else:
       get_template_part('template-parts/property', 'none');
   endif;
   ?>

这使我的功能不起作用。 template-parts/property-none 中只有 1 行代码,它只是说与其他文件相同的内容。所以我不确定为什么其他模板不会添加 body 类。

【问题讨论】:

  • 因为在 WordPress 中每个页面也存储为一个帖子,所以如果你会检查 have_post。我认为它不会起作用。

标签: php wordpress function class


【解决方案1】:

你可以像这个例子一样,

<?php
add_filter( 'body_class', 'custom_class' );
function custom_class( $classes ) {
  if ( is_single('post') ) {
     $classes[] = 'SearchBar';
  }else{
     $classes[] = 'noSearchBar';
  }
  return $classes;
}
?>

以下示例适用于单个帖子页面。更多条件。visit

希望对你有帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-08-02
    • 1970-01-01
    • 2015-11-17
    • 2016-05-16
    • 2014-07-21
    • 1970-01-01
    • 1970-01-01
    • 2012-09-23
    相关资源
    最近更新 更多