0
votes

I am looking to add a custom field for each post object with ACF.

I have two different custom post types: "Wash Programs" and "Washes"

I need to add on Washes Field Group a "Number Field" based on "Wash Programs" posts.

So if there are 3 different "Wash Programs", on the "Washes" i want to have 3 fields:

"Wash Program 1" -> "Number Field"
"Wash Program 2" -> "Number Field"
"Wash Program 3" -> "Number Field"

I am thinking of logic of it for many hours but still could't figure it out how to achieve this.

Any help would be appreciated.

2

2 Answers

0
votes

It sounds like you don't know how many posts "Wash Programs" will have, but every time you add a new "Wash Program" you'll need to add an additional number field to each "Wash."

Perhaps a workaround can be reached by adding a Repeater field to each "Wash" that takes two subfields: a post object and a number field.

Within that repeater then you could assign the post object of the new "Wash Program" and then the number field you need on "Wash" that is related to that "Wash Program."

0
votes

I consider that many of developers out there will face this kind of request sometime, so I will post here how I made this work.

So basically I queried for all Wash Programs first and then for each wash program I created new field on Washes field group

Here is the code

<?php 
// Check if function exists
if( function_exists('acf_add_local_field_group') ):

// Query the wash_program posts
$posts = get_posts(array(
    'posts_per_page'    => -1,
    'post_type'         => 'wash_program'
));

// Initialize empty array for filling later
$arr = [];

// Just a number to add on the 'key'
$c = 0;


if($posts) :
    // For each wash_program post
    foreach($posts as $post):

        setup_postdata($post);

        // Prepare the array
        array_push($arr, array(
            'key' => 'field_777'. $c,           # key used by acf
            'label' => get_field("wp_name"),    # label 
            'name' => 'sub_title_' . $c,
            'type' => 'number'
        ));

        $c++;
    endforeach;
    wp_reset_postdata();
endif;


// Add new fields on 'wash' post type
acf_add_local_field_group(

    array(
        'key' => 'group_1',
        'title' => 'Washes Numbers',
        'fields' => $arr,
        'location' => 
            array (
                array (
                    array (
                        'param' => 'post_type',
                        'operator' => '==',
                        'value' => 'wash',
                    ),
                ),
        ),
));

endif;
?>

And the result was exactly what I wanted

Automatically added Wash Programs to Washes Post Type