Если я допустил ошибку в коде, пожалуйста, помогите мне разобраться.< /p>
Код: Выделить всё
function custom_search_query($query) {
global $wpdb;
// Check if this is a search query and not in the admin area
if ($query->is_search && !is_admin()) {
$search_query = get_search_query();
// The URL of the custom API endpoint
$api_url = 'http://localhost:5000/api/search/data';
// The arguments for the POST request
$args = array(
'body' => json_encode(array(
'search_query' => $search_query,
)),
'headers' => array(
'Content-Type' => 'application/json',
),
);
// Make the POST request
$response = wp_remote_post($api_url, $args);
print_r($api_url);
// Check for errors
if (is_wp_error($response)) {
$error_message = $response->get_error_message();
echo "Something went wrong: $error_message";
return;
}
// Get the body of the response
$body = wp_remote_retrieve_body($response);
// Decode the JSON response
$results = json_decode($body, true);
// Check if the response contains post IDs
if (!isset($results['post_ids']) || !is_array($results['post_ids'])) {
echo "Invalid response from API.";
return;
}
// Modify the search query to return the posts with the given IDs
$query->set('post__in', $results['post_ids']);
// Update the query to fetch the posts
add_action('the_posts', function($posts) use ($results) {
$posts = get_posts(array(
'post__in' => $results['post_ids'],
'post_type' => 'any',
'posts_per_page' => -1,
));
return $posts;
});
}
return $query;
// Подключите функцию пользовательского поиска к действию pre_get_posts
add_action('pre_get_posts', 'custom_search_query');< /п>
Подробнее здесь: https://stackoverflow.com/questions/786 ... -wordpress
Мобильная версия