javascript - 在 while 循环之外显示帖子描述

标签 javascript wordpress custom-post-type

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

enter image description here

<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>

最佳答案

您可以使用 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 );
    });
});

关于javascript - 在 while 循环之外显示帖子描述,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58253419/

相关文章:

php - Wordpress:previous_post_link/next_post_link 按字母顺序排列?

wordpress - WP the_content() 不会显示在自定义帖子类型的单个模板中

mysql - 切换主机、移动数据库,但遇到问题

javascript - 如何在WordPress上实现Bootstrap Tour

JavaScript 设置 cookie

javascript - 如何使用cookie保存用户每次打开页面时的点击值抓取cookie

php - 如何从 WordPress 插件中的函数下载 CSV 文件?

php - 使用 Gutenberg 将缩略图添加到自定义帖子类型 WordPress

javascript - 如何执行单个 Struts 表单提交操作

javascript - 如何在扩展垫行而不是主表中显示垫表