Steps
1. Create ACF Fields
- Installation:
- Install and activate the Advanced Custom Fields plugin in the WordPress admin dashboard.
- Field Group Setup:
- Navigate to Custom Fields > Field Groups and create a new field group.
- Define the necessary fields within the group, noting the field names for future reference.
2. Create a Custom Template
- Template File Creation:
- Within the theme folder, create a new template file for the desired page or post type.
- Adhere to WordPress template hierarchy naming conventions (e.g.,
single-{post-type}.phporpage-{template-name}.php). - Template Implementation:
- Inside the template file, use the
get_fieldfunction to retrieve and display ACF field values.
example :
<?php
// Template Name: Custom Template
get_header();
if (have_posts()) :
while (have_posts()) : the_post();
$custom_field_value = get_field(‘your_acf_field_name’);
// Use $custom_field_value in your template
endwhile;
endif;
get_footer();
3. Create a Custom API Endpoint
- Function Definition:
- Define a function to handle the API request and return ACF field data in your theme’s
functions.phpfile or a custom plugin. - Endpoint Registration:
- Register the custom API endpoint using the
register_rest_routefunction.
Example :
function custom_api_get_acf_data($data) {
$post_id = $data[‘id’];
$custom_field_value = get_field(‘your_acf_field_name’, $post_id);
return rest_ensure_response($custom_field_value);
}
add_action(‘rest_api_init’, function () {
register_rest_route(‘custom/v1’, ‘/acf-data/(?P<id>d+)’, array(
‘methods’ => ‘GET’,
‘callback’ => ‘custom_api_get_acf_data’,
));
});
4. Access the Custom API Endpoint
- Utilize the custom API endpoint URL (
yoursite.com/wp-json/custom/v1/acf-data/{post_id}) to programmatically fetch ACF data.