Skip Navigation

[Resolved] Only show current User’s posts in post reference field

This thread is resolved. Here is a description of the problem and solution.

Problem: I have a post reference field that shows all the posts. I would like to filter the options so that only posts by the current logged-in User are shown.

Solution: Use this custom code snippet:

/* --------------------------------------------- */
// FILTER POST REFERENCE FIELD
// Filter the posts in a post reference field by author, where the author is the current User
function filter_reference_posts( $query ){
 
    $target_page = 12345; // ID of page with form, or string of page slug
    $ref_post_type = "cpt-slug"; // slug of post type in the post reference field
    if ( ( is_page( $target_page ) || ( defined('DOING_AJAX') && DOING_AJAX ) ) && is_array($query->get( 'post_type')) && in_array($ref_post_type, $query->get('post_type')) ) {
        $current_user = get_current_user_id();
 
        $query->set( 'author', $current_user );
    }
}
add_action( 'pre_get_posts', 'filter_reference_posts' );
This support ticket is created 6 years, 1 month ago. There's a good chance that you are reading advice that it now obsolete.

This is the technical support forum for Toolset - a suite of plugins for developing WordPress sites without writing PHP.

Everyone can read this forum, but only Toolset clients can post in it. Toolset support works 6 days per week, 19 hours per day.

Sun Mon Tue Wed Thu Fri Sat
8:00 – 12:00 8:00 – 12:00 8:00 – 12:00 8:00 – 12:00 8:00 – 12:00 - -
13:00 – 17:00 13:00 – 17:00 13:00 – 17:00 13:00 – 17:00 13:00 – 17:00 - -

Supporter timezone: America/New_York (GMT-04:00)

This topic contains 2 replies, has 2 voices.

Last updated by wernerB 6 years, 1 month ago.

Assisted by: Christian Cox.

Author
Posts
#1145878

Great, that works.
how can I show only the records from the logged-in user?

#1145951

Hi, I have a custom code snippet you can use to filter the post reference field:

/* --------------------------------------------- */
// FILTER POST REFERENCE FIELD
// Filter the posts in a post reference field by author, where the author is the current User
function filter_reference_posts( $query ){

    $target_page = 12345; // ID of page with form, or string of page slug
    $ref_post_type = "cpt-slug"; // slug of post type in the post reference field
    if ( ( is_page( $target_page ) || ( defined('DOING_AJAX') && DOING_AJAX ) ) && is_array($query->get( 'post_type')) && in_array($ref_post_type, $query->get('post_type')) ) {
        $current_user = get_current_user_id();

        $query->set( 'author', $current_user );
    }
}
add_action( 'pre_get_posts', 'filter_reference_posts' );

Replace 12345 with the numeric ID of the page containing this Form, and replace cpt-slug with the slug of the post type in the post reference field.

#1145990

My issue is resolved now. Thank you!