Query custom posts filtered by ACF users id Wordpress

39 Views Asked by At

I created a post type called "mypost". using ACF.

Tried to do a user assign by using a user field. Field name = usersacf

I want to show only the post that has been assigned to him in the user Woocommerce dashboard. I use Elementor. I created a query ID there. It is this. But it doesn't work.

I appreciate your help with this.

This is my code. but not work.

 function my_post_object_query( $args )
{
$args['author'] = get_current_user_id();

return $args;
}
add_filter('acf/fields/post_object/query/name=usersacf', 'my_post_object_query');

Getting the right code

1

There are 1 best solutions below

2
Rao azwar On

It seems like you're trying to filter the posts displayed in the "mypost" post type's user field to only show posts authored by the current user in the WooCommerce dashboard using Elementor.

Your code attempts to filter the query for the post object field named "usersacf" to only show posts authored by the current user. However, the acf/fields/post_object/query hook is not specific to a particular post type or context, so it might not behave as expected in your case.

To achieve your desired functionality, you need to ensure that the query is modified specifically when retrieving posts for the "mypost" post type and within the WooCommerce dashboard. Here's how you can achieve this:

function filter_mypost_query_for_current_user( $query ) {
// Check if we are in the WooCommerce dashboard
if ( is_admin() && function_exists( 'is_wc_endpoint_url' ) && is_wc_endpoint_url() ) {
    global $pagenow;

    // Ensure we are on the correct page and dealing with "mypost" post type
    if ( $pagenow === 'edit.php' && isset( $_GET['post_type'] ) && $_GET['post_type'] === 'mypost' ) {
        // Modify the query to show posts authored by the current user
        $query->set( 'author', get_current_user_id() );
    }
}
}

add_action( 'pre_get_posts', 'filter_mypost_query_for_current_user' );