Query custom post the belong to the logged in user

Think of a directory. To manage the listings, we built a dashboard in the back on WP, where I am showing a list of items added (custom post types) – I need to show a ‘my listings’ page and display only the items created by the logged-in user. I can easily query all the items now but can’t think of a clean way to filter the items by the currently logged-in user.

I know I can create a custom query and add it to Bricks, but this seems to be a simple query. Am I missing something?

Any help will be much appreciated. Thank you!

Hey Robert,

indeed you do not need a completely custom query for this scenario. You can use the bricks/posts/query_vars hook to include the author parameter. Should look something like this:

add_filter( 'bricks/posts/query_vars', function( $query_vars, $settings, $element_id ) {
  // Replace with your query loop element's ID
  if ( $element_id !== 'fhmnfx' ) {
    return $query_vars;
  }

  if ( $user_id = get_current_user_id() ) {
    $query_vars['author'] = $user_id;
  }

  return $query_vars;
}, 10, 3 );

Let me know if that helps.

Best,

André

2 Likes

It did not worked for me… the ID of the Card element is #mc_query and this is the code I am using ( I had to add the post name as per some research I have done but still without luck

<?php

add_filter( 'bricks/posts/query_vars', function( $query_vars, $settings, $element_id ) {
  // Replace with your query loop element's ID
  if ( $element_id !== 'mc__query' ) {
    return $query_vars;
  }

  if ( $user_id = get_current_user_id() ) {
    $query_vars['post_type'] = 'compounds';
    $query_vars['author'] = $user_id;
  }

  return $query_vars;
}, 10, 3 );

am I missing something?
Do I need to define $user_id or is it already defined?

Even if you specify a custom ID (mc__query) for your element you have to use the Bricks internal ID within the hook:

CleanShot 2023-06-27 at 21.33.51@2x

1 Like

Thank you! that did it… I removed the custom ID and kept the default ID but after the #brxe- as the image above. thanks again.

You’re welcome. You can keep your custom ID though if you want. Internally the bricks ID is still used (even when specifying a custom one) and will work for the hook.

Good to know. Thank you

It’s now super easy with version 1.9.1 onwards using the query editor. Here’s how i just did mine

$current_user = wp_get_current_user();

return [
  'post_type' => 'business',
  'author' => $current_user->ID,
  'posts_per_page' => -1
];
1 Like