Loop with variable 'post_type' field

Hi guys :wave:t2:

I’m trying to do an all-in-one query function to display posts or custom post types in blade templates. Before i would simply duplicate the function and set manually the args.

Here is the code where i need to get post_type value (line 4). I know $post is not declared, i think it’s easy but i’m missing something.

  public function postsQuery()
        $items = get_posts([
            'post_type' => get_field('posts_type', $post),
            'posts_per_page' => '10',

        return array_map(function ($post) {
            global $post;
            return [
                'url' =>  get_permalink($post),
                'title' => get_the_title($post),
                'thumbnail' => get_the_post_thumbnail_url($post, 'large'),
                'category' => get_the_category($post)
        }, $items);

I will leave there the code for displaying the loop if it helps someone:

@foreach ($posts as $item)
    <a href="{{$item['url']}}">

What is the actual problem you’re running into? What does this code not do that you expect it to do? Is it throwing errors? What errors?

Thank you @alwaysblank .

Loop is running fine but it’s returning posts by default, my get_field(‘posts_type’, $post) is not doing its job, so I think Wordpress serves me the posts because post_type is empty instead of my custom post type.

Ofc i checked data and the field posts_type has value.

This is what’s the block is returning where “assurances” is my custom post type:
Capture d’écran 2022-07-07 à 20.34.59

You haven’t provided any other context here, but since $post is not defined, this is going to fall back to whatever the value of the $post global is. Usually $post is the first item in the Loop, but not always. If you want to look up the field value on a particular post object, you’re going to need to provide that particular post object to this function somehow. I don’t know what the context of this function is, or where you’re defining it or using it, so I’m not sure how you’d get that data.

What are you trying to accomplish here? You can’t possibly actually want the global $post, since you have $post as an argument in the function that executes this code.

I’m trying to reach ‘posts_type’ field within my block itself in my page.

Also tried for testing purposes:

'post_type' => get_field('posts_type', 19),

where 19 is my page ID but it’s not doing the trick, that’s why i tried to set a global $post.

Is the posts_type field stored on the post object or on each block? Your screenshot seems to imply “on each block” but your usage of get_field implies “on the post object.”

You are right, posts_type is stored in the block.

The block is then displayed on my page trough my builder:

  <main id="main" class="main">
    @if ($builder)
      @foreach ($builder as $block)

If I understand correctly, the post object does not know the field because it’s behind the block ?