I have a small plugin to update the acf fields in a posts. In each post, there are many fields that need to be updated with the received data from the API. In the code below, I first demonstrate from one api I get the code I need, then using foreach I get the data for each post. Now I need to update the fields. I have collected all acf keys into one array and I want to use switch to update the fields. But, I ran into a problem that I cannot get the post id in the plugin. What's the correct way to do this?


add_action('admin_menu', 'cr_api_tools_api');

function cr_api_tools_api() {
    add_menu_page( 'CP API Tools', 'CP API', 'manage_options', 'cr-api-tools-plugin', 'cr_api_tools_init');
    function cr_api_tools_view() {
        wp_register_style('cr-api-tools-view', plugins_url('/view/cr-api-tools-view.css',__FILE__ ), array(), time());
    add_action( 'admin_init','cr_api_tools_view');

function cr_api_tools_init () { ?>

    <div class="container">
        <form method="post" class="cr-api-tools">
            <h1>CP API TOOLS</h1>
            <input type="submit" name="enable" class="enable" value="Enable">

        if( isset( $_POST['enable'] ) ) {
            global $post;
            $postID = $post->ID;

        // JOB API
            $result     = file_get_contents( $url );
            $result_data = json_decode( $result );

            foreach ($result_data as  $job) {

                $ref_code = $job->RefCode;
                $post_title = $job->JobTitle;

                $post_id    = post_exists( $post_title );

                if( !$post_id ){
                    $data = array(
                        'post_type'   => 'post',
                        'post_title'  => $post_title,
                        'post_status' => 'publish',
                        'post_author' => $user_ID,
                    $post_id = wp_insert_post( $data );
            // Job DATA API
                $job_api_url ='api/url' . $ref_code;
                $job_api_result = file_get_contents( $job_api_url );
                $result_api_data = json_decode( $job_api_result );

                $acf_keys = [ 

                if(is_array($acf_keys)) {
                    foreach ($acf_keys as $value) {
                        switch ($value) {
                            case 'location':
                            update_field( $value, $job->Region, $postID );
                            case 'job_intro':
                            update_field( $value, $job->JobTitle, $postID );
                            case 'job_offer':
                            update_field( $value, $job->Description, $postID );





<?php } ?>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.