首页 > 解决方案 > 在while循环外显示帖子描述

问题描述

我有一个使用 WP_Query 类调用的团队成员列表(自定义帖子类型)。这部分正在工作,但是我试图在单击他们的名字时在 while 循环之外显示团队成员的描述 (the_content())。如您在代码中所见,此容器 (#team-info) 位于 while 循环之外。理想情况下,页面会在单击名称后滚动到描述容器。

在此处输入图像描述

<div class="container">
<div class="row">
    <div class="col-md-12">
        <div id="team-info"></div>
    </div>
</div>

<div class="container mt-15">
<div class="row">
    <div class="col-md-12">
    <?php
        // The Query
        $the_query = new WP_Query( array (
            'post_type' => 'my_team_sp',
        ) );

        if( $the_query->have_posts() ): $i = 0;
            while ( $the_query->have_posts() ) : $the_query->the_post(); $i++; ?>
                 <div class="col-md-4 <?php echo $i ;?>">
                        <a href="#" id="team-name" onclick="myFunction()"><h4><?php the_title() ;?></h4></a>
                    </div>
            <?php endwhile;
        else :
        endif;


        /* Restore original Post Data */
        wp_reset_postdata();
        ?>
    </div>
</div>

标签: javascriptwordpresscustom-post-type

解决方案


你可以试试这个jQuery。请参阅下面的代码。

<div class="container mt-15">
    <div class="row">
        <div class="col-md-12">
        <?php
            // The Query
            $the_query = new WP_Query( array (
                'post_type' => 'my_team_sp',
            ) );

            if( $the_query->have_posts() ): $i = 0;
                while ( $the_query->have_posts() ) : $the_query->the_post(); $i++; ?>
                    <div class="col-md-4 <?php echo $i ;?>">
                        <a href="javascript:void(0)" class="team-name"><h4><?php the_title() ;?></h4></a>
                        <div style="display: none;"><?php the_content(); ?></div>
                    </div>
            <?php endwhile;
        else :
        endif;

        /* Restore original Post Data */
        wp_reset_postdata();
        ?>
    </div>
</div>

jQuery

Js在您的文件中添加此代码。

jQuery(document).ready(function($){
    $( '.team-name' ).on('click', function(){
        var teamInfo = $(this).next().html();
        $( '#team-info' ).html( teamInfo );
    });
});

推荐阅读