• I have a get_posts loop that can be on posts and pages. In both cases the the_title function of the single loop items shows the title of the post or page the loop is on.

    Here is an (simplified) example (index.php):

    <?php get_header(); ?>
        <?php if( have_posts() ): while( have_posts() ): the_post(); $postID = get_the_ID(); ?>
    
            <?php $args = array( 'cat'=>1234 ); $myposts = get_posts( $args ); if( !empty( $myposts ) ): foreach( $myposts as $post ) : setup_postdata( $post ); ?>
    
                <?php var_dump( $post ); the_title(); ?>
    
            <?php endforeach; else: endif; wp_reset_postdata(); ?>
    
        <?php endwhile; endif; ?>
    <?php get_footer(); ?>

    The var_dump function shows on each element the correct post information but the title_function shows wrongly the parent elements title.

    I absolutely dont know what is wrong Oo. Sorry about my english.

Viewing 2 replies - 1 through 2 (of 2 total)
  • Thread Starter JhnnsGrndy

    (@jhnnsgrndy)

    Ok i tested my code above and it works great the problem in my specific case is that that part:

    <?php $args = array( 'cat'=>1234 ); $myposts = get_posts( $args ); if( !empty( $myposts ) ): foreach( $myposts as $post ) : setup_postdata( $post ); ?>
    
        <?php var_dump( $post ); the_title(); ?>
    
    <?php endforeach; else: endif; wp_reset_postdata(); ?>

    is inside a function

    Thread Starter JhnnsGrndy

    (@jhnnsgrndy)

    Ok here is the solution call

    global $post;

    right before the get_posts foreach function like this:

    global $post; foreach( $myposts as $post ) : setup_postdata( $post );

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘the_title() in get_posts() shows page title’ is closed to new replies.