Roots Discourse

How to handle WP_Query results on a blade template

I’m using Sober\Controller class, and I want to show some random testimonials on my homepage. they are a custom post type simple custom post type. it supports title, editor and thumbnail

<?php
     namespace App;
    use Sober\Controller\Controller;
    use WP_Query;

    class FrontPage extends Controller {
    	public function random_testimonials() {
	    $args = array(
	    	'post_type' => 'testimonios',
	    	'orderby'	=> 'rand',
	    	'posts_per_page' => 3,
	    );
	    $the_query = new WP_Query( $args );
	    return $the_query;
    }
}

my problem is not having a clue on how to get those values on the template, tried several things… this is what i think its the closest thing to make the foreach to work, but the variable i’m trying to return is wrong

 @if($random_testimonials)
     <section class="testimonials">
             @foreach($random_testimonials as $testimonial)
                 {{ $testimonial['post_title'] }}
             @endforeach
     </section>
 @endif

this returns:
Notice: Undefined index: post_title in cache/compiled/ec1ff1ab1f0ae04c6d6f8ab597a68a8965a06a47.php on line 40

nothing seems to work… starting to freak out…

2 Likes

this is the return from the function using

    <pre>
        @php(print_r($random_testimonials))
    </pre>

https://pastebin.com/DkMxBWYw

Based on your print_r, maybe try looping

$random_testimonials->posts

instead?

Or you could try looping through the posts:

@while($random_testimonials->have_posts()) @php($random_testimonials->the_post())
  {!! get_the_title() !!}
@endwhile
@php(wp_reset_postdata())
1 Like

Hello people !
I have a proposition slight_smile:

in my controller “App.php”

 /**
     * Show 2 random projects
     * @return array
     */
    public static function getRandomProjects(int $nbProjects)
    {
        
        // choose $nbProjects projects from portfolio
        $args =  array(
            'post_type' => 'portfolio',
            'orderby'        => 'rand',
            'posts_per_page' =>  $nbProjects,
        );
        $projects = new \Wp_Query($args);
        
        if ($projects->have_posts()) {
            // get the total of projet
            // $totalNbProjects = wp_count_posts( 'portfolio' )->publish;
            return $projects;
        } else {
            return "no project";
        }

    }

And in my “front.blade.php”

  @php $projects = App::getRandomProjects(2); @endphp
  @if($projects)
    <section class="projects">
      <h2 class="section-title">Quelques réalisations</h2>
      @foreach($projects->get_posts() as $project)
        {{ $project->post_title }}
      @endforeach
    </section>
  @endif

What about it ?