Skip to content

Instantly share code, notes, and snippets.

@yanknudtskov
Created June 9, 2020 14:06
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save yanknudtskov/f286815010ee4762deb8acfb754eab73 to your computer and use it in GitHub Desktop.
Save yanknudtskov/f286815010ee4762deb8acfb754eab73 to your computer and use it in GitHub Desktop.
Example on how to meta query ACF repeater fields
<?php
add_shortcode( 'user_company_link', 'yanco_user_company_link' );
function yanco_user_company_link() {
if( ! is_user_logged_in() ) {
return;
}
$html = '';
$current_user = wp_get_current_user();
$current_user_id = $current_user->ID;
// Check if the user is attached to any companies
$query_args = array(
'post_type' => 'virksomhed',
'post_status' => 'publish',
'suppress_filters' => false,
'meta_query' => array(
'relation' => 'OR',
array (
'key' => 'acf_virksomhed_admins_$_user',
'value' => $current_user_id,
),
array(
'key' => 'acf_virksomhed_users_$_user',
'value' => $current_user_id,
)
),
);
$query = new WP_Query( $query_args );
if( count( $query->posts ) ) {
}
}
add_filter('posts_where', 'yanco_posts_where');
function yanco_posts_where( $where ) {
$where = str_replace( "meta_key = 'acf_virksomhed_admins_$", "meta_key LIKE 'acf_virksomhed_admins_%", $where );
$where = str_replace( "meta_key = 'acf_virksomhed_users_$", "meta_key LIKE 'acf_virksomhed_users_%", $where );
return $where;
}
@strarsis
Copy link

@yanknudtskov: Wow, so simple and elegant, near-self explanatory! Thank you very much, this was very useful for me. Before using this query I had to iterate over all the posts, then over the repeater field of each post, which was very slow and performance intensive.
With a query there is basically no overhead.

@heymicoo
Copy link

@yanknudtskov Hi, is this still working on your end?

@yanknudtskov
Copy link
Author

@heymicoo yup still works here, we're using it in several production sites currently and seems to be working as inteded :-)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment