Last active
November 26, 2020 10:17
-
-
Save morgyface/b9c106509d6ba79195c07569466ef724 to your computer and use it in GitHub Desktop.
WordPress | ACF | Selected or fallback
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 | |
| /** | |
| * Works with the ACF relationship field to always display the quota of posts | |
| */ | |
| function selected_or_fallback( $current_id, $total_required, $acf_relationship_name, $post_type = null) { | |
| $excluded = array( $current_id ); | |
| $obtained = 0; | |
| $related = array(); | |
| // Check to see if any posts have been selected via ACF relationship | |
| $selected = get_field( $acf_relationship_name ); | |
| if( $selected ) { | |
| $related = $selected; | |
| $obtained = count( $selected ); | |
| if ( $obtained < $total_required ) { | |
| // If the quota not met update excluded array for get_posts query | |
| $selected_ids = get_field($acf_relationship_name, false, false); // Returns an array of IDs | |
| $excluded = array_merge($selected_ids, $excluded); | |
| } | |
| } | |
| if ( $obtained < $total_required ) { | |
| if( $selected ) { | |
| $post_type = get_post_type( $selected_ids[0] ); | |
| } else { | |
| if ( !$post_type ) { | |
| $post_type = get_post_type( $current_id ); | |
| } | |
| } | |
| $required = $total_required - $obtained; | |
| $args = array( | |
| 'posts_per_page' => $required, | |
| 'post_type' => $post_type, | |
| 'exclude' => $excluded | |
| ); | |
| $posts = get_posts( $args ); | |
| if( $posts ) { | |
| $related = array_merge($related, $posts); | |
| } | |
| } | |
| return $related; | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Update October 2020
Further update allowing you to pass in a post-type variable. Whilst the last update was good, it failed where no posts were selected on somewhere like the homepage as the function wouldn't be able to determine the intended post-type and would instead display pages.