Return blog posts

Hi there,

I have a problem with return array map with blog posts.

my controller

public function blogPosts() {

	$blog_posts = get_posts([
	    'post_type' => 'post',
	    'posts_per_page' => -1,
	
	]);

	return array_map(function ($post) {
	    return [
	        'categories' => get_the_category($post),
	        'title'      => get_the_title($post),
	        'url'        => get_permalink($post),
	        'date'       => get_the_date('M d, Y', $post),
	        'image'      => get_the_post_thumbnail_url($post),
	    ];
	}, $blog_posts);

}

my front:
@foreach ($blog_posts as $post)
{!! $post[‘title’] !!}
@endforeach

I can’t figure out what I am doing wrong in this case …

Have you tried debugging each step of your function with var_dump or dd or a similar feature to make sure the data at is stage is what you expect? What is the name of your controller? Have you tired debugging the variables in your blade with @dump?What are the results? How is the code you posted failing?

Hi alwaysblank, thank you for quick reply.

My controller name is BlogList as class name

namespace App\Controllers;

use Sober\Controller\Controller;

class BlogList extends Controller

Ofcourse I run debug mode right now …

I’ve got notice
Notice : Undefined variable: blog_posts

Warning : Invalid argument supplied for foreach()

Controller follows the WordPress hierarchy, and requires class and file names to match up with template names in the WordPress hierarchy, see: https://github.com/soberwp/controller#overview I don’t believe there’s a template called BlogList so your controller probably isn’t matching whatever page you’re trying to load it on.

It’s important to remember that Controller matches WordPress template names not blade file names. So if you’re, say, @includeing bloglist.blade.php on your front page, your controller will need to be named FrontPage or something similar in order to match.

1 Like

Alwaysblank - thank you ! I forgot about that controller must be the same name as template. Everything works.
Thank you so much for your help.

This topic was automatically closed after 42 days. New replies are no longer allowed.