Возникли проблемы при поиске в Algolia Search для распознавания моих пользовательских полей

Недавно я внедрил плагин Algolia Search WordPress в новую сборку WP для моего клиента. Сайт будет в основном использоваться для сбора данных опроса и предоставления его администраторам надежных функций поиска.

Я создал пользовательский тип записи, который будет содержать уникальную запись для каждой отправки в опрос. Каждое поле ввода опроса помещается в настраиваемое поле в сообщении.

В следующем примере я пытаюсь реализовать функцию извлечения и извлечения настраиваемого поля Algolia: https://community.algolia.com/wordpress/advanced-custom-fields.html#push-custom-fields-to-algolia. Мой пользовательский тип записи называется «Представления», и я пытаюсь вставить настраиваемое поле с ключом «имя_организации» в этом типе записи. Опять же, я думаю, что все настроено правильно, но это пользовательское поле не индексируется Алголией. Любая помощь будет принята с благодарностью.

// Push custom fields to Algolia
add_filter( 'algolia_post_shared_attributes', 'my_post_attributes', 10, 2 );
add_filter( 'algolia_searchable_post_shared_attributes', 'my_post_attributes', 10, 2 );

/**
* @param array   $attributes
* @param WP_Post $post
*
* @return array
*/
function my_post_attributes( array $attributes, WP_Post $post ) {

if ( 'submissions' !== $post->post_type ) {
// We only want to add an attribute for the 'submissions' post type.
// Here the post isn't a 'submission', so we return the attributes unaltered.
return $attributes;
}

// Get the field value with the 'get_field' method and assign it to the attributes array.
// @see https://www.advancedcustomfields.com/resources/get_field/
$attributes['organisation_name'] = get_field( 'organisation_name', $post->ID );

// Always return the value we are filtering.
return $attributes;
}// Make custom fields searchable
add_filter( 'algolia_posts_index_settings', 'my_posts_index_settings' );
// We could also have used a more general hook 'algolia_posts_index_settings',
// but in that case we would have needed to add a check on the post type
// to ensure we only adjust settings for the 'speaker' post_type.

/**
* @param array $settings
*
* @return array
*/
function my_posts_index_settings( array $settings ) {

if ( 'submissions' !== $post->post_type ) {
return $settings;
}

// Make Algolia search into the 'bio' field when searching for results.
// Using ordered instead of unordered would make words matching in the beginning of the attribute
// make the record score higher.
// @see https://www.algolia.com/doc/api-client/ruby/parameters#attributestoindex
$settings['attributesToIndex'][] = 'unordered(organisation_name)';

// Make Algolia return a pre-computed snippet of 50 chars as part of the result set.
// @see https://www.algolia.com/doc/api-client/ruby/parameters#attributestohighlight
$settings['attributesToSnippet'][] = 'organisation_name:50';

// Always return the value we are filtering.
return $settings;
}

1

Решение

Пример здесь: https://community.algolia.com/wordpress/advanced-custom-fields.html#push-custom-fields-to-algolia адреса интеграции с плагином Advanced Custom Field.

При этом, вы также можете заменить get_field звонки с get_post_meta, который является родным для WordPress.

Вот пример:

<?php

add_filter( 'algolia_post_shared_attributes', 'my_post_attributes', 10, 2 );
add_filter( 'algolia_searchable_post_shared_attributes', 'my_post_attributes', 10, 2 );

/**
* @param array   $attributes
* @param WP_Post $post
*
* @return array
*/
function my_post_attributes( array $attributes, WP_Post $post ) {$attributes['_geoloc']['lat'] = (float) get_post_meta( $post->ID, 'latitude', true );

$attributes['_geoloc']['lng'] = (float) get_post_meta( $post->ID, 'longitude', true );// Always return the value we are filtering.

return $attributes;
}

Здесь мы получаем 2 мета поля latitude & longitude из поста.

5

Другие решения

Я решил это! Проблема заключалась в том, что этот код предназначался только для использования с плагином Advanced Custom Fields (ACF). Функция my_post_attributes () вызывала метод get_field (), которого не было в моей установке WordPress, потому что мои настраиваемые поля не создавались плагином ACF. После того, как я установил плагин, код успешно перенес пользовательское поле в Algolia.

// Get the field value with the 'get_field' method and assign it to the attributes array.
// @see https://www.advancedcustomfields.com/resources/get_field/
$attributes['organisation_name'] = get_field( 'organisation_name', $post->ID );
2

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector