创建一个wordpress函数,以类别ID作为参数,但无法获取正确的数据

我试图在“functions.php”中创建一个函数,每次调用它时我只需要告诉我想要哪个类别ID。

最终结果应该是这样的: Mockup - Posts inside a Carousel

如果没有函数,我可以在“front-page.php”文件中执行此操作,但如果我开始插入更多类别,代码将变得过于混乱和重复。

现在这就是我所拥有的(front-page.php):

<div id="carouselExampleControls" class="carousel slide" data-ride="carousel">

<div class="carousel-inner">


  <?php 

    $args = array(

      'posts_per_page' => -1,

      'post_type' => 'post',

      'orderby' => 'date',

      'order' => 'ASC',

      'category__in' => 1515

    );

                

            $firstCategory = get_posts( $args );

    $i = true;


    foreach (array_chunk($firstCategory, 3, true) as $firstCategory) : ?>


      <div class=" carousel-item <?php echo $i ? ' active' : '' ?>">


        <?php foreach( $firstCategory as $post ) : setup_postdata($post); ?>


          <div class="card col-4">

                            

                            <?php if( has_post_thumbnail() ) :  ?>

                  

              <div class="card-header">

                <a href="<?php the_permalink() ?>">


                  <?php the_post_thumbnail('thumbnail', array(

                    'alt' => trim(strip_tags( $post->post_title )),

                    'title' => trim(strip_tags( $post->post_title ))

                  )); ?>


                </a>

              </div>

                  

              <?php endif; ?>


                <div class="card-body">

                  <h3 class="card-title"> <?php the_title(); ?> </h3>

                  <p class="card-text"> <?php 

                    if(has_excerpt()) {

                      echo get_the_excerpt(); 

                    } else {

                      echo wp_trim_words(get_the_content(), 15);

                    }

              ?> 

                    

                  </p>

                    <a href=" <?php the_permalink(); ?>" class="card-link">Ver mais</a>

                </div>

          </div>


快速解释一下,此代码从类别中获取帖子,并每次在轮播中插入 3 个帖子。


当我在&ldquo;functions.php&rdquo;中执行此操作时,我无法检索所有正确的数据。只有链接和标题就可以了。


红糖糍粑
浏览 204回答 1
1回答

炎炎设计

我们可以修复/改进一些事情,但您最紧迫的问题是has_excerpt接受帖子或帖子 ID,更改has_excerpt($post->post_excerpt)为has_excerpt($post)trim(strip_tags($post->ID))只是给你 ID,你想要别的东西,也许是 post_title&nbsp;trim(strip_tags($post->post_title))?另外,不要setup_postdata($post)在循环中使用使用get_the_post_thumbnail($post, 'thumbnail', $args)而不是the_post_thumbnail('thumbnail', $args)并使用get_the_excerpt($post)而不是the_excerpt()注意:默认属性为get_the_post_thumbnail:$default_attr = [&nbsp; &nbsp; 'src'&nbsp; &nbsp;=> $src,&nbsp; &nbsp; 'class' => "attachment-$size_class size-$size_class",&nbsp; &nbsp; 'alt'&nbsp; &nbsp;=> trim( strip_tags( get_post_meta( $attachment_id, '_wp_attachment_image_alt', true ) ) ),];简而言之,您的主要问题是您混淆了全局 $post 和本地范围的 $post (及其元数据)。the_post_thumbnail并&nbsp;the_excerpt检查全局 $post,但has_post_thumbnail使用has_excerpt本地 $post。Plussetup_postdata($post)也会导致一些连锁问题。最好的解决方案是完全忽略全局 $post。
打开App,查看更多内容
随时随地看视频慕课网APP