I
I
Ilya2020-02-24 15:43:21
WordPress
Ilya, 2020-02-24 15:43:21

Problems with code in Wordpress?

There is a slider, there is a code:

<?php 
                        $posts = get_posts( array(
                            'numberposts' => -1,
                            'category_name'    => 'slider',
                            'orderby'     => 'date',
                            'order'       => 'DESC',
                            'post_type'   => 'post',
                            'suppress_filters' => true, 
                        ) );

                        foreach( $posts as $post ){
                            setup_postdata($post);
                            ?>
                            <div class="glide__slide">
                                <div class="contetn">
                                    <?php the_post_thumbnail('full'); ?>
                                    <div class="text">
                                        <h3><?php the_title() ?></h3>
                                        <p><?php the_excerpt() ?></p>
                                        
                                    </div>
                                </div>
                            </div>
                            <?php
                        }

                        wp_reset_postdata(); // сброс                        
                        ?>


Error:
Notice: Undefined offset: 2 in C:\xampp\htdocs\wp\wp-includes\class-wp-query.php on line 3252

Found this file on line 3252 contains:
$this->post = $this- >posts[ $this->current_post ];

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
Ilya, 2020-02-24
@cyberpunk3351

As Alex wrote . No need to use setup_postdata nor wp_reset_postdata.
I solved the problem by replacing this piece of code:

$posts = get_posts( array(
                        'numberposts' => -1,
                        'category_name'    => 'slider',
                        'orderby'     => 'date',
                        'order'       => 'DESC',
                        'post_type'   => 'post',
                        'suppress_filters' => true, 
                    ) );

                    foreach( $posts as $post ){

this:
$args = array( 'posts_per_page' => 2 );
                    $lastposts = get_posts( $args );
                    foreach( $lastposts as $post ){

and everything worked!

A
Alex, 2020-02-24
@Kozack

Notice: Undefined offset
It's not really a mistake. This is just a message that $this->poststhere is nothing in the key. $this->current_post
I would not use either setup_postdata or wp_reset_postdata if I were you.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question