代码之家  ›  专栏  ›  技术社区  ›  Quentin

在Wordpress搜索循环中获取帖子类型

  •  2
  • Quentin  · 技术社区  · 7 年前

    我在我的系统中使用了一个循环 search.php 文件循环浏览结果并显示其标题。

    这非常有效,但我想检查每个结果,无论是一个页面还是一篇文章。下面的代码似乎不起作用。

    if ( have_posts() ) : ?>
    
        <h1 class="page-title"><?php printf( __( 'Results for: %s', 'domain' ), '<span>' . get_search_query() . '</span>' ); ?></h1>
    
        <?php while ( have_posts() ) : the_post();
    
            $title = get_the_title();
    
            echo '<article class="post-card">';
    
                if ( is_page() ) {
                    echo 'page';
                } else if ( is_singular('post') ) {
                    echo 'post';
                }
    
                echo '<h2>' .$title. '</h2>';
            echo '</article>';
    
        endwhile; ?>
    
    <?php endif;
    
    2 回复  |  直到 7 年前
        1
  •  0
  •   revengeance    7 年前

    我想你正在寻找这个函数。会更短。只需传递post对象,它将返回包含post类型的字符串。

    获取帖子类型(int | WP | post | null$post=null)

     $somePost; // post
     $postType = get_post_type($somePost);
    
     if ('page' === $postType) { 
        // page...
     }
     elseif ('post' === $postType { 
        // post...
     }
    
        2
  •  0
  •   WhereDidMyBrainGo    7 年前

    这将在循环中获取post类型。

    if ( 'page' == get_post_type( get_the_ID() )

    最美好的祝福,

    米切尔