Support

Account

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

Search Results for 'custom fields not saving'

topic

  • Unread

    Required ACF field not preventing post Scheduling (+errant Publish)

    We’re on WPEngine @ WP 6.1.1 using Advanced Custom Fields PRO 5.12.2

    We have a “Required Field” called Section that, in certain scenarios, is not being required before publishing. In fact, under a certain flow when the intention is to Schedule… the post is becoming Published immediately with at least 2 munged fields.

    That “worst case” scenario flow seems to be:

    1. When the date is moved forward (field missing)
    2. Then the autosave functionality kicks in (triggering a Draft)
    3. Then the user clicks Schedule, then Schedule again (triggering an immediate Publish)
    4. The Add New Post UI seems to indicate the Scheduling has been prevented, but it hasn’t

    We’ve captured a video of the above:

    “Demonstrate Required ACF Field Failure as related to Scheduled Posts (+Errant Publish Behavior)”

    https://www.loom.com/share/428cb6b5bf9b48938390b89fc2677078

    If anyone has any ideas on direction to take from here, we’d be grateful to hear them before escalating to a ticket.

    Thank you,
    Michael

    PS The “best case” scenario where it fails, on rare occasions, is using a Publish + Publish flow. However, reproducing that has proved difficult as it generally “works as expected”… until it doesn’t. Because the UI errors / prompts and Post State are very consistent, and the missing field seems like something an Author would most likely correct during flow prior to an errant publish… we’re considering it “low risk” at this moment. (versus the above “worst case” scenario where the behavior and result differs greatly from the expectation)

    —— VIDEO SCRIPT BEGIN

    – First, we search for our test tag in All Posts
    – We open a fresh Add New Post tab
    – We add our tagged Post Title
    – We fill in 2 fields required for our tests
    – First, a Hero Image
    – Then Chapter which we set to “BU TEST”
    – Here we’re skipping over the required Section field, leaving it blank
    – We change the Publish Date to add 7 days
    – We add TEXT to the Block to trigger a Post State Update (without clicking Save in Progress)
    – We search our test tag again to confirm Post Status
    – We can see here that the Post has been saved as Draft
    – It has a Section set to Culture when none was selected
    – It has a Chapter set to National when “BU TEST” was selected
    – We move back to the Add New Post tab and click Schedule, pause for 5 seconds, then click the final Schedule Button
    – We do receive a required field notice
    – Before we do anything else, we add TEXT to the Block to trigger a Post State Update
    – We search our test tag again to confirm Post Status
    – We see despite scheduling this 7 days out…
    1. The Post has flipped immediately to Published
    2. The Post has Published with the incorrect Section
    3. The Post has Published with the incorrect Chapter
    – We go back and we hide the schedule menu, then scroll down we can see the more informative ACF Field Error Message for the required Section field, but it obviously hasn’t prevented saving as draft or posting of the content which is now Published despite the intention to Schedule

    —— VIDEO SCRIPT END

    —— ACF FIELD JSON BEGIN

    {
        "key": "group_REDACTED_ID",
        "title": "Article Information",
        "fields": [
            {
                "key": "field_REDACTED_ID",
                "label": "Section",
                "name": "section",
                "type": "taxonomy",
                "instructions": "You may only select one section or subsection for a post.",
                "required": 1,
                "conditional_logic": 0,
                "wrapper": {
                    "width": "",
                    "class": "",
                    "id": ""
                },
                "taxonomy": "category",
                "field_type": "select",
                "allow_null": 0,
                "add_term": 0,
                "save_terms": 1,
                "load_terms": 1,
                "return_format": "id",
                "multiple": 0
            }
        ]
    }

    —— ACF FIELD JSON END

  • Solved

    This block has encountered an error and cannot be previewed.

    Hi,

    we build a new site for a client with ACF and Gutenberg. There is one block that throws an error and I don’t know what the hell is going on.

    The console throws another error 2 times:

    
    react-dom.min.js?ver=17.0.1:9 SyntaxError: Expected property name or '}' in JSON at position 2
        at JSON.parse (<anonymous>)
        at q (acf-pro-blocks.min.js?ver=6.0.2:1:23770)
        at Array.map (<anonymous>)
        at M (acf-pro-blocks.min.js?ver=6.0.2:1:22774)
        at acf-pro-blocks.min.js?ver=6.0.2:1:23009
        at Array.forEach (<anonymous>)
        at M (acf-pro-blocks.min.js?ver=6.0.2:1:22927)
        at acf-pro-blocks.min.js?ver=6.0.2:1:23009
        at Array.forEach (<anonymous>)
        at M (acf-pro-blocks.min.js?ver=6.0.2:1:22927)
    

    I can add the block and configure it using the ACF fields, but after saving and reloading the page, the block throws this generic Gutenberg error (see title) and no ACF fields are loaded.

    block.json (the same structure for every block):

    
    {
        "name": "referenzen",
        "title": "Referenzen",
        "keywords": ["referenzen"],
        "style": {
            "handle": "referenzen-style",
            "dependencies": []
        },
        "icon": "admin-generic",
        "category": "_",
        "acf": {
            "mode": "preview",
            "renderTemplate": "render.php"
        },
        "align": "full",
        "supports": {
            "anchor": true
        }
    }
    

    render.php:

    
    <?php
    /**
     * Block Template.
     *
     * @param   array  $block The block settings and attributes.
     * @param   string $content The block inner HTML (empty).
     * @param   bool   $is_preview True during backend preview render.
     * @param   int    $post_id The post ID the block is rendering content against. This is either the post ID currently being displayed inside a query loop, or the post ID of the post hosting this block.
     * @param   array  $context The context provided to the block by the post or it's parent block.
     */
    
    require_once( get_template_directory() . '/modules/h2/h2.php' );
    require_once( get_template_directory() . '/modules/button/button.php' );
    
    // Support custom "anchor" value.
    $anchor = '';
    if ( ! empty( $block['anchor'] ) ) {
        $anchor = 'id="' . esc_attr( $block['anchor'] ) . '"';
    }
    
    // Create class attribute allowing for custom "className" values.
    $class_name = 'acf_block acf_referenzen';
    if ( ! empty( $block['className'] ) ) {
        $class_name .= ' ' . $block['className'];
    }
    
    // Load values and assign defaults.
    $subhead    = get_field( 'subhead' );
    $headline   = get_field( 'headline' );
    $text       = get_field( 'text' );
    $referenzen = get_field( 'referenzen' ) ?: get_posts( array(
        'post_type' => 'referenzen',
        'numberposts' => -1
    ) );
    $button = get_field( 'button' );
    
    wp_enqueue_style( 'referenzen-style' );
    wp_enqueue_script( 'alpine' );
    ?>
    
    <section
        <?= $anchor ?>
        class="<?= esc_attr( $class_name ) ?>"
    >
        <div class="container">
            <?= art_m_h2( $headline, $subhead ) ?>
    
            <div class="wysiwyg">
                <?= $text ?>
            </div>
    
            <?php if ( $referenzen ) : ?>
            <div class="referenzen">
                <?php foreach ( $referenzen as $item ) : ?>
                <a
                    class="item"
                    href="<?= get_the_permalink( $item ) ?>"
                    x-data="{ show: false }"
                    x-intersect:enter="show = true"
                    :class="show ? 'show' : ''"
                >
                    <div class="image">
                        <?= get_the_post_thumbnail( $item, 'full' ) ?>
                    </div>
    
                    <div class="content">
                        <div class="meta"><?= get_field( 'meta', $item ) ?></div>
                        <h3><?= get_the_title( $item ) ?></h3>
                    </div>
                </a>
                <?php endforeach; ?>
            </div>
            <?php endif; ?>
    
            <?= art_m_button( $button['link'], $button['text'] ) ?>
        </div>
    </section>
    

    The block in Gutenberg code view:

    
    <!-- wp:acf/referenzen {"name":"acf/referenzen","data":{"subhead":"Some subhead","_subhead":"field_6351502671f65","headline":"Some headline","_headline":"field_6351502671fac","text":"Some text","_text":"field_6351539802287","referenzen":["121","127","128","129"],"_referenzen":"field_635150267200c","button_text":"Referenzen in meiner Nähe","_button_text":"field_63515026d5255","button_link":"#","_button_link":"field_63515026d5294","button":"","_button":"field_63515026720a8"},"mode":"preview"} /-->
    

    Any suggestions?

  • Helping

    Saving data in a repeater or in a specific custom post type?

    I have a “provider” custom post. I would like to save the invoices received from each provider (not the actual invoice file, just a few data : invoice number, date, amount.)
    I have 2 choices :
    – Either I create a repeater in the provider custom post type.
    – Either I create an “invoice” custom post type with these few custom fields + a relationship field to assign each of them to the corresponding provider.

    I tend to prefer the first option because it seems lighter (i don’t really want to create a custom post type specifically to save a few fields) but I also read somewhere that ACF repeaters are not made to have hundreds of rows (which some providers will have eventually after a few years).
    Which solution makes more sense from a database/performance point of view?

    Thank you !

  • Solving

    ACF Pro 6 Block IDs as Attribute Not Working

    I have an “Anchors” block that allowed the user to create hyperlinks to other Blocks on the same page. This was possible, pre-6.0, because each block had an ‘id’ attribute which I dynamically populated into a Select field. In 6.0, the ID was removed.

    I’ve followed the instructions in the ACF 6 announcement under [Block IDs](https://www.advancedcustomfields.com/resources/whats-new-with-acf-blocks-in-acf-6/#block-id). Problem is, the “anchor” attribute value is deleted from each block before the acf/pre_save_block action is completed.

    Here’s my code, per the blog post’s instructions:

    
    function mypre_add_anchor_to_blocks( $attributes ) {
    
        if( !isset($attributes['anchor']) || empty($attributes['anchor']) ) {
            $attributes['anchor'] = 'block-' . uniqid();
        }
        return $attributes;
    }
    add_filter('acf/pre_save_block', 'mypre_add_anchor_to_blocks');
    

    I’ve also tried changing the priority value of add_filter from 1-100 but it doesn’t seem to matter. I presume it’s because the function acf_get_block_type_default_attributes is overwriting the attributes, which deletes the anchor value altogether. I think this because, when I pull the anchor values from the blocks outside of a loop and long after saving, they’re visible. But whenever I update my post, the anchor value changes, implying it doesn’t exist or is empty.

    I tried finding a way to hook into the acf_get_block_type_default_attributes function but couldn’t figure it out. The closest filter I could find is $block = apply_filters( 'acf/register_block_type_args', $block ); in the file /pro/blocks.php,
    but and there doesn’t seem to be a way to add an anchor value to the attributes.

    As a (hopefully) temporary solution, I am giving all custom ACF Blocks an “Anchor ID” field which will be used to populate the Anchors’ Select field. However, this requires the client to populate those ID fields, which is an added detail they don’t particularly enjoy.

    That being said, is it possible to add anchor to a block’s default attributes? If not, is there a way to prevent the anchor attribute from being deleted before the acf/pre_save_block action? If neither of those is possible, is this a problem the ACF team could remedy, possibly by just putting a filter allowing custom attributes into the acf_get_block_type_default_attributes function?

    Thanks in advance; let me know if I’m unclear about anything I’ve written.

  • Unread

    Impossible to display my fields in Woocommerce tab

    I explain my problem.
    I have imported a list of custom fields (via JSON import tool) from a site to my current site (250) that are related to WooCommerce products. What I would like to do is to display the label and value of each of the filled fields in a characteristic table below each product.

    To do this, I used the get_field_objects function with the product id as parameter. I then looped to display the fields normally. Problem : nothing is displayed. On the other hand, if I go back to the product and update it without touching anything, bam, as if by magic, everything is displayed well…. Except that my client is not going to have fun saving 80,000 products by hand…

    Here is the code:

    add_filter( ‘woocommerce_product_tabs’, ‘wpb_new_product_tab’ );
    function wpb_new_product_tab( $tabs ) {
        // Add the new tab
        $tabs[‘test_tab’] = array(
            ‘title’       => __( ‘Caractéristiques’, ‘text-domain’ ),
            ‘priority’    => 1,
            ‘callback’    => ‘wpb_new_product_tab_content’
        );
        return $tabs;
    }
    function wpb_new_product_tab_content() {
      global $product;
      $id = $product->get_id();
      $fields = get_field_objects($id);
        if( !empty($fields) ): ?>
          <table class=“table”>
            <tbody>
              <?php foreach( $fields as $field ): ?>
                  <?php if( $field[‘value’] && $field[‘label’]!=“Pictogrammes” ): ?>
                    <tr>
                      <th scope=“col”><?php echo $field[‘label’]; ?></th>
                      <th scope=“col”><?php echo $field[‘value’]; ?></th>
                    </tr>
                  <?php endif; ?>
              <?php endforeach; ?>
            </tbody>
          </table>
        <?php else : ?>
          Pas de données actuellement...
        <?php endif;
    }
  • Solving

    WP User frontend pro not saving ACF values to Database

    Hello,

    I am using WP User frontend pro plugin to accept guest posts from the frontend form that contains several custom fields. Everything works fine after submitting the frontend form and even when we check the post from wp-admin, it shows all the correct custom field values correctly.

    But on the frontend guest post, it’s not showing custom field values until I resave the submitted guest post from the backend. When talked to ACF support, they said that the wp user frontend pro plugin populates the custom fields but does not save them to the database. They also said to write a custom function that triggers after WP user frontend submits/updates post from frontend and run save_post() ACF function.

    After discussing with the WP User frontend team, they gave the following functions triggers after post insert/update and can be used for custom actions –

    – wpuf_add_post_after_insert
    – wpuf_add_post_after_update

    Ref- https://wedevs.com/docs/wp-user-frontend-pro/developer-docs/wpuf_add_post_after_insert/

    So I wrote the following code –

    
    function save_to_database($post_id,$form_id){
    if($form_id == "195"){
    do_action( 'acf/save_post', $post_id );
    }
    }
    add_action( 'wpuf_add_post_after_insert', 'save_to_database' , 10 ,2 );
    add_action( 'wpuf_edit_post_after_update', 'save_to_database' , 10 , 2 );
    

    But this dint work. Can anyone help me correct the above code? Or provide me a better solution?

  • Helping

    ACF not creating underscore fields in the database for translated pages

    Hello!

    I have a peculiar problem with ACF not working correctly with WPML plugin. Here is the description of the problem:

    The wrong behavior of ACF plugin in tandem with WPML results in repeater fields not being stored correctly in the database, meaning that they cannot be displayed correctly on the front-end. When trying to fetch some information from a repeater field, present on a page, that is a translation (WPML) of another page, the result will not be an expected array of data, but a string which represents the number of rows in the repeater. The problem occurs only on the pages, which are translations of other pages and for all repeater fields, regardless of when it was added. There is one found solution for the problem. If you go to the original page (WPML) and change in any way a repeater, it will get fixed for the translation page as well and start working as expected. But that only works for the repeaters that were edited in any way on the original page. Meaning that the problem lies not in updating the database, but in creating a mandatory record in the first place.

    Example of database info on a broken page:
    https://imgur.com/pc3fNmq (first attachment)

    Example of database info on a correctly working page:
    https://imgur.com/tdOn1kO (second attachment)

    The correct one has an additional “underscore field” _faq_custom that points to the field that holds the data so that it can be fetched.

    Additional information
    If we manually add this “underscore field” (in this case, _faq_custom) to the database, everything starts working fine.

    After saving FAQ fields on the page in the original language we can see the following in the database
    https://imgur.com/b8BHgbf (third attachment)

    It adds not only _faq_custom field, but a bunch of other ones as well, that weren’t properly added before.

  • Helping

    acf/save_post does nothing

    Not sure if I should open a ticket for this yet or not.

    According to the documentation, “This action allows you to hook in before or after the $_POST data has been saved, making it useful to perform additional functionality when updating a post or other WP object.”

    That’s exactly what I wan to do. Problem is, it does nothing. It’s never executed.

    add_action('acf/save_post', 'my_acf_save_post');
    function my_acf_save_post( $post_id ) {
    	file_put_contents('vardump.txt', serialize($post_id));
    }

    Nothing is ever written to my dump file.

    Using the standard WP “save_post” action hook, the ID is written to my dump file:

    add_action('save_post', 'my_wp_save_post');
    function my_wp_save_post( $post_id ) {
    	file_put_contents('vardump.txt', serialize($post_id));
    }

    No errors and nothing in debug log. The “acf/save_post” action hook just does nothing.

    I’d like to do additional processing on $_POST data prior to saving to the DB, but I can’t even get it to write the post_id right now.

    Should I report this as an official bug, or am I the only one experiencing this bizarre issue?

  • Solving

    Validation for required fields on post status "pending"

    Hey,

    how can I validate required fields, when the post status is “pending”?

    I have a custom post type for a user role with ACF fields.
    The user role can only save the CPT post as “pending”.
    The admin has to publish the CPT post.

    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 it possible to validate the fields on status pending?

    Best regards,
    Alex

  • Helping

    Convert JS serialized post-edit form data to get_fields array

    So, here’s something that I ran into and I’m not sure how to approach.

    Backstory.
    We’re creating an admin feature for Custom Post Type, let’s call it “A”, that should recalculate some data when we edit values on the edit form of said CPT. In order to perform that recalculation, we need information from CPT “B” that is not available on that edit screen.

    The recalculation should be possible to perform, even without actually saving the “A” edit form. We need to send current data to the backend, perform calculations, and return results for review before the user decides to Update the CTP for real.

    Idea.
    We know that we can run JS that will serialize edit post data, eg:
    jQuery(‘form’).serializeArray()

    That gives me the form data in the format of:
    JS serialized form

    That’s great, but parsing that would be a big pain in the …

    So, WP and ACF must be parsing this somehow already, in order to save it to the object. I wonder if there’s a good way to convert this serialized form to format that is returned by get_field or get_fields

    Toughts?

  • Solving

    ACF Pro – Custom Fields Sporadically Not Saving on Post

    We’re using ACF Pro to add custom fields to our posts; we then have our editors/admins go through on the backend and choose specific categories and/or check certain boxes for actions, etc for us to sort through user submissions.

    A couple of months ago (without any major changes to our site) this stopped working sporadically. One of our editors can be going through categorizing and assigning things on a post and it’s working great – and then suddenly, nothing saves anymore. They’ll choose the options in our ACF fields, click update (and get the WP update confirmation) but nothing changes – it resets back to what it was before they made changes.

    It doesn’t happen every time, but does several times a week/day. For example, out of roughly 1000 entries last week, 168 of them didn’t update when we tried.

    Thoughts? We have everything up to to date and I’m now at the point where I want to pull my non existent hair on my bald head out because I can’t find anything that may be wrong. Help! Thanks!

  • Solved

    Dynamically populated Select within Repeater

    I have a Repeater field with 2 subfields, one of which is called “user_role”. I want to populate the options of that field with the current available roles in the right translation.

    I’ve used the acf/prepare_field filter to populate and know that it works, because it works flawlessly when the (Select-)field is NOT in a repeater. But Because I want to be able add as many user roles as needed, a repeater seems in place.

    The problem is that, once I’ve set the role in one or two repeater rows and save it, I get an error. As soon as I move my Select field into a repeater, after saving the field valueI get this:

    Notice: Undefined index: sub_fields in /www/kinsta/public/toolbox-dashboard/wp-content/plugins/advanced-custom-fields-pro/pro/fields/class-acf-field-repeater.php on line 122

    Even if I remove my code after that, the error remains and I need to remove the entire field and start over. The subfield are nowhere to be found. After removing the repeater field and saving the fieldgroup, the subfields appear on the toplevel.

    Here’s an extract of my code, pretty simple really:

    class Options {
    
        public function __construct() {
    
            // make sure the user roles field has the appropriate roles
            add_filter( 'acf/prepare_field/name=tdb_user_role' , __CLASS__ . '::get_available_user_roles' );
    
        }
    
        public static function get_available_user_roles( $field ) {
            // setting these manually here, but will be coming from get_editable_roles()
            $field[ 'choices' ] = array( 'administrator' => 'Administrator' , 'editor' => 'Editor' );
            return $field;
        }
    }

    Filter is added after including the script and initializing it:

    new Options();

    Please, does anyone have a suggestion or insight on how to make this work within a repeater?

  • Solving

    ACF post category – Posts are not saving 1st time I publish

    I’m developing a wordpress site and i’m facing an issue with Advanced Custom Field that I can’t figure out.

    I have a category called “nature” and I have create a field using the ACF plugin and set the following rule: POST CATEGORY IS EQUAL TO NATURE.

    So, everytime I create a new post and then, inside the post, select the category “nature” at the right bar, it shows the custom fields right away (like ajax or something). The fields just shows. I thought that everything was fine, but there is one major problem with that.

    I fill the fields with information, upload images and so on and then I publish. But it doesn’t save the first time I leave the post. It just works fine if I edit the post again and retype and resend all the images and then update the post.

    It’s not a custom post type. It is an ordinary post. The loops shows only the post title, but none of the custom fields are being showed after the first time I publish. Only if I fill everything again.

    I’ve tried everything (reinstalled the plugin, the theme, the group of fields) but It just does not work. Can someone help me with that?

    Thanks a lot.

  • Solving

    Create product title + permalink + slug from several custom fields

    I want to create new Woo products in backend as admin (or update), without using the default WP title field.
    The title (and permalink + slug) should always be created based on values selected in two dropdown boxes and one text field in ACF Pro (all are mandatory fields). When saving the product (also about 20 other custom fields) it should be created/updated and published. The title should be a combination of: “value 1 + 2 + 3”.

    Changes afterwards in the products default WP title field should be ignored (maybe hide that), unless any of the three custom fields that create the title have been edited. Updates in any of the three custom fields should not only update the title when saving, but also update the permalink and slug.

    I created a solution to this at least 5 years ago, but it was a slow and bad solution as I´m not a coder. I can´t find that code, but it took about 30 seconds to save a product so there were probably several errors in that code (I guess that “wp_insert_post_data” was run before the acf/save_post)! I have searched for an updated code in several forums, but I have not succeeded. I really appreciate any help with this!

    WP (5.8.1), Avada (7.5), ACF Pro (5.10.2), PHP (7.4.25). Smarter code and better performance with PHP version 8.0.12?

  • Solving

    Many fields in a repeater : long saving times

    Hi,

    I am building some kind of custom CRM tool for my company, based on WordPress and ACF.

    From what I understood from this thread and others, having too many fields will cause long saving times, and even timeout issues* (I haven’t finished building my fields so I haven’t tested yet)

    Most of my fields will be located in a repeater, with about 50 fields in each row. I want to add more functions eventually so I’ll eventually get to 100 or even 150 fields. When I have 2 rows in the post, it will be fine, but as soon as I get to 5, 6 (regularly) or more than 10 rows (rarely), I’ll probably face serious performance issues.

    Question:
    I understand that the problem comes from the fact that, when a post is saved, WordPress checks each field individually, one after the other.
    => Wouldn’t it be possible to create a custom function that makes WP check each ROW of the repeater, and ONLY if there has been a modification in that row, check each field independently ? That would increase the performance dramatically.

    I’m not a developer so I would ask one to do it, but first I need to know if it’s even feasible.

    If not, is there any other solution that could help with this problem ?
    If not, I might have to rethink the way my tool is built, and separate different functions in different custom posts, instead of having it all in a same custom post. A solution I don’t really like, but better than having very long saving times.

    Thank you in advance !

    *On another thread, John Huebner mentions that Gutenberg might help with this issue, so I don’t even know if the problem still remains nowadays.

  • Solving

    update_field values not showing on frontend

    After couple of nights of searching and trying various approaches, I haven’t found any solution.

    Issue

    I suspect that ACF’s cache is not clearing after saving programmatically post meta.

    I’m creating a tool for admins, which will update custom post type’s meta data (ACF-fields) with command update_field()

    Changes are being saved to the database and changes can be seen when editing the post. And actually the new values can be seen anywhere in backend.

    On the frontend new saved meta data can’t be seen, but there’s old values that doesn’t exist in the database anymore. In other words: on frontend meta data is showing value A, and in database is stored value B.

    So the values are not fetched from the database, but from cache, I think. If I update the post in the edit post view, then the new values will show on frontend. But instructing users to go editing post and save it after using this mentioned tool, is not good practice.

    So what am I not noticing?

    What have been tried

    This is what I have already tried: After update_field() I’ve run:

    wp_cache_delete()
    
    clean_post_cache()
    
    update_post_caches()
    
    wp_cache_flush()
    
    $wpdb->flush()

    These functions didn’t empty the cache. Am I perhaps using them wrong?

    I’m doing the developing in Local by Flywheel, which is using Nginx. I suspected about Nginx and switched to Apache, but that didn’t help. So Nginx isn’t causing the issue. And now as I’m developing the site, there is no cache plugins being used.

  • Solved

    When is acf/settings/load_json supposed to run?

    Hi,
    I’m trying to set up local json sync on a multisite installation. It worked with the default acf-json folder in the child theme, but I’d like to save and load everything from the parent theme. I managed to make it work when it comes to saving (custom fields will get saved to the parent theme folder from all subsites). However, the filter for loading (acf/settings/load_json) doesn’t seem to trigger. Even when I just try to output some strings in the error log.

    I’m not sure what I’m doing wrong since I basically just copy pasted the documentation’s code and only changed the path, but the fields won’t sync.

    Any help would be appreciated! Thank you 🙂

    Here’s what I put in functions.php:

    // changes saving location for custom fields
    add_filter('acf/settings/save_json', 'my_acf_json_save_point');
    function my_acf_json_save_point($path) {
        // update path
        $path = get_template_directory() . '/custom-fields';
        
        // return
        return $path;
    }
    
    // changes loading location for custom fields
    add_filter('acf/settings/load_json', 'my_acf_json_load_point');
    function my_acf_json_load_point( $paths ) {
        error_log('hey!');
        
        // remove original path (optional)
        unset($paths[0]);
        
        // append path
        $paths[] = get_template_directory() . '/custom-fields';
        
        // return
        return $paths;
    }
  • Solved

    Saving values to another post on post save

    I have the custom post type ‘machines’.

    Machines has two custom fields of the type post object: “company” and “seller”.

    On saving the machine post type, I want to update the company post (which has a ‘sellers’ repeater and a ‘machines’ repeater) with
    the ‘seller’ id selected for ‘machine’ and the ‘machine’ id itself.

    Also I want to update the ‘seller’ post’s ‘company’ custom field with the ‘company’ post type id that has been selected for the machine post type.

    I have written the following function to accomplish this:

    add_action('save_post_machines', 'associate_machine', 10, 3);
    
    function associate_machine($post_ID){
            
        //Add seller and machine to company page
            $company = get_field('field_60f1861f1b262', $post_ID); //company ID
            $seller = get_field('field_60f186361b263', $post_ID);  //seller ID
            $whichs = ['machine' , 'seller'];
            foreach($whichs as $which):
                
                $post_ID = $which == 'machine' ? $post_ID : $seller;
    
                $repeaterValues = [];
                    if(have_rows($which.'s', $company)): //Machines or sellers repeater
                        while(have_rows($which.'s',  $company)):
                            the_row();
                        $repeaterValues[] = get_sub_field($which, $company);
                        endwhile;
                    else:
                        add_row($which.'s', array($which => $post_ID), $company);
                    endif;
    
                    //if machine or seller ID is already inserted, simply stop here
                    if(in_array($post_ID, $repeaterValues)):
                    elseif(!in_array($post_ID, $repeaterValues) && !empty($repeaterValues)): // if not, add it
                        add_row($which.'s', array($which => $post_ID), $company);
                    endif;
    
            endforeach; 
    
            //Add company to seller:
            update_field('company', $company, $seller);

    But instead of having the seller id in the sellers repeater, I only get an empty row.

    Additionally, and this is strange: I was testing this on my staging site, and it was working. Then uploading the same code to live, it is not. (I made a compare of all theme files of live and staging and matched them up 100%, and still.

    I also checked if there were any plugins that were not updated on the staging site, still no change.

    So I have worked on this for a while and can’t seem to find what I am missing.

    Any insights would be appreciated.

  • Solving

    Whenever we are creating new custom field groups, the fields are not saving the

    Hi,

    Recently whenever we are creating new custom field groups, the fields are not saving the data. But the fields from old custom field groups are working fine. This problem is happening with both older and newer versions of Free ACF.

    Is there any limitation of the number of custom field groups we can use using Free ACF?

  • Solving

    issues importing content from Salesforce

    I’m using this plugin to sync data from Salesforce into our site, specifically ACF fields:
    https://wordpress.org/plugins/object-sync-for-salesforce/

    We’re experiencing some very weird behavior.

    The fields are assigned to a custom post type which are then pulled via a query into a grid layout on a single page.

    On a published post that has already imported data from Salesforce, whenever we update that data in SF, then wait for the object sync cron job, I can see the updated text when that post is open in my browser (wp backend). However, this is then only visible on the front end after manually clicking publish.

    So after reaching out to the object sync dev, he thought maybe there’s some ‘intermediate step’ whereby ACF isn’t actually saving the change to the database, as would occur when clicking update.

    Does this make sense at all? That newly imported data from SF could visibly appear inside the post editor in the backend, but not actually be visible on the front end until manually clicking publish?

    Here’s my support ticket with object sync if that helps: https://wordpress.org/support/topic/syncing-issues-4/

  • Helping

    acf field type wysiwyg editor is stripping question mark from UTM breaking link

    I have an ACF wysiwyg editor where I need to put a link in as raw text/html

    like:

    <a class="home-hero-tc-cta" href="https://web.com/pagename?utm_campaign=campaign%20name&utm_source=Homepage%20Hero&utm_medium=From%20the%20homepage">Register Now</a>

    but it remove the question mark and breaks so it does

    <a class="home-hero-tc-cta" href="https://web.com/pagenameutm_campaign=campaign%20name&utm_source=Homepage%20Hero&utm_medium=From%20the%20homepage">Register Now</a>

    and it 404s.

    https://www.reddit.com/r/Wordpress/comments/btazok/wordpress_stripping_code_from_acf_fields/

    >For the text field for custom scripts, is it a WYSIWYG field or just a textarea field? WordPress does not like scripts in WYSIWYG fields, it will remove them altogether if on the Visual Editor portion and saving. If on HTML view, they likely would be retained but in general WP does not want scripts/HTML code in WYSIWYG fields.

    It’s WYSIWYG and its not a script

    https://support.advancedcustomfields.com/forums/topic/regression-backslashes-stripped-in-wysiwyg/

    not backslashes

    I can’t find anything online explaining this.

    How do you keep question marks in WYSIWYG editor in wordpress acf to keep question marks in url

  • Solving

    Save ACF relationship (name) value to ACF text field

    I try to achieve the following. I have two post types, “projects” & “kuenstlerinnen” (artists) Within the post type “projects”, there’s an ACF relationship field setup, connecting these two to together → “project_to_kunstlerin”

    The post-type “künstlerinnen” (Artists) contains two ACF text fields: first-name (“artist_vorname”) & Last- or Group-Name (“artist_nachname”). There is a code snippet running, which saves both fields to the title → “artist_vorname””artist_nachname”

    I know would like to have a hidden text field within the projects post type, which is automatically populated with the first value of the “project_to_kunstlerin” field. It should only use the last name field. The reason I try to get this to work, is that I can order by this hidden field, so I get the posts ordered by the last name of the artist.

    So far I come up with the following code-snippet:

    <?php
    
    //Make special artist field autosave for sorting
    function write_artist_name_to_hidden( $post_id ) {
        $post_type = 'projects'; //custom post type for events
      
        //Check if we are saving correct post type
        if( get_post_type( $post_id ) != $post_type)
          return;
      
        //Check it's not an auto save routine
        if( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ) 
          return;
        
        // get the artist id  of the post. Note this is in a relationship field
        $nameofartist = get_post_field ('project_to_kunstlerin', $post);
        
      
        // update the artist value 
        update_field( 'project_kunstlerin_nach_name_sort', $nameofartist, $post_id );
      }
      add_action('save_post', 'write_artist_name_to_hidden');

    In the backend, it now populates the destination ACF field with:

    One artist: “[“37″]” Two artists: [“37″,”38”]

    These are the IDs.

    How can I get another value there instead of the post id?

    In theory, it must be something like:

    Check with IDs are in the “project_to_kunstlerin” relationship field.
    Take the first ID.
    Look up, which value is stored in “artist_nachname” of ID in post type “kuenstlerinnen”
    Maybe anybody of you has an idea how to get this to work? Your help is highly appreciated!

  • Solving

    saving different value than $_POST['acf']['field_xxx']

    Hi,
    I am having a problem saving data that is not the same as the _Post,
    It is writing what is coming from the form, And I want it to write the new information.

    I got some of this from here update_value-hook-not-working-when-saving-post/
    as I think it is not using the updated value but the value from the form.

    This is the code I have and I cannot not figure out where I have gone wrong.

    add_action('acf/save_post', 's4f_save_post_step_content', 20);
    function s4f_save_post_step_content( $post_id ) {
        if (wp_is_post_revision($post_id)) {
            return false;
        }
        if ( (isset($_POST['acf'])) && (get_post_type($post_id) == 'step') ) { 
    
            $fields = $_POST['acf'];
    
         //  Data to retrieve and calculate
         	$goal_post_id = $fields['field_6052515cbb6c7'];  // an array related_goal 
         	$the_goal_post_id = $goal_post_id[0];  // related_goal  
         
         // data from the related goal
         	$goal_collections_not_from_s4f = get_field('field_605257355dc6d', $the_goal_post_id); 
         	$goal_collections_from_s4f = get_field('field_605256cf5dc6c', $the_goal_post_id); 
         	$goal_total = $fields['field_605254421e35d'];  
    	
    	// data from step input form
         	$step_old_collected_to_date_not_s4f = $fields['field_605254a91e35e']; // used to compare with goal to see if it needs updating
         	$new_step_input_not_from_s4f = $fields['field_605260f5663f1'];  // new_collected_not_s4f  input
    
         	$new_calc_collected_from_other_sources = $goal_collections_not_from_s4f + $new_step_input_not_from_s4f; // recalculated here in case this is an update
         	$new_calc_total_collected = $new_calc_collected_from_other_sources + $goal_collections_from_s4f;  // grand total recalculated here in case this is an update
        
       
        if ($goal_collections_not_from_s4f !== $step_old_collected_to_date_not_s4f):
    
            if (isset($_POST['acf']['field_605254a91e35e'])) : // replace with your field key
                 $_POST['acf']['field_605254a91e35e'] = $goal_collections_not_from_s4f;
               else :  update_field('collected_to_date_not_s4f',$goal_collections_not_from_s4f,$post_id);
            endif;
    
            if (isset($_POST['acf']['field_60526244663f2'])) : // replace with your field key
                 $_POST['acf']['field_60526244663f2'] = $new_calc_collected_from_other_sources;
               else :  update_field('calc_collected_to_date_not_s4f',$new_calc_collected_from_other_sources,$post_id);
            endif;
    
            if (isset($_POST['acf']['field_6052632c663f5'])) : // replace with your field key
                 $_POST['acf']['field_6052632c663f5'] = $new_calc_total_collected;
               else :  update_field('calc_grand_total',$new_calc_total_collected,$post_id);
            endif;
         endif;
    
        } // end post type
    }// end function s4f_save_post_step_content
    
  • Unread

    From Where Does "get_field()" Acquire A Value?

    The ACF documentation states the following in its description of the “get_field()” function:

    “Returns the value of a specific field.”

    In the interest of clarification, is a custom field’s value retrieved via a database query or is it acquired directly from the current value populated for that custom field in a post’s editor?

    If it the value results from a database query, then I need to understand why the value for one of my custom fields is not saving properly to the WP postmeta table. The following are code excerpts from two ACF custom field types that I created. Each instance of the custom field types are used within the same custom post type. The first custom field type’s value saves properly to the WP postmeta table; the second one does not.

    ===================================
    First ACF custom field code excerpt
    ===================================

    function __construct($settings) {
      // Stuff...
      $this->defaults = array(
        'value' => 'Testing 1...2...3...'
      };
      // More stuff...
    }
    
    function render_field_settings($field) {
      acf_render_field_settings($field, array(
        'label' => __('The Test', 'acf'),
        'instructions => __('An ACF test case value', 'acf'),
        'type' => 'text',
        'name' => 'value'
      ));
    }
    
    function render_field($field) {
      ?>
      <label for="<?php echo esc_attr($field['name']) ?>">ACF Test Case Value</label>
      <input
        type="text"
        name="<?php echo esc_attr($field['name']) ?>"
        value="<?php echo esc_attr($field['value']) ?>" />
      <?php
    }

    ===================================
    First ACF custom field code excerpt
    ===================================

    function __construct($settings) {
      // Stuff..
      $this->defaults = array(
        'value' => array(
                     'host' => 'uvi',
                     'version' => '1.0'
                   )
      );
      // More stuff...
    }
    
    function render_field_settings($field) {
      acf_render_field_setting($field, array(
        'label' => __('Plugin Host Value', 'acf-plugin-host'),
        'instructions' => __('Enter the plugin host & version values in this form', 'acf'),
        // 'type' => 'text',
        'type' => 'array',
        'name' => 'value'
      ));
    }
    
    function render_field($field) {
      ?>
      <label for="<?php echo 'pc-host-' . $field['value']['host']; ?>">Plugin Host</label>
      <input
        type="text"
        id="<?php echo 'pc-host-' . $field['value']['host']; ?>"
        name="<?php echo 'pc-host-' . $field['value']['host']; ?>"
        value="<?php echo $field['value']['host']; ?>">
      </input>
    
      <label for="<?php echo 'pc-host-version-' . $field['value']['version']; ?>">Plugin Host Version</label>
      <input
        type="text"
        id="<?php echo 'pc-host-version-' . $field['value']['version']; ?>"
        name="<?php echo 'pc-host-version-' . $field['value']['version']; ?>"
        value="<?php echo $field['value']['version']; ?>">
      </input>  
      <?php
    }

    As I understand it, the ACF custom field value is saved to the WP postmeta table when the edited post is saved/updated; saving the custom field data requires no additional code by default. The first custom field value is saved properly, but this is not the case with the second custom field value. For the second case, the WP postmeta table stores a “NULL” value.

    The primary difference between the first and second custom field types is that the first’s value is scalar but the second’s value is an array. For the second custom field type’s code, I commented out the type text value within the “render_field_settings()” function and assigned the type key to “array” instead.

    Unfortunately, that change had no impact on the value saved to the WP postmeta table. It still saves as “NULL”.

    Your feedback is appreciated.

    Thank you.

  • 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.

Viewing 25 results - 26 through 50 (of 243 total)