自定义帖子查询WordPress和显示帖子的更好方法


Custom Post Query WordPress and a better way to display posts

这似乎有点菜鸟,但我没有找到更好的选择。我创建了一个自定义循环,以仅显示我创建的自定义帖子类型的标题。

例:

自定义帖子类型:Atuação

  • Contratos (Cível e Societário)
  • 迪雷托刑罚

问题是:我无法在菜单上"验证"帖子是否处于活动状态或仅链接。示例:我的访问者正在访问Direito刑事官员页面。但是菜单不显示任何类,所以我可以自定义它。它只是显示<a href> link.

请参阅下面的自定义循环代码。

<ul class="menu-advogados">
    <?php
        // WP_Query arguments
        $args = array (
            'post_type'              => 'atuacao_posts',
            'pagination'             => false,
            'order'                  => 'ASC',
            'orderby'                => 'title',
        );
        // The Query
        $exibir_atuacao_posts = new WP_Query( $args );
        // The Loop
        if ( $exibir_atuacao_posts->have_posts() ) {
            while ( $exibir_atuacao_posts->have_posts() ) {
                $exibir_atuacao_posts->the_post();
        ?>
        <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
        <?php 
            }
        } else {
            echo "Nenhum post encontrado";
        }
        // Restore original Post Data
        wp_reset_postdata();
        ?>
    </ul>

有更好的解决方案吗?或者如果没有,如何将"活动"类添加到 href?

更新:您可以实时查看网站。

您需要

将当前帖子 ID 存储在变量中,然后您需要将当前帖子 ID 与列表项帖子 ID 进行比较,如果两者相同,则应用活动类。所以你的代码将是这样的——

<ul class="menu-advogados">
    <?php
         global $post;
         $post_id = $post->ID; // Store current page ID in a variable.
        // WP_Query arguments
        $args = array (
            'post_type'              => 'atuacao_posts',
            'pagination'             => false,
            'order'                  => 'ASC',
            'orderby'                => 'title',
        );
        // The Query
        $exibir_atuacao_posts = new WP_Query( $args );
        // The Loop
        if ( $exibir_atuacao_posts->have_posts() ) {
            while ( $exibir_atuacao_posts->have_posts() ) {
                $exibir_atuacao_posts->the_post();
        ?>
        <li><a href="<?php the_permalink(); ?>" <?php echo ($post_id==$post->ID)?'class="active"':''; ?> ><?php the_title(); ?></a></li>
        <?php 
            }
        } else {
            echo "Nenhum post encontrado";
        }
        // Restore original Post Data
        wp_reset_postdata();
        ?>
    </ul>

使用这个

// WP_Query arguments
$args = array (
    'post_type'              => 'atuacao_posts',
    'post_status'            => 'publish',
    'pagination'             => false,
    'order'                  => 'ASC',
    'orderby'                => 'title',
);
// The Query
$query = new WP_Query( $args );
<?php if ( $query ->have_posts() ) : ?>
    <!-- the loop -->
    <?php while ( $query ->have_posts() ) : $query ->the_post(); ?>
        <h2><?php the_title(); ?></h2>
    <?php endwhile; ?>
    <!-- end of the loop -->
    <?php wp_reset_postdata(); ?>
<?php else : ?>
    <p><?php _e( 'Sorry, no posts matched your criteria.' ); ?></p>
<?php endif; ?>

对于WP_Query考虑这个链接
,这是一篇很棒的文章......