Add ACF data to rest API query. Live search feature.

[ad_1]

I have a baking website that uses the content for recipes but uses ACF for some info to fill out like ingredients, bake time, ect. The content is searchable If i put power sugar somewhere in the body it will bring up the caramel recipe for example. However If I have cats as an ingredient using ACF so my client has a formatted website when I search cats nothing comes up. The reason is it's saved in the database as some kind of serialized code. I want to add a query for each custom field but it's a bit tricky and when I think i add it nothing shows up in the search anymore.

database

wp json

<?php


add_action('rest_api_init', 'bakingRegisterSearch');

function bakingRegisterSearch()
{
    register_rest_route('baking/v1', 'search', array(
        'methods' => WP_REST_SERVER::READABLE,
        'callback' => 'bakingSearchResults',
    ));
}

function bakingSearchResults($data)
{
    $mainQuery = new WP_Query(array(
        'post_type' => array('post', 'page', 'recipe', 'categories',),
        's' => sanitize_text_field($data['term']),
    ));
    $results = array(
        'generalInfo' => array(),
        'recipes' => array(),
        'categories' => array(),

    );

    while ($mainQuery->have_posts()) {
        $mainQuery->the_post();

        if (get_post_type() == 'post' or get_post_type() == 'page') {
            array_push($results['generalInfo'], array(
                'title' => get_the_title(),
                'permalink' => get_the_permalink(),
                'postType' => get_post_type(),
                'authorName' => get_the_author()
            ));
        }

        if (get_post_type() == 'recipe') {
            array_push($results['recipes'], array(
                'title' => get_the_title(),
                'permalink' => get_the_permalink(),
                'image' => get_the_post_thumbnail_url(0, 'recipe-card')
            ));
        }

        if (get_post_type() == 'categories') {
            array_push($results['categories'], array(
                'title' => get_the_title(),
                'permalink' => get_the_permalink(),
                'image' => get_the_post_thumbnail_url(0, 'recipe-card')
            ));
        }
    }

    return $results;
}

[ad_2]

 

This site will teach you how to build a WordPress website for beginners. We will cover everything from installing WordPress to adding pages, posts, and images to your site. You will learn how to customize your site with themes and plugins, as well as how to market your site online.

Buy WordPress Transfer