Support

Account

Home Forums Search Search Results for 'custom fields not saving'

Search Results for 'custom fields not saving'

topic

  • Solving

    Triggering the Advanced Custom Fields (ACF) \'acf/save_post\' Action

    I’ve read the ACF ‘acf/save_post’ documentation here: https://www.advancedcustomfields.com/resources/acf-save_post/, which states this action enables one to add additional functionally before or after saving/updating a post. I want to test when this action is triggered.

    I created a custom post type and a collection of ACF custom fields that are linked to this custom post type. This includes some ACF custom field types that I created using the ACF Starter Kit, and they are used for some of the ACF custom fields. When I edit a custom post and then click the ‘Update’ button in the Gutenberg editor, I expect the ‘acf/save_post’ action to fire, but it does not seem to do so. Perhaps I am missing something. Here is the relevant code from my theme’s ‘function.php’ file.

    function my_acf_save_post($post_id) {
      console_log("Testing...");
    }
    add_action('acf/save_post', 'my_acf_save_post', 20);
    
    function console_log($output, $with_script_tags = true) {
      $js_code = 'console.log(' . json_encode($output, JSON_HEX_TAG) . ')';
    
      if($with_script_tags) {
        $js_code = '<script>' . $js_code . '</script>';
      }
    
      echo $js_code;
    }

    Citation for the ‘console_log’ function: Kim Sia (see: https://stackify.com/how-to-log-to-console-in-php/).

    I have my web browser’s inspector window opened for my custom post type post’s editor. After modifying the post and clicking ‘Update’, nothing displays in the inspector’s console pane. I posted about this in the ACF forum but have received no response.

    Your feedback is appreciated. Thank you.

  • Solved

    Problems with saving values to ACF-Fields when creating a new post

    Hi there,

    I want to update the $_POST[‘acf’]-Array with specific values for some field_keys. I use ACF with another plugin called “Event Organiser” which register the custom-post-type “event”. I have several ACF-Fields

    • SELECT “district” to have a region-filter for the events
    • TEXT “thumbnail_’district’ ” where the url of a thumbnail is stored
    • TEXT “thumbnail_deleted” for the thumbnail when the event will be deleted
    • TEXT “thumbnail_postponed” for the thumbnail when the event will be deleted

    When the user creates or edits an event my function should update the field for the thumbnails referring to the chosen district. Also it should update the fields for deleted and postponed.

    I’ve two custom functions to get the choices of the select field “districts” and to get the field_keys for the thumbnail-fields for the different districts and the fields for deleted and postponed.

    Here my code:

    function update_image_fields( $post_id ){
    	$post_type = get_post_type( $post_id );
    	if (isset ($_POST['acf']['field_5ecf8ef280a84'])){
    		$new_district = strtolower($_POST['acf']['field_5ecf8ef280a84']);
    	} else {
    		$new_district = "bayreuth";
    	}
    
    	$image_urls = array (
    			'bamberg' 		=> wp_get_attachment_image_url(244),
    			'bayreuth' 		=> wp_get_attachment_image_url(244),
    			'coburg'		=> wp_get_attachment_image_url(244),
    			'forchheim'		=> wp_get_attachment_image_url(244),
    			'hof' 			=> wp_get_attachment_image_url(244),
    			'kronach'		=> wp_get_attachment_image_url(244),
    			'kulmbach'		=> wp_get_attachment_image_url(244),
    			'lichtenfels'	=> wp_get_attachment_image_url(244),
    			'wunsiedel' 	=> wp_get_attachment_image_url(244),
    			'postponed' 	=> wp_get_attachment_image_url(476),
    			'deleted' 		=> wp_get_attachment_image_url(481),
    		);
    	
    	$acf_thumbs = get_district_choices ( );
    	array_push ($acf_thumbs, "deleted", "postponed");
    	
    	if ('event' == $post_type){
    		
    		//update all thumbnail_fields
    		
    		$test_meta_key = "_thumbnail_" . $new_district;
    		$test = acf_get_all_field_key ( $test_meta_key, $post_id );
    		
    		
    		foreach ($acf_thumbs as $acf_thumb) {
    			$meta_key = "_thumbnail_" . $acf_thumb;
    			// if there is a new event
    			if (false === $test) {
    				$args = array (
    					'numberposts'	=> 1,
    					'post_type'		=> 'event',
    					'post_status'	=> 'publish',
    					'fields'		=> 'ids',
    				);					
    				$new_post_id = get_posts($args)[0];
    				$field_keys[$acf_thumb] = acf_get_all_field_key ( $meta_key, $post_id = $new_post_id );
    			} 
    			// for an update of an event
    			else {
    				$field_keys[$acf_thumb] = acf_get_all_field_key ( $meta_key, $post_id );
    			}
    		}
    		
    		foreach ($field_keys as $field_key => $field_value) {
    					
    			switch ($field_key) {
    				case "deleted" :
    					$fk_deleted = $field_keys['deleted'];
    					$_POST['acf']["$fk_deleted"] = $image_urls['deleted'];
    					break;
    				case "postponed" :
    					$fk_postponed = $field_keys['postponed'];
    					$_POST['acf']["$fk_postponed"] = $image_urls['postponed'];
    					break;
    				case $new_district :
    					$fk_new_district = $field_keys["$new_district"];
    					$_POST['acf']["$fk_new_district"] = $image_urls["$new_district"];
    					break;
    				default :
    					$fk_others = $field_keys["$field_key"];
    					$_POST['acf']["$fk_others"] = "";
    					break;
    			}
    		}
    						
    	}
    }
    add_action( 'acf/save_post', 'update_image_fields', 5);

    For updating an event, it do what it should. But when I am creating a new event nothing is updating. I think it’s overwritten by any build-in-function or by ACF when WordPress creates a new post. Can you please give me hint what I’m doing incorrect or what I can do otherwise? Is “acf/save_post” the correct action to hook for a new post/ event?

    Thank you and all the best!

  • Helping

    Bulk Action for Updating Bidirectional Relationships

    Hello,
    I have a relationship field with a group and several post types, all of which share this same field. By using the below example, I was able to add bidirectional relations to saving the post.

    https://www.advancedcustomfields.com/resources/bidirectional-relationships/

    However, a large portion of the posts will be imported, and thought the import plugin creates the relation between Post A and Post B, to create the association between Post B and Post A, I would have to go to either and “save” the post.

    To avoid this task, I would like to create a custom bulk action that will use the same ACF example but in a bulk manner.
    Bellow is the skeleton code. Can you please advise if this is possible? All my attempts in doing so have failed. The update_field always returns true, but no update occurs.

    add_filter( 'bulk_actions-edit-people', 'custom_rel_update_bulk_action' );
    
    function custom_rel_update_bulk_action( $bulk_array ) {
    
    	$bulk_array['bulk_update_rels'] = 'Update Relationships';
    	return $bulk_array;
    
    }
    
    add_filter( 'handle_bulk_actions-edit-people', 'custom_rel_update_bulk_action_handler', 10, 3 );
    
    function custom_rel_update_bulk_action_handler( $redirect, $doaction, $object_ids ) {
    
    	// let's remove query args first
    	$redirect = remove_query_arg( array( 'bulk_update_rels_done' ), $redirect );
    
    	// do something for "Make Draft" bulk action
    	if ( $doaction == 'bulk_update_rels' ) {
    
    		foreach ( $object_ids as $post_id ) {
    
                //https://www.advancedcustomfields.com/resources/bidirectional-relationships/
    
    		}
    
    		// do not forget to add query args to URL because we will show notices later
    		$redirect = add_query_arg(
    			'bulk_update_rels_done', // just a parameter for URL (we will use $_GET['bulk_update_rels_done'] )
    			count( $object_ids ), // parameter value - how much posts have been affected
    		$redirect );
    
    	}
    
    	return $redirect;
    
    }
    add_action( 'admin_notices', 'bulk_update_rels_notices' );
    
    function bulk_update_rels_notices() {
    
    	// first of all we have to make a message,
    	// of course it could be just "Posts updated." like this:
    	if ( ! empty( $_REQUEST['bulk_update_rels_done'] ) ) {
    		echo '<div id="message" class="updated notice is-dismissible">
    			<p>Posts updated.</p>
    		</div>';
    	}
    
    }

    Advanced Custom Fields PRO 5.9.1

    Thank you very much

  • Solving

    Saving data to ACFs using AJAX POST

    Hello,

    I created a front-end form that allows a user to enter data to create a new flight log entry. I’m using AJAX to create the post. While the post is created and shows the title and content, I can’t get the data to save to the Advanced Custom Fields. I’ve registered the field groups and I’m using the field keys with update_field(). I’m not certain what I’m overlooking. Any help would be greatly appreciated.

    createLogEntry(e){
    var departure_field = $(“.new-flight-departure”).val();
    var arrival_field = $(“.new-flight-arrival”).val();
    var title = (date + ‘ ‘ + departure_field + ‘ ‘ + arrival_field);
    var content = $(“.new-flight-text”).val();

    $.ajax({
    beforeSend: (xhr) => {
    xhr.setRequestHeader(‘X-WP-NONCE’, flightData.nonce);
    },
    url: flightData.root_url + ‘/wp-json/wp/v2/flight/’,
    type: ‘POST’,
    data: {
    action: ‘submit_log_entry’,
    title: title,
    departure_field: departure_field, //Advanced Custom Field
    arrival_field: arrival_field, //Advanced Custom Field
    content: content
    },
    success: (response) => {
    console.log(“Congrats”);
    console.log(response);
    alert(‘Post has been saved.’);
    },
    error: (response) => {
    console.log(“Sorry”);
    console.log(response);
    }
    });
    }

    function submit_log_entry() {

    $title = $_POST[‘title’];
    $content = $_POST[‘content’];
    $departure = $_POST[‘departure_field’];
    $arrival = $_POST[‘arrival-field’];

    $post_data = array(
    ‘post_title’ => $title,
    ‘post_content’ => $content,
    ‘post_type’ => ‘post’,
    ‘post_status’ => ‘publish’
    );

    $post_id = wp_insert_post($post_data);

    //Update departure field
    $field_key = ‘field_5ecb28b30812a’;
    update_field($field_key, $departure ,$post_id);

    //Update arrival field
    $field_key = ‘field_5ecc33eb92cf4’;
    update_field($field_key, $arrival ,$post_id);

    die();
    }

    add_action( ‘wp_ajax_nopriv_submit_log_entry’, ‘submit_log_entry’ );
    add_action( ‘wp_ajax_submit_log_entry’,’submit_log_entry’ );

  • Unread

    Trouble to use update_sub_field() for saving specific user ID?

    I have been trying to Googling around and I can’t really find any answers for this.

    I am creating a simple LMS project. The idea is that there will be many users. Each user has their own user ID which is generated from the WP.

    Each user will have one or many courses displayed on the website, and on the website, the user can click on the checkboxes to mark which of the course lecture they have finished.

    The problem is that right now the checkboxes are “global state”. That means every user can mark the checkbox and it’s not private anymore, or rather marked specifically for the user who attended the course lecture.

    I have managed to create my own WP Customized REST API, but I have a problem with how to use the update_sub_field() in context to update for a specific user ID.

    I am using the repeater Field type with checkboxes.

    Here is my code:

    
    add_action('rest_api_init', 's68_course_api');
    
    function s68_course_api() {
        register_rest_route('s68/v1', 'course/(?P<id>\d+)', [
          [
            'methods' => WP_REST_Server::EDITABLE,
            'callback' => 's68_update_course'
          ]
        ]);
    }
    
    function s68_update_course($data) {
          $subfield_whitelist = ['academy_course_progress_button'];
        $post_id = sanitize_text_field( $data['id' ] );
    
        if( $data['course_content'] ) {
            $row_index = intval( $data['course_content']['row_index'] );
            $sub_field = sanitize_text_field( $data['course_content']['sub_field'] );
            $new_value = $data['course_content']['value'];
    
            // If intval() returned 0, then $data['course_content']['row_index'] was not a number.
            // It's alright to check this way because ACF row indexes start at 1 instead of 0 - so 0 is
            // never a valid row number.
            if( $row_index === 0 ) {
                return [
                    'success' => false,
                    'message' => 'Invalid row number'
                ];
            }
    
            // Don't let malicious users change subfields they're not allowed to
            if( !in_array( $sub_field, $subfield_whitelist ) ) {
                return [
                    'success' => false,
                    'message' => 'Invalid sub field'
                ];
            }
    
            $success = update_sub_field(
              [ 'academy_course_content', $row_index, $sub_field ],
              $new_value,
              $post_id,
            );
    
            update_user_meta('user_' . 1, '', $success);
    
            return [
                'success' => $success
            ];
        }
    
        return [
            'success' => false,
            'message' => 'Unknown update request'
        ];
    }
    

    I am not sure what I am missing here.

    How do I achieve this?

    Much appreciate if someone could please help me out

  • Solved

    Migrate from Custom Field Suite

    I’m trying to migrate some custom WYSIWYG fields from the Custom Field Suite plugin into ACF. I’ve generated some new WYSIWYG ACF fields with the same name as the CFS fields.

    All of information seems to appear in both CFS and ACF fields ok, but when I view the ACF content on the front of the site, the content is not rendered with any html, and the shortcodes don’t work.

    I’ve managed to get the shortcodes to work using
    echo do_shortcode($extra_product);
    …but the text content is just displaying as unstyled content (no html).

    If I open and resave any of the pages, then the problem is solved, but I really don’t want to go through hundreds of pages resaving them – does anyone know of a way to somehow refresh this field content, and resave multiple pages all in one go?

    Any ideas much appreciated.
    Many thanks

  • Solved

    Weird Behavior with Taxonomy field

    Can someone explain to me what might be happening? Or maybe I’m just misunderstanding the documentation for the Taxonomy field. I’m seeing two issues, one with the “Save Terms” option and the other with “Load Terms”. For context, I have a repeater field with one of the subfields as a taxonomy field set to use the default post tags taxonomy.

    When I set the “Save Terms” to true with the intention to make it so whatever tag they set here is also assigned to the post in the sidebar, making it dummy-proof for my editors in case they forget to also assign the tag to the post. But doing so while editing a post wipes out all other tags upon saving and makes it so that the tag assigned in this ACF subfield is the _only_ tag assigned to the post. Obviously this is not what I want, and I just set it to false and hope that my editors remember to assign the same tag they selected in ACF to the actual post.

    As an alternative to the first issue, my second issue is when I set “Load Terms” to true with the idea that _only_ the tags assigned to the post will appear in the drop down, so it forces the editors to assign it first and then use the ACF. However, all tags appear in the drop-down, regardless if any tags are assigned to the post. Even worse, if I have two tags assigned to my post and I use field to point to the second one, after saving, it forcefully points to the first tag. Once again, I set this ACF configuration to false so it at least behaves normally but now I can’t really dummy-proof it for my editors in any capacity.

    Is this the intended behavior of “Save Terms” and “Load Terms” or is something going on? Thanks in advance!

  • Unread

    Custom Fields Not Displaying

    The issue I am having is straightforward an, hopefully, I am just overlooking something here. I have a custom field called, “XYZ”. The location rules are set to show the custom field grouping if the page template is equal to “ABC template” or “DEF template” or GHI template” or “TESTPAGE_A” page. Note: the last criteria here is a page, not a page template.

    When I go to the edit screen for “TESTPAGE_A”, I can see the grouping for the custom field, “XYZ” an can edit, make changes and save. However, when I open the page after saving changes (using Incognito mode in Chrome to avoid caching) the custom field does not display. NOTE: The custom field will display if I go back to edit the TESTPAGE_A page, select one of the aforementioned page templates (ABC, DEF, GHI) for the page and save it.

    I am using version 5.8.13 of ACF, PHP 7.3

  • Helping

    Update_field Does not Affect WP_Query Until Post is Saved in Backend

    Hello,

    I have two content blocks (A and B) on my front page which I want to fill with post teasers. Each block has 6 positions, A1-A6 and B1-B6.

    I created custom select field containing options with the values A1-B6 and an option with „X0 – not on front page“ which is the standard value.

    Then I created two WP_Queries, one for each Block:

    
    $args_a = array(
        'numberposts' => 6,
        'post_type' => 'post',
        'meta_key' => 'position',
        'meta_value' => '^A', 
        'meta_compare' => 'REGEXP',
        'order_by' => 'meta_key',
        'order' => 'ASC'
    );
    
    $args_b = array(
        'numberposts' => 6,
        'post_type' => 'post',
        'meta_key' => 'position',
        'meta_value' => '^B',
        'meta_compare' => 'REGEXP',
        'order_by' => 'meta_key',
        'order' => 'ASC'
    );

    And put them in two different loops, like it’s shown in the documentation. So far, everything works fine, when I change the position from A to B, the teaser appears in the other box.

    Then I decided to try if the position changes could be automated somehow. I created another custom select field with the same options and named it „position_new“ and one datetime field named it „switchtime“. The switchtime is in the future and when it is reached, the field position should be updated with the value from position_new and after that the values of the fields switchtime and position_new have to be deleted.

    First I created another WP_Query which gets all posts that are scheduled:

    // Get Scheduled Posts
    $scheduled = array(
        'numberposts' => -1,
        'post_type' => 'post',
        'order' => 'ASC',
        'order_by' => 'meta_value',
        'meta_key' => 'switchtime',
        'meta_type' => 'DATETIME'
    );

    Here is the first problem, there are all posts inside the loop, including the posts, where the field switchtime is empty. Deleting meta_key and meta_type from the args does not have an effect.

    And then I wrote inside the loop (the first part of the if statement is there to get rid of empty values):

            if ( ( get_field("switchtime") != "" ) && ( current_time('Y-m-d H:i:s') > get_field("switchtime") ) ) {
                $postid = get_the_ID();
                $newpos = get_field("position_new");
                update_field('position', $newpos, $postid);
                delete_field('switchtime');
                delete_field('position_new');
               // wp_insert_post( array('ID' => $postid) );
            }

    At first sight, it seems to work, the field position is updated and the other two fields are deleted on switchtime, but my teaser which I moved from A to B still appears in content block A. I displayed the field value in the frontend and it clearly says B, but the WP_Query from A fetches it anyway. I have to edit the post in the backend simply by saving it without changing anything and after that the teaser appears in B.

    Therefore I wondered if that last line in the if statement which should save the post would solve the problem, but no.

    Do you know what to do?

    Cheers,
    Pierre

reply

  • To change the permalink of a Custom Post Type (CPT) in WordPress to act as a child of another CPT, you’ll need to customize the rewrite rules and manage the hierarchy through hooks in your theme’s functions.php file or a custom plugin. Here’s a step-by-step guide:

    Example Setup
    – **Parent CPT**: parent_cpt
    – **Child CPT**: child_cpt
    – Desired permalink structure: /parent_cpt/child_cpt/

    1. Register Custom Post Types
    First, make sure both your parent and child CPTs are registered. The key is to set up the rewrite rule correctly for the child CPT.

    Parent CPT Registration
    `php
    function register_parent_cpt() {
    $labels = array(
    ‘name’ => ‘Parent CPT’,
    ‘singular_name’ => ‘Parent CPT’,
    );
    $args = array(
    ‘labels’ => $labels,
    ‘public’ => true,
    ‘rewrite’ => array( ‘slug’ => ‘parent_cpt’ ),
    );
    register_post_type( ‘parent_cpt’, $args );
    }
    add_action( ‘init’, ‘register_parent_cpt’ );
    `

    Child CPT Registration (with rewrite)
    `php
    function register_child_cpt() {
    $labels = array(
    ‘name’ => ‘Child CPT’,
    ‘singular_name’ => ‘Child CPT’,
    );
    $args = array(
    ‘labels’ => $labels,
    ‘public’ => true,
    ‘rewrite’ => array( ‘slug’ => ‘parent_cpt/%parent_cpt%/child_cpt’, ‘with_front’ => false ),
    ‘has_archive’ => true,
    );
    register_post_type( ‘child_cpt’, $args );
    }
    add_action( ‘init’, ‘register_child_cpt’ );
    `

    2. Add Rewrite Logic to Handle Permalinks
    We need to intercept and replace %parent_cpt% with the actual parent_cpt slug. Here’s how to do that.

    Handle Permalink Replacement
    `php
    function child_cpt_permalink($permalink, $post) {
    if ($post->post_type !== ‘child_cpt’) {
    return $permalink;
    }

    // Get the parent CPT ID
    $parent_id = get_post_meta($post->ID, ‘parent_cpt_id’, true);

    if ($parent_id) {
    $parent_post = get_post($parent_id);
    $parent_slug = $parent_post->post_name;
    return str_replace(‘%parent_cpt%’, $parent_slug, $permalink);
    }

    return $permalink;
    }
    add_filter(‘post_type_link’, ‘child_cpt_permalink’, 10, 2);
    `

    3. Add Rewrite Rules
    This rule tells WordPress how to parse URLs in the desired format.

    `php
    function add_custom_rewrite_rules() {
    add_rewrite_rule(
    ‘^parent_cpt/([^/]+)/child_cpt/([^/]+)/?$’,
    ‘index.php?child_cpt=$matches[2]’,
    ‘top’
    );
    }
    add_action(‘init’, ‘add_custom_rewrite_rules’);
    `

    4. Save Parent CPT as Post Meta
    You need a way to associate the child post with its parent. You can do this via a meta box in the admin area or using a custom relationship field.

    Here’s an example of saving a parent_cpt_id as a post meta field:

    `php
    function save_child_cpt_meta($post_id, $post, $update) {
    if ($post->post_type != ‘child_cpt’) {
    return;
    }

    if (isset($_POST[‘parent_cpt_id’])) {
    update_post_meta($post_id, ‘parent_cpt_id’, $_POST[‘parent_cpt_id’]);
    }
    }
    add_action(‘save_post’, ‘save_child_cpt_meta’, 10, 3);
    `

    5. Flush Rewrite Rules
    Whenever you add new rewrite rules, you need to flush them. You can do this temporarily by visiting the **Settings > Permalinks** page, or by adding this line temporarily to your code:

    `php
    flush_rewrite_rules();
    `

    Final Notes
    – The parent-child relationship is stored using post meta (parent_cpt_id), but you can adjust this based on how you’re managing relationships.
    – If you’re using a plugin like Advanced Custom Fields (ACF) for relationships, the code can be modified accordingly.

    This setup allows the child CPT to inherit the parent CPT’s slug in the URL structure.

  • Are you talking about a “Field Group” or a “Group Field” that is named “custom_fields”?

    A field will not have a value unless you update the user. Are you expecting to search on the “default value” of the field without saving the value? This cannot be done. A default value does not automatically add values to usermeta, you must update each user before there is a value to search on in the DB.

  • You cannot rename during the saving of the post. ACF uses the WP native upload. Files and images are uploaded and named when they are added.

    I do not have any examples of doing what you want but here is an outline of what would need to be done in ACF to rename the file on upload in ACF

    • First you would need to make sure that the other fields are completed before an image can be added, and potentially that the fields cannot be altered.
    • You will need to add custom JS and use the ACF JS API using an undocumented hook in the API “prepare_for_ajax” data = acf.applyFilters('prepare_for_ajax', data);
    • Using a filter you would have to get the values of the other fields and add them to this ajax data.
    • This data will then be available in $_POST during the file upload process and then you can use these values in the processed described in some of those posts.

    I honestly don’t know how you would rename the files in WP each time the other fields are changed and the post is updated. I have looked and I can’t find much in the way of examples of doing this. If I had to do this I would probably look at the code in other plugins that make it possible to rename a file after it is uploaded and see how they do it and adapt that for use in an acf/save_post action.

    This looks somewhat promising https://stackoverflow.com/questions/64990515/wordpress-rename-attachment-file-with-working-thumbnails#answer-65065944

  • After looking into this further, you are not going to be able to use acf_form(). This issue is that this is a user registration form. There is no value get_current_user_id() under this condition. Also, ACF will not know that a new user is being created and will not be able to get the correct user id to save the fields for.

    What you will have to do instead is create a select field that you populate on your own with the select values. Since this you are saving a value in some type of relationship field the values need to be the ID of the related post.

    Then you will need to create an action for the WP user_register hook. This will provide the user ID just created. Then using this ID you use update_field(), using the field key and the "user_{$user_id}" post ID.

  • This is a user forum and ACF developers do not answer questions here.

    Someone can try to help you but you’ll need to provide more information. With the information you’ve provided I can give you some general reasons that this happens.

    If the page you are editing has many fields it could be an issue with the php setting “max_input_vars”

    Another possible issue is that another field with the same name is interfering with saving the value.

    If you want to contact the developers directly you need use the contact form or submit a ticket through your account.

    You’re video does not really help me. How many fields are you dealing with? How many rows have you added to repeaters and flexible content fields? How many other fields are on the page?

  • Unfortunately, no.

    And by adding the load_value and save_post hooks you’ve slowed it down even more because ACF will still save the values to the database and load those values from the database. Using these hooks does not override the default ACF action.

    It might be possible to do this if you use acf/save_post with a priority of < 10. This would run before ACF has saved the values. You could then loop over the repeater in $_POST[‘acf’] and create your JSON and then delete the repeater input from $_POST[‘acf’], deleting the input will prevent ACF from saving the values.

    It’s probably too late to make a changes but 250 rows with 12 fields in each row tells me that this should have been done with a custom post type instead of a repeater.

  • You cannot use exported JSON files for this. To add local JSON to a plugin.

    1) add the acf-json folder to your theme
    2) create field groups
    3) download the json files for you field groups from your theme folder
    4) upload the json files to the acf-json folder in your plugin
    5) Add the path to your plugin json files with acf/settings/load_json

    Note, you cannot use acf/settings/save_json the way you are using it. This will cause all field groups on the site to be saved in your plugin folder. In order to do this you must check the field group field group to make sure that it is one of the field groups used by your plugin before adding the save location hook. This can be done using the acf/update_field_group filter to check the field group and if it is one of yours then add the acf/settings/save_json filter.

    If you do not want the field groups to by sync-able then you add then you can set them as private, that is discussed here https://www.advancedcustomfields.com/resources/synchronized-json/. This must be done manually because when saving a field group in the admin, if you are using acf/settings/save_json hook then the private setting will be removed when the groups is saved in the admin. It is possible to use the acf/prepare_field_group_for_export hook to create a filter that can set the private value of the field group dynamically based on something else. I have done this in the past by defining a custom constant on my dev sites so that I can check this and set the private value based on this constant being defined.

  • The problem was solved after examining my code again. I’ve worked with a custom table in the past. Due to difficulties I had retrieved the fields with post_name (‘field_5f4005dc755c5’) and not with the field name (‘deathdate’). I have now re-saved the posts. After saving, I could now retrieve the field values with the field name again, and now the custom fields appear in the taxonomy output! Although I don’t know why it was related to the URL parameter, everything works now. Please excuse the confusion 😉

  • You are correct. You cannot limit where individual fields are shown, only entire field groups.

    It is possible to limit where a specific field is used by using an acf/prepare_field filter to remove fields that should not be shown. You would need to use the “field key” variant of the filter and you would need to determine for yourself when the field should be shown or not.

    In all likely hood it would mean saving the post to become effective. For example, if a location rule is based on a taxonomy term then the post would need to be saved with that taxonomy term before you would be able to test for that taxonomy in your filter function. The same would apply to any setting that is generally controlled by WP.

    This could be overcome by moving all WP settings into custom fields, you could then use conditional logic based on these new custom fields instead of the above filter. However, this would mean creating an acf/save_post action to convert all of the new controls into WP setting when the post is saved. This may also not be possible in all cases.

  • Using divi, I have no idea how you would do this. More than likely you’d have to build a custom shortcode for every value you want to display, but that’s just a guess, I do not use divi, but I do know that with most of these page builders it is the only practical way to do something like this.

    How long it would take you would depend on the number of statistics you want to do this for.

    The first thing you would need it to create an acf/save_post action that will put all of the statistics every time a post is added or updated and store all statistics for all posts in a single array in the options table. This would have to be done to prevent the entire thing from timing out (crashing) the site. Depending on the number of values you are saving this could take 1 to several hours.

    The next thing you’d need to do is build a custom shortcode for each statistic. There are plenty of tutorials available on the web for doing this as well. The first one might take you a couple of hours to build, after that you could likely copy and past the first one and then change the name and modify the array indexes used to do the calculations and then test. You’re probably looking at an average an hour per statistic, maybe a little less once you get started depending on how many there are. You might also be able to use a function to do the actual calculation based on arguments and reduce the time taken to build new statistic shortcodes and the amount of code needed. This is what I’d probably do, so you might be looking at 2 hours to build the first one + the function and then 30 minutes or so for each additional shortcode.

  • Actually, no.

    This function like all others requires that the field key reference exists in the database for the current $post_id. It uses a combination of the post ID and field name to look up the field key reference.

    It all ends with the function acf_get_metadata(). In this function you will find

    
    $meta = get_metadata( $type, $id, "{$prefix}{$name}", false );
    

    $prefix in this case in an underscore (_), so it is trying to get the meta value of the meta key (your field name) prefixed with “_”. This is where the field key reference is stored. This meta value will only be set if the post already has a value for the field.

    As stated in the update_field() document

    Updating via field key

    This example shows how to achieve the same result as above using the field’s key instead of its name. The field’s key should be used when saving a new value to a post (when no value exists). This helps ACF create the correct ‘reference’ between the value and the field’s settings.

    The reason this is it because field names can be duplicated. All ACF operations actually need the field key to work. Field keys are unique. When you save a new post in the admin every input name is the field key, not the field name. ACF really has no way of knowing what field you are referencing by a field name and the field name has no meaning without the reference, which is why a field key reference is inserted into the DB for every field value that is saved for every post.

  • You are going to need to contact the developers on this. This is coded into the save post function in ACF. It only does validation if the post status is publish and I cannot find any way to alter this. They would need to add some type of filter or something allow changing this.

    If I recall this was added because most people wanted to allow saving drafts without validation, but that was a long time ago.

  • Hey,

    I know, this is from 2016.
    But today in 2022 I have the same problem.
    I have the newest ACF PRO Version.
    I have a custom post type for a user role.
    The user role can only save the CPT post as “pending”.
    The admin has to publish the CPT post.

    My problem is similar. The user with the specific user role can skip the required fields, because they are not validated on saving as “pending”. So the admin needs to contact the user to fill the required fields.

    Is there today a current solution?

    Best regards,
    Alex

  • There are a couple of options.

    One way to do this is to create an acf/save_post action with a priority of < 10. In this action you can compare the old value in the field get_field('file_field') with the new value submitted $_POST['acf']['field_KEY'] and if they are different then use wp_delete_attachment() to delete the old file. This will only work after a post has been saved. So if someone adds a file and then changes their mind before saving then the file will not be deleted.

    A variation of the above (still using an acf/save_post action) would be get all of the attachments for the post being saved https://stackoverflow.com/questions/42917812/how-to-get-all-attachments-for-a-wordpress-post. All files uploaded in an ACF field should be attached to the post. Then look in every field that is for an attachment (file, image, gallery) and get a list of the ones actually being used and delete the ones that are not. The flaw in this method is that you will not be able to detect files or images that are added in the WP editor or a WYSIWYG field and you’d end up deleting these.

    Another way that this could be done is to add custom JavaScript to ACF and add an action to the remove button that fires an AJAX request to delete the file. This would be the best solution, but also the hardest to accomplish.

    There is another flaw with every method, you will not know if the same file has been used on another post. Deleting the file if it is used somewhere else will cause issues with wherever else it is used.

  • Experiencing a similar issue with some ACF custom fields not saving. There were suggestions online to increase the max_vars to a larger size to allow the custom fields to save, but even after I increased these max vars to 50,000 as a test, and updated docker, the custom fields were still not saving. I also tried to rename the custom fields to make sure there are no duplicates or possible name conflicts. Are there any other methods I should try that may help solve this issue?

    The only way I can think of now is to separate some custom fields into separate sections/pages but overtime this would lead to a bit of clutter since they would have to keep getting divided… Thank you in advance for any advice!

Viewing 25 results - 51 through 75 (of 244 total)