Support

Account

Home Forums Search Search Results for 'q'

Search Results for 'q'

topic

  • Unread

    Updating order issue

    Hi,

    I managed to set up a percentage of completion of specific fields, everything works but one thing: I need to save the post 2 times for it to update the average of this percentage across every post.

    I’ll start with the whole procedure:

    1. I have a group of fields where I need to import files, I created a PHP snippet that detects if a file is inserted into the field and return a completion percentage. Coding is not my thing so there is probably a shorter way of doing it.


    <?php
    $values1 = get_field( 'cni' );
    $values2 = get_field( 'rib' );
    $values3 = get_field( 'justif' );
    $values4 = get_field( 'lettre' );
    $values5 = get_field( 'der' );
    $values6 = get_field( 'situation' );

    if(count(array_filter(array($values1,$values2,$values3,$values4,$values5,$values6)))==1){
    //only 1 variable is not empty
    echo '17';
    }

    elseif(count(array_filter(array($values1,$values2,$values3,$values4,$values5,$values6)))==2){
    //only 1 variable is not empty
    echo '33';

    }

    elseif(count(array_filter(array($values1,$values2,$values3,$values4,$values5,$values6)))==3){
    //only 1 variable is not empty
    echo '50';
    }

    elseif(count(array_filter(array($values1,$values2,$values3,$values4,$values5,$values6)))==4){
    //only 1 variable is not empty
    echo '67';
    }

    elseif(count(array_filter(array($values1,$values2,$values3,$values4,$values5,$values6)))==5){
    //only 1 variable is not empty
    echo '83';
    }

    elseif(count(array_filter(array($values1,$values2,$values3,$values4,$values5,$values6)))==6){
    //only 1 variable is not empty
    echo '100';
    }
    else {
    echo '0%';
    }?>

    2. In hook-functions.php, I added this code that adds the percentage as a field so I can call it somewhere else (which works):

    function my_acf_load_value11( $value, $post_id, $field )
    {
    // run the_content filter on all textarea values
    $value = do_shortcode( '[xyz-ips snippet="test"]' );

    return $value;
    }

    3. I can display the field just fine but then when I use this code, it doesn’t update right away, it keeps the last update which forces me to update the post 2 times for it to show the right number.

    $args = array(
    'posts_per_page' => -1,
    'post_type' => 'post',
    'meta_key' => 'sum',
    'meta_value' => '100',
    );

    // The Query
    $the_query = new WP_Query( $args );

    // Counting the results
    $the_count = count($the_query->posts);

    //* Restore original Post Data
    wp_reset_postdata();

    echo $the_count;

    I can’t find the problem, my suggestion would be the saving order of the post and the field but I don’t know how to solve it.

    Thank you for the help, I tried my best to explain but it’s pretty complex to me.

  • Unread

    Woocommerce ACF uploaded files? Import/Exports

    I have a website with a few thousand products in Woo. I’m using the Woo import/export feature to export, edit then re-import product data. All of my products have custom ACF fields with files uploaded.

    Woo exports as a CSV which is fine, but when I re-upload the CSV, the products no longer have the uploaded files in place.

    I have a few questions!

    1. Is there a way to stop these file connections being broken during the update?

    2. Is there a way to update files through this csv? Currently ACF names these fields as ‘field_xyz’ rather than the direct URL of the file. Is there a way to have ACF return the exact file URL?

    Really appreciate any help on this one. I’m no coder, so its all a bit scary!

  • Unread

    Missing a step in the process?

    I’m brand new to ACF and attempting and failing to use it for the first time. My goal is to use ACF to help populate an image module with a category archive title.

    The problem is that when I go into the category archive template I built, I can’t see the ACF field group I created as an option to add.

    Even though I’ve been reading and watching videos on the ACF site, I’m still struggling with the terminology and the concept of ACF.

    How I have it set up:
    Field Group
    1. Field type: Text
    Field Label: catname1
    Field Name: catname1
    Default Value: blank because I have no idea what I’d input on this one.

    2. Field type: Image
    Field Label: catimage1
    Field Name:catimage1
    Default Value: blank

    Under Settings I input:
    Taxonomy is equal to Category (category)

    Under Post Types
    Plural Label: Category Headers
    Singular Label: Category Header
    Post Type Key: category-header
    Taxonomies: Category (category)
    Set to Public but Hierarchical is toggled off.

    Under Taxonomies
    Plural Label: Category Headers
    Singular Label: Category Header
    Post Types: Post (post)
    Set to Public but Hierarchical is toggled off.

    I notice this comes up when I hit Save but I’m unsure if I’m supposed to do anything with these:
    Category Headers taxonomy updated
    Add fields
    Link field groups
    Create taxonomy
    Duplicate taxonomy
    Create post type

    Essentially I don’t know enough to know if I’ve set this up incorrectly or if I’m missing a vital step in the process.

    Addendum question: am I required to install a child theme (plugin) in order to not lose my ACF fields? In other words, when I next update my theme or wordpress, am I going to lose all of the work I did in the ACF plugin?

  • Unread

    ACF not retaining or showing data – What I’ve tried…

    New to the forums and using ACF. I’m not a developer, but know my way around PHP and building website for myself.

    I have my current site built with Kirby. and want to rebuild it in WordPress. So I started building and found I needed ACF. Installed it and found it wasn’t retaining any data, so using the snippets it wawasn’t showing anything.

    Ok, maybe it was my coding. So I installed the basicWP theme But it was still not doing anything.

    One more test… I build a ’nothing’ theme where I had only a title and one ACF field. Still not showing or retaining any data.

    So now I’m stuck. That’s even after watching videos, reading the requirements and doing a bunch of research.

    Here’s what I have tried…

    Local:
    – MAMP pro
    – PHP 8.3 (and 8.2)
    – mysqli 5.7.39
    – mysqlnd 8.3.0
    – Fresh install of WordPress 6.8.2
    – Theme: Twenty Twenty three
    – ACF 6.5.0

    Server:
    – Lightspeed
    – PHP 8.2.29
    – mysli 10.6.22-MariaDB-cll-lve
    – mysqlnd 8.2.29
    – Fresh install of WordPress 6.8.2
    – Theme: Twenty Twenty three
    – ACF 6.5.0

    What am I missing? Or is this a bug of some sort?

    Any help would be appreciated!

  • Helping

    Date Picker question

    The documentation doesn’t appear to answer a couple of issues I am having.

    1. There seems to be a limit to the earliest year you can go back to – 1925. Is there a way around this?
    2. If I only have a year, rather than a full date, obviously I can’t use the date picker function BUT even if I type it in manually into the field it doesn’t seem to retain the data. Is this due to a wordpress limitation – that it only store dates in the YYYYMMDD format?

    Context: I have a site which contains biographies of people, mostly bornin ain the 1800s. For many of those people I only have a year of birth (or approximate year of birth) and not a specific date. Can I use the date picker to record/retain this data or is the only solution to use a free text field? If anyone has any ideas around this I;d love tto hear them.

    Thank you 🙂

    I’m using WordPress, Divi Theme, ACF free version.

  • Unread

    InnerBlocks and empty $block in render_block_preview action

    Hi!
    I noticed a problem when I create custom blocks that contain <InnerBlocks/>. In that case, I am not able to retrieve the $block object in the js script fired in the backend.

    function.php
    ——————

    add_action('init', 'register_acf_blocks');
    function register_acf_blocks() {
    	wp_register_script('accordion-script', get_stylesheet_directory_uri() . '/blocks/accordion/script.js');
    	register_block_type(get_template_directory() . '/blocks/accordion/block.json');
    }

    block.json
    ————–

    {
        "name": "accordion",
        "title": "Accordion",
        "description": "Accordion to hide large amounts of text in drop-down sections.",
        "category": "my-category",
        "icon": "media-code",
        "keywords": [
            "accordion"
        ],
        "acf": {
            "mode": "preview",
            "renderTemplate": "render.php"
        },
    	"script": "accordion-script",
        "supports": {
            "layout": false,
            "align": false,
            "customClassName": false
        },
        "example": {
            "viewportWidth": 800
        }
    }

    render.php
    —————-
    <InnerBlocks/>

    script.js
    ———–

    
    (function($){
    
        var initializeBlock = function($block) {
    		console.log($block); // HERE IS THE PROBLEM!!! IN CONSOLE: e.<computed> {length: 0, prevObject: e.<computed>}
        }
    
        if( window.acf ) {
            window.acf.addAction( 'render_block_preview/type=accordion', initializeBlock );
        }
    
    })(jQuery);
    

    The problem disappears when I insert any HTML instead of InnerBlocks in render.php

    WP version: 6.8.1
    ACF version 6.4.2

  • Unread

    Warning if a field group has unsync’ed changes

    I love the local JSON files feature and use it in all my projects, both ones where I’m the only developer and others where we are several developers.

    What we run into ever so often is that we end up losing changes because somebody modifies an ACF field group that has newer changes in the local JSON file that had not been sync’ed yet. For example when working on different branches and switching between them, or when different developers make changes to the field groups and commit the changes to .git.

    Luckily, we all our JSON files in git, so we can always go back and find the changes that have been overwritten. But it’s not our favorite way of spending our time 🙂

    P.S.: I’ve already implemented a hook for this as part of my projects where I now show a warning on the “Edit field group” screen if the field group has unsync’ed changes. But I think it would be amazing to have something similar in the core product to everyone’s benefit. See the attached screenshot to see how my own little hack looks.

    The code for my workaround:

    
    // Show a warning when editing an ACF Field Group that has not been sync'ed yet
    function unsynced_acf_field_group_warning_hook() {
      global $post;
      $group_key = $post->post_name;
      $json = acf_get_local_json_files($post->post_type);
      if (isset($json[$group_key])) {
        // HACK: At this point in the life cycle, the ACF field groups are not loaded
        // So we simply read the JSON file and compare the timestamps
        $json_file = $json[$group_key];
        if (file_exists($json_file)) {
          $json_data = json_decode(file_get_contents($json_file), true);
          $json_modified = $json_data['modified'] ?? 0;
          $db_modified = get_post_modified_time('U', true, $post->ID);
          if ($json_modified > $db_modified) {
            add_action('admin_notices', function () {
              echo '<div class="notice notice-error"><p>The local JSON file has unsynced changes. <a href="' . admin_url('edit.php?post_type=acf-field-group&post_status=sync') . '">Sync now</a></p></div>';
              echo '<style> #wpcontent { background: rgba(255 0 0 / 0.05); } </style>';
            });
          }
        }
      }
    }
    add_action('acf/field_group/admin_head', 'unsynced_acf_field_group_warning_hook');
    
  • Unread

    Frontend Form – Field Validation – Not WP Die

    Hello,

    I’m looking to add some custom validation for a frontend (acf_form()) form input.

    The form input needs to make an ajax request to validate it’s value.

    What’s the best way to do this in an ACF supported way?

    – – –

    I’ve tried to add an event listener to the form submit, and I can prevent it from submitting to run my own validation, but then I can’t get the form to submit again for some reason.

    I’ve tried putting a listener onto the input itself, but then it’s a race against the user and ACFs own form submission validation.

    I’ve tried to go the PHP route with the validation filter hook, but wp_die() is probably the lamest way to show an error message that I can possibly imagine.

    I’ve tried taking a look at the JS docs, but sometimes their documentation isn’t always clear about what events do, what is given to them, or how to use them. It also doesn’t help that the ACF Pro input.js is minified, it doesn’t seem like it ships with any kind of unminified version either – makes it difficult to jump into the source to try and find a solution.

    – – –

    Ideally, I would like to return a validation error in a similar fashion to what ACF already does. Any suggestions on how I can accomplish this?

  • Unread

    Add filter picking acf-json file path

    Currently, if you add additional paths for ACF to load json from using acf/settings/load_json, it will use the LAST found acf field group. This means, even if a field is edited via the editor, it will still use the last path, such as from a plugin. This is described in the documentation:

    This filter will allow plugin and theme developers to easily register field groups, post types, taxonomies, or options pages which cannot be edited by clients.

    I have a different use case – we are an agency and want to have some base packages as all of our sites share a similar structure but I still need to be able to add fields to suit different clients, such as adding an additional image field in some nested field group.

    Currently, there is no way to change the behavior of this, it always picks the last. I propose adding a filter that would enable plugin developers to choose which file should be used for a specific field group.

    
    // Pick the newest version, regardless of if its in the theme or plugin folder
    add_filter('acf/json/pick_file', function($currentFile, $newFile, $newJson, $loadPath) {
    	// Only modify it if its the plugins path
    	if($currentFile && $loadPath == plugin_dir_path( __FILE__ ) . 'acf-json') {
    		$currentJson = json_decode( file_get_contents( $currentFile ), true );
    		// Compare modified dates and take newest
    		if ( $currentJson['modified'] < $newJson['modified'] ) {
    			return $newFile;
    		} else {
    			return $currentFile;
    		}
    	}
    	return $newFile;
    });
    

    All the code to support this would be very simple in the includes/local-json.php file:

    // __construct()
    add_filter( 'acf/json/pick_file', array( $this, 'pick_file' ), 10, 4 );
    
    // scan_files() line 326
    $json_files[ $json['key'] ] = apply_filters( 'acf/json/pick_file', $file, $json_files[ $json['key'] ] ?? null, $json );
    
    // Maintain current behavior
    public function pick_file( $currentFile, $newFile, $newJson, $path ) {
    	return $newFile;
    }

    Right now, the best you can do is choose to not include the acf-folder when doing acf/settings/load_json. This is problematic though if there are multiple field groups you want to load. Being able to filter individual files would unlock a lot of possibilities.

    TLDR Goal:

    • Create new theme, importing packages via composer
    • Use acf-json from packages
    • Make changes via editor, save to themes acf-json folder
    • Right now, will still use the packages acf-json, despite the theme’s being newer.

      • Would like to use the themes json file, while allowing sync from the package should we update it.

    Workaround:
    Prepend the package’s acf-folder path. This means the theme will always win, but it does unfortunately break the sync feature. Even if the package is modified and newer, it doesn’t show sync available.

  • Solved

    Looking for Content in Database

    I have inherited a project and I’m trying to wrap my head around how data is stored for ACF in our database.

    The example I’m struggling to debug is as follows: we have a field group (Sidebar Components) that has a list of layouts (button, image, form, etc) that references other field groups that will have fields (like buttontext). Now, I go to a post, scroll down to the Sidebar Component, add a Button, give it some text and save it, where does that text get saved???

    I can look at the postmeta table and see everything related to that post_id. _sidebar_components has a field related to it, as does _sidebar_components_0_sidebar_components. I can trace this back to my posts table to the acf-field that provides the structure, but I am looking for the actual text I put in for buttontext and can’t find that anywhere. I made it a fairly unique string, but can’t find it in the postmeta table and the query times out when I look in posts. If it is in posts, is there something more specific I can look for?

    I see this as the name for the input field on the post but I don’t understand how to trace it in the DB. acf[field_614deb4f175c1][row-0][field_61b6758cdc490][688b91cc13ce8][field_61b6758cdf9c0_field_614340d246dd8]. It seems the 688b91cc13ce8 is the unique ID for this specific sidebar, but not sure how to find it.

    WordPress 6.6.1
    Advanced Custom Fields PRO 6.2.9

  • Helping

    Issues with clickable links in my Repeater

    Hi – Would anyone else be able to look at this and help me identify what’s happening?

    I’m currently building a card block using a Repeater in ACF Pro (Version 6.4.3). Within the repeater, I have a number of sub fields – one of which is a link for a CTA button.

    I’m experiencing an issue where the string outputted by the ‘get_sub_field( )’ function in my <a> tag href appears to be outputted, but is not clickable.

    I’ve tried to output the link both with the Link Array and Link URL string method, and it seems to be happening for both.

    Here is my code, where my Link field is set to ‘Link URL’ within ACF:

    
    <div class="feature-cards-wrapper">
    
                        <?php 
        
                        if( have_rows('feature_card') ): 
                            while( have_rows('feature_card') ): the_row(); ?>
                                <div class="feature-card">
                                    <?php 
                                        $card_logo = get_sub_field('card_logo');
                                        $size = 'full';
                                            if ($card_logo ) {
                                                echo wp_get_attachment_image( $card_logo, $size, "", array('class' => 'feature-card-logo' ), 
                                            );
                                }
                                 
                                 $card_description = get_sub_field('card_description');
                                 $card_title = get_sub_field('card_title');
                                 $link = get_sub_field('page_link'); 
                                 $CTA_label = get_sub_field('cta_label');
    
                                    ?>
                                        <h3 class="feature-card-title block-title-<?php echo $text_value ?>"><?php echo $card_title ?></h3>
                                            <p class="block-copy-<?php echo $text_value?>"><?php echo $card_description ?>
    
                                                <div class="feature-card-cta">
                                                <?php if( $link ): ?>
                                                    <a class="feature-card-link" href="<?php echo esc_url( $link ); ?>"><?php echo $CTA_label; ?></a>
                                                <?php endif; ?>
                                                </div>
                                    </div>
    
                        <?php endwhile; ?>
                        <?php endif;  ?>
                    </div>
    

    Here’s my code, where the Link is set to ‘Link Array’. Both of these examples outputs the link string itself, but the link is still not clickable:

    
    <div class="feature-cards-wrapper">
    
                        <?php 
        
                        if( have_rows('feature_card') ): 
                            while( have_rows('feature_card') ): the_row(); ?>
                                <div class="feature-card">
                                    <?php 
                                        $card_logo = get_sub_field('card_logo');
                                        $size = 'full';
                                            if ($card_logo ) {
                                                echo wp_get_attachment_image( $card_logo, $size, "", array('class' => 'feature-card-logo' ), 
                                            );
                                }
                                 
                                 $card_description = get_sub_field('card_description');
                                 $card_title = get_sub_field('card_title');
                                 $link = get_sub_field('page_link'); 
                                 $CTA_label = get_sub_field('cta_label');
    
                                    ?>
                                        <h3 class="feature-card-title block-title-<?php echo $text_value ?>"><?php echo $card_title ?></h3>
                                            <p class="block-copy-<?php echo $text_value?>"><?php echo $card_description ?>
    
                                                <div class="feature-card-cta">
                                                <?php if( $link ): 
                                                  $link_url = $link['url'];
                                                  $link_title = $link['title'];
                                                  $link_target = $link['target'] ?       
                                                  $link['target'] : '_self';  
                                                   ?>
                                                    <a class="feature-card-link" href="<?php echo esc_url( $link_url );?>" target="<?php echo esc_attr( $link_target ); ?>"><?php echo esc_html( $link_title ); ?></a>
                                                <?php endif; ?>
                                                </div>
                                    </div>
    
                        <?php endwhile; ?>
                        <?php endif;  ?>
                    </div>
    

    _________

    My ‘feature-card-link’ css class isn’t affecting it, as it’s added to a CTA at the end of the card which works absolutely fine:

    
    a.feature-card-link {
        border-radius: 2rem;
        color: white;
        margin: 2rem 0;
        padding: 0.75rem 1rem;
        border: 1px solid #ffffff;
        text-transform: uppercase;
        text-decoration: none;
        letter-spacing: 2px;
        font-family: 'DMSans';
        font-weight: 300;
        transition: 350ms ease-in-out;
        &:hover{
            background-color: var(--wp--preset--color--ba-pink);
        }
    }
    

    Code for the CTA outisde the repeater that’s working fine. I tried to replicate this in my repeater field with ‘the_sub_field( )’, but didn’t work:

    
    <div class="feature-card-cta">
                        <?php $page_id = get_field('feature_link'); ?>
                        <a class="feature-card-link" href="<?php the_field('feature_link'); ?>">Let's have a chat</a>
                    </div>
    

    ___________

    I’ve attached a screenshot of the link in my inspector, where you can see the code has outputted, with the target html, but no working link in the button.

    Any assistance or help that could shed light on this for more would be greatly appreciated!

  • Unread

    Option to swap Location Rules rule group logic

    Would be great to be able to swap the logic/direction of the Location Rules operators. E.g., right now within a rule group the AND operator is used and the OR operator between the rule groups. If we wanted to set up a rule where the ACF fields are displayed when the current user is an Admin AND the post type is any one of post/layout/section/element/etc. we’d have to set it up as:

    Rule Group 1: Current User is Administrator AND Post Type is equal to Page
    Rule Group 2: Current User is Administrator AND Post Type is equal to Section
    …and so on.

    The “Current User is Administrator” has to be added into every rule group.

  • Unread

    Tabs Previous and Next Buttons

    Done!
    You can add this JS using WPCode, Woody Code plugins or manually add it in.
    This also works if you show ACF on the frontend of a page or post.

    
    //Add the body end in <script> tags
    document.addEventListener("DOMContentLoaded", function() {
        const tabGroup = document.querySelector('ul.acf-tab-group');
        const tabs = document.querySelectorAll('ul.acf-tab-group li a.acf-tab-button');
        const submitButtonDiv = document.querySelector('.acf-form-submit');
        const submitButton = submitButtonDiv.querySelector('input[type="submit"]');
        const nextButton = document.createElement('button');
        nextButton.id = 'next-button';
        nextButton.innerText = 'Next';
        nextButton.type = 'button'; // Set the button type to prevent form submission
        const prevButton = document.createElement('button');
        prevButton.id = 'prev-button';
        prevButton.innerText = 'Prev';
        prevButton.type = 'button'; // Set the button type to prevent form submission;
    
        let currentTab = 0;
    
        // A. Count the amount of tabs
        const totalTabs = tabs.length;
    
        // Hide Submit button initially
        if (submitButton) {
            submitButton.style.display = 'none';
        }
    
        // Show Next, Prev buttons based on data-order attribute
        function showHideButtons() {
            prevButton.style.display = currentTab > 0 ? 'block' : 'none';
            nextButton.style.display = currentTab < totalTabs - 1 ? 'block' : 'none';
            submitButton.style.display = currentTab === totalTabs - 1 ? 'block' : 'none';
        }
    
        // Trigger tab click based on data-order
        function triggerTabClick(order) {
            let tabToClick = document.querySelector(<code>a.acf-tab-button[data-order="${order}"]
    );
            if (tabToClick) {
                tabToClick.click();
            }
        }
    
        // Handle Next button click
        nextButton.addEventListener('click', function() {
            currentTab = Math.min(currentTab + 1, totalTabs - 1);
            triggerTabClick(currentTab);
            showHideButtons();
        });
    
        // Handle Prev button click
        prevButton.addEventListener('click', function() {
            currentTab = Math.max(currentTab - 1, 0);
            triggerTabClick(currentTab);
            showHideButtons();
        });
    
        // Add data-order attribute to each tab
        tabs.forEach((tab, index) => {
            tab.setAttribute('data-order', index);
            tab.addEventListener('click', function(event) {
                event.preventDefault();
                tabs.forEach(t => t.classList.remove('active'));
                tab.classList.add('active');
                currentTab = index;
                showHideButtons();
            });
        });
    
        // Initial setup
        showHideButtons();
    
        // Apply inline style to the submitButtonDiv
        submitButtonDiv.style.display = 'flex';
        submitButtonDiv.style.justifyContent = 'space-between';
    
        // Prepend the buttons before the Submit button in the div.acf-form-submit
        submitButtonDiv.insertBefore(prevButton, submitButton);
        submitButtonDiv.insertBefore(nextButton, submitButton);
    });
    
    

    Steps to make:

    I started by identifying the container for ACF tabs and the individual tab elements within it. Next, I fetch the submit button div on the page and hide its default submit button to create 2 custom navigation buttons, “Next” and “Prev,” which are dynamically generated for users to navigate between tabs.

    I’ve assigned each tab a numerical order using a created data-order attribute. This allows me to show or hide the buttons based on the current tab position to prevent navigation beyond its limits. Clicking the “Next” button increases the current tab by one, while clicking the “Prev” button decreases it, both updating the displayed tab accordingly.

    Clicking directly on a tab does not disrupt the function and remains available for use. Finally, I styled the div containing the custom buttons inline to use flexbox with justify-content: space-between, ensuring the buttons are properly aligned. Cheers!

  • Unread

    One Directional Sync

    I want to have a plugin that defines my Base ACF structure that I use across all of our sites we build. I still need the ability to modify the structure for specific client needs. I would like to have the ability to keep sites up to date with our Base ACF structure however.

    I’ve been playing around adding my plugin as a load_json path. I added a test field and synced it. I created an acf-json folder in my theme, so it saves the structure there.

    If I manually add another field, the entire stucture gets saved to my theme acf-json folder, which is fine. If I then add another field to my plugin’s ACF, I see I can sync them.

    My issue is, it wants to overwrite my local acf fields that I created. What I want to do is only bring IN the changes from the plugin.

    Example:

    Base ACF Plugin

    
     { 
                "key": "field_686ff4418f6cd",
                "label": "Test Field 1",
                "name": "test_field_1",
     }
    

    Define Field in Theme

    
     { 
                "key": "field_686ff4849c814",
                "label": "Test Field 2",
                "name": "test_field_2",
     }
    

    Update Base ACF Plugin

    
     { 
                "key": "field_243cc2251d954",
                "label": "Test Field 3",
                "name": "test_field_3",
     }
    

    In this case I would want all three fields to exist, only bringing in the new fields added to my plugin.

    Or is there a better way about going about this. I imagine something like this is a pretty common thing agencies want to do. I am also playing around with defining it via PHP but the JSON is so much more convenient, especially if the admin UI editor can be retained.

    Other thoughts
    I realize the diff editor is just doing a file diff, and not actually comparing items based on their key which poses an implementation change to support this.

  • Solved

    Force update of “Bidirectional”

    Hi.
    This is my Scenario:
    Custom Post Type “A”: has many ACF Fields, 1 of them is “Related to…”
    Custom Post Type “B”: has not so many ACF Fields, 1 of them is “This A are related to me”.
    I have just modified an ACF Field in “A” from Relationship to Relationship with Bidirectional that puts the relationship in the proper value of B.

    Now I need to open all “A” make a change in the relationship to enforce the update and add all the Relationship.

    “A” posts are >1000 so I’m looking if is possible do it in an automatic way …
    Just enforce an “update” in not enough…

    This code, doesn’t work.

    <?php
    include 'wp-load.php';
    print '<xmp>';
    $post_type   = 'MY_POST_TYPE A';
    $acf_field   = 'ACF_FIELD_OF_A_HAS_RELATIONSHIP';
    $batch_size  = 200;
    set_time_limit(0);
    
    $offset = 0;
    $total  = 0;
    
    do {
        $spots = get_posts([
            'post_type'      => $post_type,
            'post_status'    => 'any',
            'posts_per_page' => $batch_size,
            'offset'         => $offset,
            'fields'         => 'ids',
            'orderby'        => 'ID',
            'order'          => 'ASC',
            'no_found_rows'  => true,
        ]);
    
        foreach ($spots as $spot_id) {
            $value = get_field($acf_field, $spot_id);
    
            update_field($acf_field, $value, $spot_id);
    
            $total++;
            echo " • Post ID {$spot_id} \n";
        }
    
        $offset += $batch_size;
    } while (!empty($spots));
    
    echo "\n {$total} posts done.\n";
    

    Maybe to trigger bidirectional update there is something special to do?

  • Solving

    Order by Custom Field

    Hi,

    Sorry for the basic nature of this question but I’m only just finding my way in the word of WordPress coding.

    I have installed the ACF plugin on my WordPress website which is for a walking club. I have created a custom field type called walk which has custom fields such as distance, leader and meeting point. I have a page that displays brief details of each walk via the Queryloop block. I would like to add a custom field e.g display_order that could be a date or just a number and use that field to order the walks rather than order by published date.

    Here’s where my knowledge is lacking. So…

    1. Do I need to start from scratch using php/html/css etc to code the entire page that displays the brief walk details or can I tweak the code that is behind the Queryloop and retain all the layout that I already have.
    2. Where do I need put the code I create?
    3. How does the code I write get “called” on the display page?

    Any pointers would be most welcome

    Thanks Pete

  • Unread

    Question about deleting a row from repeater with acf javascript api

    Hello,

    I have the following question and have already worked out some code but it doesn’t seem to work completely.

    I have a repeater called labels and have a repeater called data_rows in this repeater there is another repeater called data.

    I would like that when I add or remove a row in the repeater labels that it also does that in every repeater data for every row in the repeater data_rows

    Now I have the adding working but when I remove one my javascript crashed.

    Does anyone have an idea how I can do this?

    Below you can find the javscript.

    Thanks in advance.


    (function($) {

    function syncDataRepeaters( type = '' ) {

    // Get the labels field using ACF's API
    const labelsField = acf.getField('field_683346e30acc7');

    if (!labelsField) {
    console.warn('Labels field not found');
    return;
    }

    const labelCount = labelsField.$rows().length;

    // Get the main repeater: data_rows
    const dataRowsField = acf.getField('field_68584dfaa3ed5');

    if (!dataRowsField) {
    console.warn('data_rows field not found');
    return;
    }

    // For each row in data_rows
    dataRowsField.$rows().each(function(index, rowEl) {
    const $row = $(rowEl);

    // console.log( 'data data_rows found', $row );

    const dataRepeaters = acf.findFields({
    key: 'field_68584e03a3ed6', // inner repeater field name
    parent: $row
    });

    dataRepeaters.each(function(index, dataItem) {

    const $el = $(dataItem);
    const dataField = acf.getField($el);

    if (!dataField) return;

    if( type === 'add' ) {

    dataField.add();

    }

    if( type === 'remove' ) {

    acf.removeAction('remove', onRemove);
    dataField.remove();
    setTimeout(() => {
    acf.addAction('remove', dataField);
    }, 50);

    }

    });

    });

    }

    // Run when new fields are added
    acf.addAction('append', function($el) {

    // Check if the appended element is your labels field (field_683346e30acc7)
    const isLabelsField = $el.closest('.acf-field[data-key="field_683346e30acc7"]').length > 0;

    if (isLabelsField) {
    syncDataRepeaters('add');
    }

    });

    function onRemove($el) {
    console.log('remove');
    console.log($el);

    const isLabelsField = $el.closest('.acf-field[data-key="field_683346e30acc7"]').length > 0;

    console.log( isLabelsField );

    if (isLabelsField) {

    setTimeout(() => {
    syncDataRepeaters('remove');
    }, 10);

    }
    }

    acf.addAction('remove', onRemove);

    })(jQuery);

  • Unread

    Image selection question

    Is there any way to do this? I am setting up database and instead of uploading each photo twice, or having to go find it in the library, is there a way to reference the existing photo?

  • Unread

    How Lighting Design Can Instantly Transform a Space (and Where to Start)

    As someone who’s worked in interiors for years, I’ve learned this: lighting isn’t just a final touch — it’s the foundation of how we feel in a space.

    Think about it. The same room can feel cozy or cold, vibrant or dull, simply by changing the type and placement of light. Yet, most people still underestimate its power.

    If you’re looking to get more intentional about lighting but don’t know where to begin, I highly recommend checking out 50bulbs.com. It’s not just a shop — it’s a curated resource filled with practical advice, inspiration, and lighting solutions that make sense for real spaces.

    From learning the difference between warm and cool tones to figuring out where to place your fixtures for maximum comfort, 50bulbs makes the process simple and approachable — no jargon, no guesswork.

    Lighting doesn’t need to be complicated. You just need the right guidance and a few smart choices. Feel free to share your favorite lighting tips, questions, or before/after photos — I’d love to see how others are using light to bring spaces to life.

  • Unread

    Update ACF field in Users table

    Hi Everyone,

    I have been racking my brain and running code via AI to try and get a resolution to what I am looking for, I have a customer that has an ACF field named assigned_rep registered in the User Table, I am trying to improve the process that is currently done when they reassign reps, currently we edit each account manually using a Gravity Forms process I have built and it works, but when they do a bulk reassingment, that is over 900 accounts to update via Gravity Forms, one user at a time.

    I have created a process that works with Posts to update an ACF field with the current assigned rep, if something changes, i update the code snippet and then I can go thru all posts pretty quick with just clicking an link on a page and it updates the post to the new assigned rep, I can get all the posts done in less than than the 900 accounts (there are over 11k posts to update when they do this reassignment.

    Below is the code that AI says will work, however when I click the update rep link I have, it never updates and debug log shows it should update to the right value.

    Any input is appreciated (you won’t hurt my feelings if you say the code is garbage)

    Thanks!


    /**
    * Updates the user meta field 'assigned_rep' based on the value in 'federal_id'.
    *
    * @param int $user_id The user ID to update
    * @return bool True if updated, false otherwise
    */
    function update_assigned_rep_based_on_federal_id($user_id) {
    // Get the federal_id from user meta
    $federal_id = get_user_meta($user_id, 'federal_id', true);

    // If federal_id is empty, use default rep
    if (empty($federal_id)) {
    $assigned_rep = '[email protected]';
    update_user_meta($user_id, 'assigned_rep', $assigned_rep);
    return true;
    }

    // Check if federal_id matches special cases (example: PA-35-050, 35-050, etc.)
    if (preg_match('/^(PA-)?35-0?(50|51)/', $federal_id)) {
    $assigned_rep = '[email protected]';
    update_user_meta($user_id, 'assigned_rep', $assigned_rep);
    return true;
    }

    // Extract the main number from federal_id (assuming format PA-XX or just numbers)
    $number = null;
    if (preg_match('/^PA-(\d+)/', $federal_id, $matches)) {
    $number = intval($matches[1]);
    } elseif (preg_match('/^(\d+)/', $federal_id, $matches)) {
    $number = intval($matches[1]);
    } else {
    // Use default if no number found
    $assigned_rep = '[email protected]';
    update_user_meta($user_id, 'assigned_rep', $assigned_rep);
    return true;
    }

    // Determine the assigned rep based on the number
    if ($number >= 1 && $number < 16) {
    $assigned_rep = '[email protected]';
    } elseif ($number >= 16 && $number < 26) {
    $assigned_rep = '[email protected]';
    } elseif ($number >= 26 && $number < 41) {
    $assigned_rep = '[email protected]';
    } elseif ($number >= 41 && $number < 47) {
    $assigned_rep = '[email protected]';
    } elseif ($number >= 47 && $number < 61) {
    $assigned_rep = '[email protected]';
    } else {
    $assigned_rep = '[email protected]';
    }

    // Update the user meta
    update_user_meta($user_id, 'assigned_rep', $assigned_rep);

    return true;
    }

  • Solving

    ACF Block Fields Not Displayed Inline in Reusable Block Editor Since WordPress 6

    Hi ACF Team,

    We’ve noticed an issue with the Reusable Blocks (wp_block post type) editor since updating to WordPress 6.8. When using ACF version 6.4.2, the custom fields for ACF blocks are no longer displayed inline within the editor. Instead, they only appear in the sidebar, which makes editing significantly more difficult and less intuitive.

    This behavior did not occur in previous versions. Specifically, when using WordPress 6.7.1 and ACF 6.3.*, the ACF block fields are still shown as expected directly inside the editor interface.

    Our questions:

    Is this a known issue with the current ACF version?

    Is there a workaround or a fix planned to restore the previous inline behavior?

    Can we assist you in reproducing or diagnosing the issue in any way?

    Thank you in advance for your support!

  • Unread

    Slowness When Editing Site Pages – Request to Disable Automatic Post Loading

    I have a significant performance issue I’m experiencing when editing my website pages. The editing process has become extremely slow, and after investigating, I’ve identified the cause as the automatic loading of posts within the editing block.

    Every time I access the editing area, a long list of posts loads automatically, which consumes a lot of resources and slows down the entire process. To streamline my workflow, I would like to find a way to disable this automatic loading.

    My preference would be for the post editing block to only display the post search field, without the list of posts appearing by default below it. This would allow me to search for and insert specific posts only when needed, without the slowness caused by loading all items.

    Is there any setting or modification I can make to implement this change? I would greatly appreciate any guidance or solution you can offer to resolve this slowness issue.

  • Helping

    How to build a custom app to sync inventory across multiple Shopify stores?

    Hey folks,

    I’m managing two Shopify stores and it’s becoming a hassle to manually sync inventory between them. I was wondering if anyone here has built a custom app for this purpose or knows how I could automate the process? I’ve read that creating a private Shopify app might be the solution.

    Also, if anyone has worked with a reliable Shopify app development company in Florida or elsewhere, I’d love a recommendation. I don’t mind paying for a quality solution, just need a team that knows Shopify inside out. Thanks!

  • Helping

    TinyMCE is not loading when set as ACF field

    I added a TinyMCE field for a page within ACF.
    When editing the page, most of the time the editor (TinyMCE) is not displayed. So I always have to switch to HTML view to see the content. When reloading the page, sometimes it works. Sometimes not.

    I am using the newest WordPress and ACF version.

    Other probably relevant plugins:

    • Autoptimize
    • Yoast
    • Query Monitor

    Query Monitor doesn’t show any errors.
    For testing purposes I deactivated Autoptimize, same issue.

    Console output:
    Console Output: Uncaught TypeError: n is null

    Debugger: // Source: wp-includes/js/tinymce/tinymce.min.js
    // 4.9.11 (2020-07-13)

    I experienced this issue on multiple sites for some time now. They all use the same Theme (own creation). Maybe it is theme related even if I have no idea how it could be?

    Thanks for your help 🙂

  • Unread

    Custom acf/load_value function issues

    I’m trying to write a custom version of the backend repeater sorting code here: https://www.advancedcustomfields.com/resources/how-to-sorting-a-repeater-field/

    I’m grabbing the repeater name and sorting field key dynamically.

    function my_acf_load_value($value, $post_id, $field, $subfield_key) {
    	return function () use ($value, $post_id, $field, $subfield_key) {
            	// vars
    		$order = array();
    
            	// bail early if no value
    		if( empty($value) ) {
    
    			return $value;
    
    		}
    
            	// populate order
    		foreach( $value as $i => $row ) {
    			$order[ $i ] = $row[$subfield_key];
    		}
    
            	// multisort
    		array_multisort( $order, SORT_DESC, $value );
    
            	// return   
    		return $value;
    	};
    }
    
    function acu_standing_order() {
    	
    	$standings_args = array(
    		'posts_per_page' => -1,
    		'post_type' => 'standings'
    	);
    
    	$standings = new WP_Query( $standings_args );
    
    	if($standings->have_posts()){
    		while($standings->have_posts()) {
    
    			$standings->the_post();
    
    			$post_id = get_the_ID();
    			
    			$fields = get_fields($post_id);
    			
    			if ($fields) {
    				foreach ($fields as $field_name => $value) {
    					// Get field object meta so we can check type
    					$field_object = get_field_object($field_name, $post_id);
    					
    					// Find repeater fields
    					if ($field_object && $field_object['type'] === 'repeater') {
    						$field_name = $field_object['name'];
    
    						if (have_rows($field_name, $post_id)) {
    							while (have_rows($field_name, $post_id)) { the_row();
    
    								// $subfield_object = get_sub_field_object('points');
    								// $subfield_key = $subfield_object['key'];
    
    								if(have_rows('points')){
    
    									// Iterate points fields
    									while(have_rows('points')) : the_row();
    										$subfield_object = get_sub_field_object('total');
    										$subfield_key = $subfield_object['key'];
    									endwhile; // points group
    
    								}
    
    							}
    						}
    
    						add_filter('acf/load_value/name=' . $field_name, my_acf_load_value($value, $post_id, $field_name, $subfield_key), 10, 3);
    					}
    				}
    			}
    		}
    	}
    }

    Currently getting the error…

    Warning: Undefined array key “field_68221235bbc48” in Path/functions.php on line 419

    So it looks like I’m getting the right key but something else is wrong.

    Help appreciated.

Viewing 25 results - 1 through 25 (of 21,345 total)