Last active
April 13, 2021 11:21
-
-
Save PatelUtkarsh/632e883486f2ef35817b44f44b0dfcc4 to your computer and use it in GitHub Desktop.
ACF exclude current post from post object
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace Utkarsh\acf; | |
/** | |
* Exclude current post from ACF filter. | |
* Add param include_current_post => true in ACF field if you need include current post. Defaults to exclude. | |
* | |
* @param array $args WP_Query args. | |
* @param array $field ACF field params. | |
* @param int $post_id current post id. | |
* | |
* @return mixed | |
*/ | |
function acf_filter_posts( $args, $field, $post_id ) { | |
if ( isset( $field['include_current_post'] ) || ! empty( $field['include_current_post'] ) ) { | |
return $args; | |
} | |
$post_type = get_post_type( $post_id ); | |
if ( ! isset( $args['post_type'] ) || ! in_array( $post_type, $args['post_type'], true ) ) { | |
return $args; | |
} | |
$args['post__not_in'] = [ $post_id ]; // Poor query. | |
return $args; | |
} | |
add_filter( 'acf/fields/post_object/query', __NAMESPACE__ . '\\acf_filter_posts', 10, 3 ); | |
add_filter( 'acf/fields/relationship/query', __NAMESPACE__ . '\\acf_filter_posts', 10, 3 ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment