-1

I'm using the filter to append items to the content on one page only. It's fully working except for the ordering of the $whole variable. The title is appearing after the content but the for each loop appears above or prepended to the content no matter the order. I think I am passing the loop correctly by using one($arr) but I am still learning php. I'd normally include this type of loop on page template but I'm trying to add it with a plugin.

function insertLoop($content) {

  if( is_page( 'regular-page' ) ) {

  function one( $arr ) {  

    global $post;

    $args = array( 
      'post_type' => 'custom-post-type',
      'posts_per_page' => -1,
    );

   $customposts = get_posts( $args );

   foreach ( $customposts as $post ) : setup_postdata( $post ); ?>

    <div class="custom-post-listing">
        <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
        <p><?php the_date(); ?></p>
    </div>

   <?php endforeach; wp_reset_postdata();

   }

   $words = "<h2>Custom Post Full List</h2>";

   $whole = $content . $title . one($arr);

   return $whole;

  }

}

add_filter ('the_content', 'insertLoop');
0

Filter should modify the given value and return it. It should not print anything.

But your foreach loop does exactly opposite - it prints its output and doesn’t append anything to result. So when you use it to append its result to the content, it prints its result and doesn’t return anything - so nothing gets appended.

One way to fix it is to use buffering:

function one( $arr ) {  
    ob_start();
    global $post;

    $args = array( 
      'post_type' => 'custom-post-type',
      'posts_per_page' => -1,
    );

    $customposts = get_posts( $args );

    foreach ( $customposts as $post ) : setup_postdata( $post ); ?>

    <div class="custom-post-listing">
        <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
        <p><?php the_date(); ?></p>
    </div>

    <?php endforeach; wp_reset_postdata();
    return ob_get_clean();
}

Another, a little bit cleaner is to modify this function in such way, that it constructs strings as a result.

  • I read up on ob_start and ob_get_clean(). Seems very useful but it is not working here. I also read that with WordPress it's better to use ob_get_contents so I tried that as well but it didn't work. This is what I have after I reset post data. $content .= ob_get_contents(); return $content; – scottie5689 Jun 6 at 3:13
  • I guess you misunderstood the answer... – Krzysiek Dróżdż Jun 6 at 6:23
  • 1
    Reread and realized that what I was doing wrong. I only needed to add the filter, not wrap it in another function to return it. Makes sense now, thank you. – scottie5689 Jun 7 at 17:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.