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?
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 );
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?
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.
not sure if it is just not shown in your example code and your screenshot but you have to return the query arguments. The following (adjusted) custom query works as expected for me:
if ( ! is_user_logged_in() ) {
/* Do not return any results when there is no logged in user */
return [ 'post__in' => [ 0 ] ];
}
$current_user_id = get_current_user_id();
$current_year = date( 'Y' );
$query_args = [
'post_type' => 'grant-application',
'posts_per_page' => -1,
'author' => $current_user_id,
'orderby' => 'modified',
'order' => 'DESC',
'date_query' => [
[
'after' => [
'year' => $current_year,
'month' => '1',
'day' => '1',
],
],
],
];
return $query_args; /* Do not forget this line! */
Hi André,
do you perhaps have an idea how to display the repeater values from CPT for the currently logged in user? I tried based on your code I posted above but it doesn’t work :/.