Tell us what you are trying to do?
Hi, I have a CPT "Group" that has a reference post field "Members". Everything is working fine. Members CPT has a custom field status ('active', 'resigned' etc.). I want to filter Members by its custom field 'status'. I have seen this link where Chirstian described how can we filter reference post type in an add form using page id or page slug. https://toolset.com/forums/topic/only-show-current-users-posts-in-post-reference-field/
1. I want to use the same in page edit form as well that is called in a content template, should I just simply use the content template id? (I tried by with no results)
2. I want to filter reference post by its own custom field, what I have to add in query?
* --------------------------------------------- */
// 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' );
If this form is on a content template you will need to get the id of the page that is being generate with the edit form. Add this to the content template that the edit form is on [wpv-post-id] this should give you the ID of the page.