ACF
тип поля отношения сохраняет свои значения как serialized array
в базе данных. Быстрый поиск по serialized array
в базе данных как meta field
невозможен для этого типа поля.
Я рекомендую перестроить и добавить собственный обработчик для обновления relation field
в , ориентированный на скорость структура для получения значений.
Я предлагаю решение, основанное на перестройке этого типа поля с настраиваемой структурой для быстрого получения related_resources
( с использованием вашей собственной мета поля )
Коды фрагментов
1. Создание пользовательской структуры для существующих постов
//run this hook for build existing acf to speed search by meta structure
add_action( 'wp', 'theme_prefix_build_resources_products_meta' );
function theme_prefix_build_resources_products_meta() {
/* Visit the web site with theme-prefix-rebuild-resources-products GET param for
building existing resources to structure for searching*/
// if needed - you could add permission checking and wp_nonce checking
if ( ! isset( $_GET['theme-prefix-rebuild-resources-products'] ) ) {
return;
}
wp_suspend_cache_addition( true ); // Prevent Fatal Error by Memory overflow if there is a lot of resources posts
$args = [
'post_type' => 'resources',
'post_status' => [ 'publish', 'pending', 'draft', 'auto-draft', 'future', 'private', 'inherit', 'trash' ],
'paged' => 1,
'posts_per_page' => 20,
];
$meta_key = 'your-prefix-resource-product-id';
while ( ! empty( $posts = get_posts( $args ) ) ) {
foreach ( $posts as $post ) {
$products = get_field( 'products', $post->ID );
if ( empty( $products ) ) {
continue;
}
delete_post_meta( $post->ID, $meta_key );
foreach ( $products as $product ) {
add_post_meta( $post->ID, $meta_key, $product->ID );
}
}
$args['paged'] ++;
}
}
2. Обновите поле для ускорения структуры
// store the relation field for searching structure
add_filter( 'acf/update_value', 'theme_prefix_acf_update_field', 10, 3 );
function theme_prefix_acf_update_field( $value, $post_id, $field ) {
if ( ( 'products' !== $field['name'] ) || ( 'resources' !== get_post_type( $post_id ) ) ) {
return $value;
}
$meta_key = 'your-prefix-resource-product-id';
delete_post_meta( $post_id, $meta_key );
$products_ids = $value;
if ( empty( $products_ids ) ) {
return $value;
}
foreach ( $products_ids as $product_id ) {
add_post_meta( $post_id, $meta_key, $product_id );
}
return $value;
}
3. Получить связанные ресурсы
//You could get related_products in loop by calling theme_prefix_get_related_products( get_the_ID() ) ON Resource page
function theme_prefix_get_related_products( $resource_id ) {
$resource_products = get_field( 'products' );
$related_products_ids = wp_list_pluck( $resource_products, 'ID' );
$meta_key = 'your-prefix-resource-product-id';
$meta_queries = array_map(
function ( $related_product_id ) use ( $meta_key ) {
return [
'key' => $meta_key,
'value' => $related_product_id,
'compare' => '=',
];
},
$related_products_ids
);
$args = [
'post_type' => 'resources',
'post_status' => 'publish',
'posts_per_page' => 5,
'paged' => 1,
'orderby' => 'rand',
'meta_query' => [ $meta_queries ]
];
return get_posts( $args );
}