Support

Account

Home Forums Search Search Results for 'q'

Search Results for 'q'

topic

  • Unread

    PHP Warning: Attempt to read property “ID” on bool in

    Hello,

    I have an ACF field which is set to return a post object.

    It does return the object as expected however I’m getting errors in my PHP log which say PHP “Warning: Attempt to read property “ID” on bool in (the theme template file) on the line with the code requesting the ID from the object.

    The ID is actually returned despite the errors but they are really cluttering up my error log.

    The code is very basic and looks like this:

    $community = get_field(‘community’);
    $community_id = $community->ID; <– The error is shown for this line of code.

    The community field is a post object field with the Return Format set to “Post Object”.

    How can I get rid of this annoying error?

    Thanks,
    Nicole

  • Helping

    Checkboxes do not save when in a group

    I have a group called Equipment and a checkbox field called employee_devices. If I move the employee_devices field out of the group, then the checkboxes save without issue. As soon as they are within the group, they no longer will save. The plugin has the latest update as of today.

  • Unread

    New nested blocks not updated when switching to preview

    I’m experiencing an issue where when a block is initially added to an InnerBlocks area, swapping between Edit and Preview mode doesn’t trigger a re-render of the block content.

    For example, I add a quotation block to an InnerColumns area. When I switch to Edit view for that quotation block and make a change, then switch back to Preview view, the content rendered does not change. If I make that same edit via the sidebar area, it updates immediately as expected.

    Once I save that post after updating the content. The swapping between Preview and Edit work normally and the content updates. It’s only when a block is first added that the issue occurs.

    I’m using ACF 6.3.6 on WP 6.6.2

  • Unread

    Field group location rules not working??

    The website I am working on requires new customers to enter a license number on the check out page. Once they pay for a course, they will be logged in and their license number needs to reflect on their Account page. Furthermore, I need to have a field set up in the wp-admin back end that will allow admins to edit this license number on behalf of users if need be. Lastly, when users complete their courses, the license # must appear on their certificate of completion. I created a field in ACF for this function but despite these rules being in place (see below) I cannot get the license number entered on the check out page reflecting on the account page, the certificate, or the admin side (when a user enters a license # at check out, admin should be able to see what they entered via the “users” area of WordPress). The field on the check out page for the license number was set up through the WooCommerce check out fields area. Am I missing something here with these rules? I’ve tried the rules shown below, plus many other variations yet I’m not getting the desired results. Any feedback is much appreciated, thank you.

    Field type is “Text area”.
    Settings > Location Rules, set up is as follows:

    Rules
    Show this field group if
    Current user role is equal to administrator AND
    Current user is equal to Viewing back end
    OR
    Current user is equal to Logged in
    OR
    Page is equal to My Courses AND
    Current user role is equal to Customer
    OR
    Page is equal to Checkout

  • Helping

    Meta query with ACF subfields (populated by Formidable Forms)

    Hi,
    I found other topics about this issue but after trying all the solutions available, I am still stuck.

    I use Formidable Forms and their add-on Formidable ACF to create posts. It works like a charm with all kind of fields.
    But when I try to do a meta query using a subfield of an ACF repeater field group (which is populated through a Formidable Form) to find some posts, it doesn’t work.

    I use the example : https://www.advancedcustomfields.com/resources/query-posts-custom-fields/#4-sub-custom-field-values

    But my query always returns nothing ( var_dump gives array(0) { } ).
    ———-
    My code :
    function my_posts_where( $where ) {

    $where = str_replace(“meta_key = ‘essai_centres_investigateurs_$”, “meta_key LIKE ‘essai_centres_investigateurs_%”, $where);
    return $where;
    }
    add_filter(‘posts_where’, ‘my_posts_where’);

    $essais = get_posts(array(
    ‘post_type’ => ‘essai_clinique’,
    ‘post_status’ => ‘publish’,
    ‘posts_per_page’ => -1,
    ‘suppress_filters’ => false,
    ‘meta_query’ => array(
    array(
    ‘key’ => ‘essai_centres_investigateurs_$_essai_centre_investigateur’,
    ‘value’ => 1695, // value to search
    ‘compare’ => ‘=’,
    ),
    ),
    ));
    ———-

    Any help would be greatly appreciated as I am becoming mad ! 🙂
    Best Regards,
    Cedric

  • Unread

    I haven’t seen the “toggle all” option

    ACF field type is taxonomy, and appearance type is a checkbox, but I haven’t seen the “toggle all” option for this field. I really required toggle all option for this field.

  • Helping

    Woocommerce order exports variable products

    Hello everyone.

    I urgently need help and am looking for an ingenious idea for the following problem: How can I retrieve ACF information for variable products when exporting orders from Woocommerce?

    Details:

    > Orders should be exported from Woocommerce with the plugin “WP ALL EXPORT PRO” and ACF to my fulfillment partner as XML
    > ONLY relevant orders or products with necessary information should be filtered, which works well for “simple products” with the following code
    > Variable products (T-shirts) are also correctly recognized and exported by the code – BUT all ACF information remains empty and is not retrieved

    What have I created?

    > Created variable product “T-SHIRT” in the Woocommerce Dashboard
    > Woocommerce attribute “SIZE” with the variants S / M / L / XL
    > ACF field group “DDF” with desired text fields created to export the necessary ACF information later for orders (in addition to simple products also for product variants e.g. T-SHIRT, SIZE “L”)
    > Field group rule: content type -> is equal to -> product
    > Do I also have to apply the rule here? Taxonomy -> is equal to -> “SIZE”

    Do I have to add or create other settings in ACF?
    or is this only possible with ACF Pro?

    ->

    /////CURRENT STATUS CODE IN WP ALL EXPORT

    //////XML EDITOR

    <?xml version="1.0" encoding="UTF-8"?>
    <orders>
    	<!-- BEGIN LOOP -->
    	<order>
    		<commission>{Bestell ID}</commission>
    		<production>2</production>
    
    		<receiver>
    			<line1>{Shipping First Name} {Shipping Last Name}</line1>
    			<line2>{Shipping Company}</line2>
    			<street>{Shipping Address 1}</street>
    			<streetnumber>{Shipping Address 2}</streetnumber>
    			<country_code>{Shipping Country}</country_code>
    			<zip>{Shipping Postcode}</zip>
    			<city>{Shipping City}</city>
    			<email>{Customer Account Email Address}</email>
    
    		</receiver>	
    
    		<items>	
    			[my_get_order_items({Bestell ID})]
    		</items>
    	</order>
    	<!-- END LOOP -->
    </orders>

    /////FUNCTION EDITOR

    <?php
    
    function my_get_order_items($Bestell_id) {
        // Check if the Bestell ID is valid
        if (!$Bestell_id) {
            return false;
        }
    	
        // Fetch the order
        $order = wc_get_order($Bestell_id);
        if (!$order) {
            return false;
        }
    
        // Initialize the string to store order details
        $order_details = "";
    
        // Loop through each order item
        foreach ($order->get_items() as $item_id => $item) {
            // Get the product object
            $product = $item->get_product();
    
            // Skip if there's no product associated with the item
            if (!$product) 
    		{ continue; }
    		
    		
    		if (!(
    strpos($item->get_name(), 'KERAMIKTASSE') !== false ||
    strpos($item->get_name(), 'BAUMWOLLTASCHE') !== false ||
    strpos($item->get_name(), 'T-SHIRT') !== false))
    { continue; }
    		
    		$order_details .= "**LT**item**GT**";
    		$order_details .= "**LT**ID**GT**" . $product->get_sku() . "**LT**/ID**GT**";
    		$order_details .= "**LT**produktname**GT**" . $item->get_name() . "**LT**/produktname**GT**";
    		$order_details .= "**LT**amount**GT**" . $item->get_quantity() . "**LT**/amount**GT**";
    		$order_details .= "**LT**upload**GT**" . maybe_serialize( get_field( 'upload', $product->get_id() ) ) . "**LT**/upload**GT**";
    		$order_details .= "**LT**size**GT**" . maybe_serialize( get_field( 'size', $product->get_id() ) ) . "**LT**/size**GT**";
    		$order_details .= "**LT**groesse**GT**" . maybe_serialize( get_field( 'produktgröße', $product->get_id() ) )  . "**LT**/groesse**GT**";
    		$order_details .= "**LT**material**GT**" . maybe_serialize( get_field( 'material', $product->get_id() ) ) . "**LT**/material**GT**";
    		$order_details .= "**LT**print**GT**" . maybe_serialize( get_field( 'print', $product->get_id() ) ) . "**LT**/print**GT**";
    		$order_details .= "**LT**variante**GT**" . maybe_serialize( get_field( 'variante', $product->get_id() ) ) . "**LT**/variante**GT**";
    		$order_details .= "**LT**category**GT**" . maybe_serialize( get_field( 'category', $product->get_id() ) ) . "**LT**/category**GT**";
    		
    		 //add options to the output
            $order_details .= "**LT**Options**GT**";
                $order_details .= "**LT**Option**GT****LT**ID**GT**" . "1996" . "**LT**/ID**GT****LT**Value**GT**" . maybe_serialize( get_field( 'value_115', $product->get_id() ) ) . "**LT**/Value**GT****LT**/Option**GT**";
    		
    		    $order_details .= "**LT**Option**GT****LT**ID**GT**" . "2489" . "**LT**/ID**GT****LT**Value**GT**" . maybe_serialize( get_field( 'value_117', $product->get_id() ) ) . "**LT**/Value**GT****LT**/Option**GT**";
    		
    		   	$order_details .= "**LT**Option**GT****LT**ID**GT**" . "2056" . "**LT**/ID**GT****LT**Value**GT**" . maybe_serialize( get_field( 'value_118', $product->get_id() ) ) . "**LT**/Value**GT****LT**/Option**GT**";
    		
            $order_details .= "**LT**/Options**GT**";
            
    		$order_details .= "**LT**/item**GT**";
    		
        }
    
        return $order_details;
    }
    
    ?>

    ->

    Does anyone have an idea?

    Many thanks.

  • Unread

    How to Create a Dynamic Table of Contents (TOC) for ACF Flexible Content in Word

    I’m working on a WordPress site where I’m using Advanced Custom Fields (ACF) to create a complex layout for my posts. Specifically, I’m using the ACF Flexible Content field to structure my posts with various layouts, including headings. Here’s what I’ve done so far and where I’m running into difficulties:

    #### What I’ve Done:

    1. **ACF Setup**:

    – I’m using a Flexible Content field in ACF called “Contenu flexible” with the field name contenu_flexible_custom.
    – One of the layouts within this Flexible Content field is titre_h2, which contains the headings I want to include in the Table of Contents (TOC).

    2. **TOC Attempt**:

    – I tried using the block_editor_settings_all filter to generate anchors for the headings automatically in the Gutenberg editor:

    `php
    add_filter(
    ‘block_editor_settings_all’,
    static function( $settings ) {
    $settings[‘generateAnchors’] = true;
    return $settings;
    }
    );
    `

    – However, this didn’t seem to work with my ACF Flexible Content setup, as the TOC wasn’t generated correctly.

    3. **Custom PHP Code**:

    – I wrote a custom PHP function to loop through the ACF Flexible Content field and manually create a TOC:

    `php
    function generate_acf_flexible_toc() {
    $toc = ‘<div class=”custom-toc”><h2>Table of Contents</h2><ul>’;
    $content_found = false;

    // Check if the flexible content field has rows of data
    if( have_rows(‘contenu_flexible_custom’) ) {
    // Loop through the rows of data
    while ( have_rows(‘contenu_flexible_custom’) ) : the_row();

    // Check for the ‘titre_h2’ layout which contains the headings
    if( get_row_layout() == ‘titre_h2’ ) {
    $heading = get_sub_field(‘titre_h2’); // Field containing the heading text
    if ($heading) {
    // Create a unique ID for each heading
    $id = sanitize_title($heading);
    $toc .= ‘<li><a href=”#’ . esc_attr($id) . ‘”>’ . esc_html($heading) . ‘</a></li>’;

    // Output the heading with an ID in the content
    echo ‘<h2 id=”‘ . esc_attr($id) . ‘”>’ . esc_html($heading) . ‘</h2>’;
    $content_found = true;
    }
    }

    endwhile;
    }

    $toc .= ‘</ul></div>’;

    // Return the TOC only if content is found
    if ($content_found) {
    return $toc;
    }
    return ”;
    }

    function add_acf_flexible_toc_to_content( $content ) {
    // Only prepend the TOC if it’s a standard post
    if ( is_singular(‘post’) ) {
    return generate_acf_flexible_toc() . $content;
    }
    return $content;
    }

    add_filter( ‘the_content’, ‘add_acf_flexible_toc_to_content’ );
    `

    – This function is meant to generate a TOC from the headings in the titre_h2 layout and prepend it to the post content.

    #### The Issue:

    – The TOC doesn’t seem to generate correctly using the native method or TOC plugins since the headings are part of the ACF Flexible Content and not in the standard post content.
    – I need a solution to dynamically generate a TOC for posts using ACF Flexible Content fields, specifically targeting the titre_h2 layout.

    #### What I’m Looking For:

    – Is there a better way to generate a TOC dynamically for ACF Flexible Content fields?
    – How can I ensure the TOC includes headings from specific layouts in my Flexible Content field?
    – Any suggestions or best practices for integrating a TOC with ACF, especially when using custom layouts?

    Thanks in advance for any help or guidance you can provide!

  • Unread

    Block editor iframed and metabox

    Hello !

    I am a happy early user of ACF and this is the first time I’m asking for your help!

    I started my latest project with the block editor in API v3.
    I have the editor in iframe mode (important to have an exact rendering with media queries) on my pages, but not on my custom post types.

    After investigating, I found that shouldIframe() in edit-post.js ( line 2613 ) returns false because of metaboxes : hasMetaBoxes() return true ( line 1175 )!
    These metaboxes come from settings added to the custom post type via ACF in the sidebar.

    I don’t see any other way to add parameters to the post itself except through custom fields, and therefore via a metabox…

    Am I the only one experiencing this? Is there no alternative?

    Thanks in advance!

  • Unread

    Render CPT with ACF in Post Object field backend

    Hello, I have a CPT with ACF fields. I than use the Post Object field within pages to select this CPT. Using the following function I always was able to display / preview some of the ACF fields within that CPT: title, image and year.
    Since the latest updates I just see html instead of a render of the actual CPT ACF content.

    How can I change this function for it to work? Thanks in advance!

    
    function post_object_with_avatar( $title, $post, $field, $post_id ) {
    
      	$post_thumbnail_url = get_field('portfolio_item_image',$post->ID);
    	$year = get_field('portfolio_item_year',$post->ID);
    	$dimensions_height = get_sub_field('portfolio_item_height',$post->ID);
    	$dimensions_width = get_sub_field('portfolio_item_width',$post->ID);
      	$avatar = '<div class="post_ava_prefilter_wrapper" title="'.$title.'">';
        $avatar .= '<div class="ava_prefilter_wrapper"><img src="'.$post_thumbnail_url.'" /></div>'."<b>$title</b>"."<br>"."$year"."<br>"."$dimensions_height";
      	$avatar .= '</div>';
      return $avatar;
    }
    
    add_filter('acf/fields/post_object/result/key=field_636bXXX', 'post_object_with_avatar', 10, 4);	/* Portfolio-1-a */
    add_filter('acf/fields/post_object/result/key=field_6344XXX', 'post_object_with_avatar', 10, 4);	/* Portfolio-2-a */
    add_filter('acf/fields/post_object/result/key=field_6344XXX', 'post_object_with_avatar', 10, 4);	/* Portfolio-2-b */
    add_filter('acf/fields/post_object/result/key=field_6344XXX', 'post_object_with_avatar', 10, 4);	/* Portfolio-3-a */
    add_filter('acf/fields/post_object/result/key=field_6324XXX', 'post_object_with_avatar', 10, 4);	/* Portfolio-3-b */
    add_filter('acf/fields/post_object/result/key=field_6344XXX', 'post_object_with_avatar', 10, 4);	/* Portfolio-3-c */
    add_filter('acf/fields/post_object/result/key=field_634bXXX', 'post_object_with_avatar', 10, 4);	/* Portfolio-4-a */
    add_filter('acf/fields/post_object/result/key=field_634bXXX', 'post_object_with_avatar', 10, 4);	/* Portfolio-4-b */
    add_filter('acf/fields/post_object/result/key=field_634bXXX', 'post_object_with_avatar', 10, 4);	/* Portfolio-4-c */
    add_filter('acf/fields/post_object/result/key=field_634bXXX', 'post_object_with_avatar', 10, 4);	/* Portfolio-4-d */
    
  • Unread

    No styling attributes when you use acf_register_block_type()

    In my code I use the following function to register my ACF blocks:

    
    acf_register_block_type($args);
    

    $args in this case is an array based on a .json file. I like using this function because with this I am able to modify the array as I like it (e.g. translating title and description).
    I also have the following code in my array:

    
    "attributes": {
       "style": {
          "type": "object",
          "default": {
            "color": {
              "background": "var(--wp--preset--color--button-primary-initial-background)"
            },
            "spacing": {
              "margin": {
                "top" : "var(--wp--preset--spacing--30)"
              }
            }
          }
        }
      },
    

    But I found out that the “style” attribute is ‘removed’ (read: not added) by the ACF plugin whenever I use acf_register_block_type(). After some digging I found a function called acf_get_block_type_default_attributes() in the file /advanced-custom-fields-pro/pro/blocks.php on line 310 that completely replaced the ‘attributes’ of my original array.

    Unfortunately this function does not contain any hooks (actions/filters) to modify this array. How can I still get the attribute ‘style’ to work with acf_register_block_type()?

  • Unread

    The Role of Random Data Generators in Modern Computing

    Random data generators play a crucial role in various fields of modern computing, from software testing to cryptography. At their core, these generators produce sequences of numbers or characters that appear unpredictable or random. In software development, they are essential for testing applications under a wide range of scenarios. By simulating different inputs, developers can identify bugs and vulnerabilities that might not surface under typical conditions. Similarly, random data generators are invaluable in fields like machine learning, where they help create diverse datasets to train algorithms effectively.

    In addition to software testing, random data generators are foundational in cryptography, where they ensure data security and privacy. Cryptographic algorithms rely on randomness to generate secure encryption keys, making it nearly impossible for malicious actors to predict or recreate these keys. Without high-quality random data, the security of encrypted communications and data storage could be compromised. To achieve the necessary level of unpredictability, modern random data generators often use hardware-based random number generators that take advantage of natural entropy sources, such as electronic noise.

    Moreover, random data generators find applications beyond technical fields, influencing areas like finance and scientific research. For example, in financial modeling, random data simulates market conditions, helping analysts predict future trends and assess risk. In scientific experiments, particularly those involving Monte Carlo simulations, randomness is used to model complex systems and predict their behavior over time. As technology advances, the demand for robust random data generators continues to grow, underscoring their importance across diverse domains.

  • Helping

    Field type selection and performance

    I have a custom post type with ACF fields that will be populated with an import from a .csv file. A large number of fields were supplied as yes/no (true/false) fields. There are approximately 30 fields that were supplied in the .csv file. For example, assume this data was supplied for a single custom post type:

    Red: yes
    Blue: no
    Yellow: yes
    Green: no
    Orange: yes
    Purple: yes
    Black: no
    White: no
    Aqua: no
    Pink: no
    Gray: yes
    etc….

    Question – From a performance aspect, would it be better to convert these fields to a checkbox type instead of using true/false fields? The data will be output using a WP Template file (with the GeneratePress theme).

    If there is a performance boost from using a Checkbox instead of a True/False field, I can pre-process the .csv file prior to the import to convert the data to a string instead of yes/no.

    That is the data snippet above would be changed to a single field of ‘Colors’ and imported into an ACF Checkbox with the individual colors as the choices. The corresponding .csv for the colors above would be converted to:

    Colors: ‘Red,Yellow,Orange,Purple,Gray’

    My assumption is making a query for a single checkbox type would be faster than a query for 30 individual true/false fields.

    thanks, -s

  • Helping

    Tracking Downloads Via Google Analytics

    We want to track file downloads using Google Analytics.

    Right now we have a form set up that lets users upload a file.

    That is working fine.

    But to track downloads of that file via GA, we need some sort of unique id for each file as our site has about 50 users.

    We’d like to place a unique id in the url to track the file download.

    It could be the organization name like this:

    http://www.oursite.com/dallascowboys/pdfdownload.pdf

    or we could use some sort of unique id in the url like this:

    http://www.oursite.com/pdfdownload.pdf?id=3493 (an organization or user id for the dallascowboys)

    Those are the initial ideas we came up with.

    With either of those in place we could then filter our reports in GA to only show the downloads for the dallascowboys.

    We are open to any other ideas to do this via GA.

    With the above two examples we would to either:

    – force the uploads into a unique directory for each user (uploads/dallascowboys)
    – or append the file url with the id

    Anyone have any ideas about how to do this via ACF?

  • Solved

    Set Post Title on ACF Form Submit

    I have an ACF form on the front end that creates an entry for a custom post type. I don’t want to show the post title field for the user to edit, but I want to set it to something like “News Item 123456” when the form is submitted, where 123456 uses time(). Below is my code for showing/submitting the form which does work.

    <?php
    // Show ACF Form On Front End Via ShortCode
    
    // acf_form_head(); added to header.php
    
    // Function for the shortcode
    function bwp_acf_form_function($attr) {
    
    // If ACF isn't running then exit
    if (!function_exists('acf_form')) {
    return;
    }
    
    // Buffer data instead of outputting it
    ob_start();
    
    // Unique form ID to avoid conflicts
    $form_id = 'bwp-acf-form-' . uniqid();
    
    // Debug: Log form ID and request data
    error_log('Rendering ACF Form with ID: ' . $form_id);
    error_log('Request data: ' . print_r($_REQUEST, true));
    
    // Display ACF form
    acf_form(array(
    'id' => $form_id,
    'post_id' => 'new_post',
    'new_post' => array(
    'post_type' => 'daily-message',
    'post_status' => 'draft',
    ),
    'field_groups' => array($attr['field_group_id']),
    'post_title' => false, // False to auto-populate
    'post_content' => false, // False to not use for content
    'submit_value' => __("Add CSCC Daily Messenger Info", 'acf'),
    'updated_message' => __("Daily Messenger Post Added", 'acf'),
    'return' => '', // Redirect URL after saving (empty string means no redirect)
    'html_after_fields'=> '<input type="hidden" name="my_form_nonce" value="' . wp_create_nonce('my_form_nonce_action') . '">', // Add nonce for security
    ));
    
    // Empty the buffer data
    return ob_get_clean();
    }
    
    // Add the shortcode
    add_shortcode('bwp_acf_form', 'bwp_acf_form_function');
    
    ?>
  • Unread

    acf/fields/post_object/query filter

    Hi all,

    I have an ACF frontend form which creates a new post

    acf_form( array(
    								'id'			=> 'edit-survey',
    								'field_groups'	=> array( 53 ),
    								'post_id'		=> absint( $_GET['survey'] ),
    								'return'		=> add_query_arg( 'survey', '%post_id%', get_the_permalink() ),
    								'submit_value'	=> 'Save Survey',
    							)
    						);

    I am then trying to filter the POST OBJECT field within the field_group 53. But when I try to use $post_id I am only getting ‘new_post’ returned and not the actual $post_id.

    The code I am using:

    add_filter( 'acf/fields/post_object/query/name=survey_id', function( $args, $field, $post_id ) {
    $args['meta_query'] = array(
    array(
    'key'		=> 'user_id',
    'value'		=> get_current_user_id(),
    'compare'	=> '=',
    ),
    array(
    'key'		=> '_parent_survey',
    'value'		=> $post_id, // << RETURNING 'new_post'
    'compare'	=> '=',
    ),
    );
    return $args;
    }, 10, 3 );

    Any suggestions? 🙂

    Many thanks

    EDIT: Code formatting didnt work when posting so I removed tabs.

  • Solved

    ACF Front End Form Posting Twice

    I have a fresh WP install and am working with an ACF front end form (I’ve used ACF before but this is my first time using a front end ACF form). Everything is working but it’s posting twice.

    I’m adding the code via a custom plugin I created just for this, using a shortcode on the page. Below is the code I am using that posts the entry twice. Any ideas what could be causing this?

    <?php
    // Show ACF Form On Front End Via ShortCode
    // Info from this video: https://www.youtube.com/watch?v=MSIc7rnZ2U0

    // Code to show form
    add_action('init', 'brandpage_form_head');
    function brandpage_form_head() {
    acf_form_head();
    }

    // Function for the shortcode
    function bwp_acf_form_function($attr) {

    // If ACF isn't running then exit
    if (!function_exists('acf_form')) {
    return;
    }

    // Buffer data instead of outputting it
    ob_start();

    // Unique form ID to avoid conflicts
    $form_id = 'bwp-acf-form-' . uniqid();

    // Debug: Log form ID and request data
    error_log('Rendering ACF Form with ID: ' . $form_id);
    error_log('Request data: ' . print_r($_REQUEST, true));

    // Display ACF form
    acf_form(array(
    'id' => $form_id,
    'post_id' => 'new_post',
    'new_post' => array(
    'post_type' => 'daily-message',
    'post_status' => 'draft',
    ),
    'field_groups' => array($attr['field_group_id']),
    'post_title' => false, // False to auto-populate
    'post_content' => false, // False to not use for content
    'submit_value' => __("Add CSCC Daily Messenger Info", 'acf'),
    'updated_message' => __("Daily Messenger Post Added", 'acf'),
    'return' => '', // Redirect URL after saving (empty string means no redirect)
    'html_after_fields'=> '<input type="hidden" name="my_form_nonce" value="' . wp_create_nonce('my_form_nonce_action') . '">', // Add nonce for security
    ));

    // Empty the buffer data
    return ob_get_clean();
    }

    // Add the shortcode
    add_shortcode('bwp_acf_form', 'bwp_acf_form_function');

    ?>

  • Unread

    Migration to move fields into group to adhere to new ACF structure

    Hi!

    I’m hoping to create a one-time-use PHP script to update ACF data belonging to blocks, in a number of posts on a site I’m working on. The block in question has a repeater field with three fields, and I want that to be moved into a group.

    Repeater field name: ‘rep_items’
    Repeater subfields: ‘heading’ (Text), ‘content’ (Wysiwyg), ‘image’ (Image)
    New group name: ‘acc_content’

    The overall ACF field group has been updated, using drag-and-drop to move the existing repeater into the group. I have a high number of populated blocks across pages and posts in the site, which is why I’m very keen to use a script for this; I also hope to leverage it in future for similar tasks, so this is a learning experience too.

    The issue I’m having is that it seems quite difficult to rearrange the data in this way. If I use parse_blocks() on my post->post_content, find the blocks I’m looking to modify, and examine block[‘attrs’][‘data’], the repeater’s content seems to be deconstructed and sits at the root level, with key string names that are indicative of the structure I’d expect to see when working at the post-meta level. I think I understand now that this is serialised for storage against Gutenberg blocks, and this might not happen if I were looking at a post’s ACF fields.

    I’ve examined this same data on a block populated using my updated structure with the repeater inside a group, and I can see that the repeater field names are prefixed with the group, but not in a way that I believe can be parsed safely by ACF without reference to other fields. The data looks like this:

    acc_content_rep_items_0_heading: "Title 1"
    _acc_content_rep_items_0_heading: "field_somefieldid"
    acc_content_rep_items_0_image: "625"
    _acc_content_rep_items_0_image: "field_somefieldid"
    acc_content_rep_items_1_heading: "Title 2"
    _acc_content_rep_items_1_heading: "field_somefieldid"

    There are also fields “acc_content” and “_acc_content”, which obviously represent the group. I can almost see the connections here, but I’m not certain on them.

    This is what the content looks like when it IS adhering to the new structure, of course. What I want to do is migrate the data that doesn’t reference the ‘acc_content’ group. It won’t be sufficient to just build a fallback into my block’s PHP to find the old structure and render it; I want content authors to be able to go into blocks populated in the old structure, and see the content, not to have it hidden in legacy fields in the DB that are supported as a patch.

    I feel as though, in the migration script, I may need to query the ACF field group definition – as opposed to just playing blindly with the data – if for no other reason than to know what field_ID to insert for the group. Or maybe I need to just go to my ACF field group’s JSON, take that field_ID, and manually add it and all the other internal, underscore_prefixed fields and construct this the hard way.

    Are there any tricks or ACF library utility methods that I can employ to make this process easier for myself? What are your thoughts on doing this, generally?

    Thanks for any assistance you can provide.

  • Unread

    get_object returns illogical JSON object instead of key/value

    I recently cloned my existing database into a development site, and have been stung by a bug that I can’t reproduce in the production environment. Current WordPress v6.6.1, ACF PRO plugin v6.3.5.

    A custom field whose values appear totally normal on the front end, but get_object returns a totally illogical JSON object instead of a value.

    Array
    (
        [0] => Array
            (
                [value] => s:68:"a:2:{s:5:"value";s:11:"city-living";s:5:"label";s:11:"City Living";}";
                [label] => s:68:"a:2:{s:5:"value";s:11:"city-living";s:5:"label";s:11:"City Living";}";
            )
    )

    The exact same code works on the production site! A screenshot of the field group configuration is attached. It looks totally normal.

    The code snippet from the page template is:

    <?php
    $location_types = get_field('type_of_location');
    print_r($location_types);
    if ($location_types) :
        foreach ($location_types as $location_type) { ?>
        <p><span><img />.png">  </span><span><?php echo $location_type['label'] ?></span></p>
    <? }
        endif;
    ?>

    Can anyone help me figure out why this wouldn’t work and/or troubleshoot how the field group somehow is set up incorrectly in the database, but looks fine on the front end?

    I’d be delighted for this to be something dumb, but I doubt it.

    Thank you all!

  • Helping

    Link Field: Insert/Edit Link Submits Post

    I have a custom post-type with a number of required fields, including a few link fields.

    For any of these link fields, when I click Select Link, enter a URL, and then click ‘Add Link’ (which is a submit input within the modal popup), it appears that it tries to submit/publish the entire post. The posts’s ‘Publish’ button greys-out, a loading spinner appears, and after a few seconds, validation messages appear for all other required fields.

    The same does not seem to occur if I first enter data into the required fields, however for content authors this is an undesirable experience for them and I am hoping to track down information on how I might prevent this from happening.

    I have tried this on several websites which I work on and the same things seems to happen.

  • Unread

    Ajax issues with FSE archive template

    Hi,
    I’m creating a generic load more system in a website for one of my client.
    The configuration of the system is done by ACF fields in a custom block. The global functioning is as follow:
    In the block settings you can:

    • set the post type to show
    • set a possible filter: either an interactive filter (a drop) or a fixed filter (archive)
    • the taxonomy associated to the filter
    • some other random settings (by page, etc.)

    In a page context, I have no issue. I send the page ID to the back and get_fields() works like a charm to force the desired configuration and return the new posts to load on front.
    But where I have an issue, it’s in a FSE template context.
    When I create a template for a taxonomy archive in the FSE Editor, ACF seems to save the fields value in the template’s post_content. And in this contexte I cannot fetch the fields values via get_fields() on back. I tried sending the get_the_ID(), get_queried_object_id(), etc. Nothing. ACF cannot recover the fields set in the FSE template.

    Is there a way to do this? As I do not want to send the post-type / taxonomy via ajax (and thus stored in the DOM) for security issues.

    Thank you.

  • Unread

    Groups and custom columns when filtering

    FYI, some info about Groups and custom columns when filtering. It seems retrieving the Group values won’t work when the admin listings page gets filtered, because that’s creating a ‘post’ and not a ‘get’. Here is the code that i had (which worked great when the listings page rendered:

    			// Display the value of the custom fields in the custom columns
    			public function display_custom_column_content($column_name, $post_id) {
    					$general_info = get_field('general_info', $post_id);
    
    					switch ($column_name) {
    							case 'bedrooms':
    									$value = $general_info['bedrooms'];
    									echo $value ? esc_html($value) : '-';
    									break;
    							case 'bathrooms':
    									$value = $general_info['bathrooms'];
    									echo $value ? esc_html($value) : '-';
    									break;
    							case 'size':
    									$value = $general_info['size'];
    									echo $value ? esc_html(number_format($value) . ' sq. ft.') : '-';
    									break;
    							case 'lot_size':
    									$value = $general_info['lot_size'];
    									echo $value ? esc_html(number_format($value) . ' sq. ft.') : '-';
    									break;
    							case 'price':
    									$value = $general_info['price'];
    									echo $value ? esc_html('$' . number_format($value, 0, '.', ',')) : '-';
    									break;
    							default:
    									echo '-';
    									break;
    					}
    			}

    And here is the solution (which is to use get_post_meta with the proper field name of having the group field name precede the sub field name. Here is the updated code that worked for me:

    			// Display the value of the custom fields in the custom columns
    			public function display_custom_column_content($column_name, $post_id) {
    
    					switch ($column_name) {
    							case 'bedrooms':
    									$value = get_post_meta($post_id, 'general_info_bedrooms', true);;
    									echo $value ? esc_html($value) : '-';
    									break;
    							case 'bathrooms':
    									$value = get_post_meta($post_id, 'general_info_bathrooms', true);;
    									echo $value ? esc_html($value) : '-';
    									break;
    							case 'size':
    									$value = get_post_meta($post_id, 'general_info_size', true);
    									echo $value ? esc_html(number_format($value) . ' sq. ft.') : '-';
    									break;
    							case 'lot_size':
    									$value = get_post_meta($post_id, 'general_info_lot_size', true);
    									echo $value ? esc_html(number_format($value) . ' sq. ft.') : '-';
    									break;
    							case 'price':
    									$value = get_post_meta($post_id, 'general_info_price', true);
    									echo $value ? esc_html('$' . number_format($value, 0, '.', ',')) : '-';
    									break;
    							default:
    									echo '-';
    									break;
    					}
    			}
  • Solving

    Force Select Field Choices (Repeater) to Appear in Alphabetical Order

    Hi,

    I’ve searched everywhere and went through all the topics and replies including this one (https://support.advancedcustomfields.com/forums/topic/sort-asc-a-select-field-in-backend/) but can’t seem to find the solution I’m looking for.

    I have the following scenario and would like to force the select field/choices to appear in alphabetical order in both frontend (output) and the page editor (refresh order of existing rows after updating). The choices in the backend will be input in the correct order manually but I wouldn’t mind if that could be re-sorted automatically as well.

    – Field Group: Field Type “Repeater”
    – Sub Field 1: Field Type “Select” [countries dropdown]
    – Sub Field 2: Field Type “Number” [manual entry]

    Currently the output looks something like the following example, depending on the order the rows were created:

    United States 44 [entered 1st]
    Australia 18 [entered 2nd]
    China 27 [entered 3rd]

    However I require the table to display alphabetically (ASC) at all times, no matter the text value or what row was created first:

    Australia 18 [entered 2nd]
    China 27 [entered 3rd]
    United States 44 [entered 1st]

    Any help is much appreciated!

    Thanks.

  • Unread

    Linking forms with different constraints

    Hello everybody,

    As part of an optimization of procedures, I am looking to link three forms created with ACF and coupled with Advanced Custom Fields: Extended for the creation of custom post types (CPT) where data needs to be “forced”.

    Form 1: Team Creation
    I have a CPT “teams” that records data from a “team creation” form containing a group of “teams” fields which. In this form, partners are asked to create a team. Two actions are linked to the submission of the questionnaire: a user action where a user is created and an article action where an article is created and inserted into the CPT “teams”.

    Form 2: Individual Registration
    I have a CPT “cyclist” that records data from an “individual registration” form containing a group of “registered” fields where we ask, among other things, to select a team created by the previous form. Two actions are linked to the submission of the questionnaire: a user action where a user is created and an article action where an article is created and inserted into the CPT “cyclist”.

    In my group of “registered” fields, I have a “team” field of type “post object” filtered on the “team” post type, which allows me, in the form, to enable the selection of a previously created team via a dropdown list. (I couldn’t get a dropdown list using a “relationship” field). At this stage, I encounter two difficulties. First, a user can link to multiple teams if they fill out the registration form several times. Second, if anyone erase an account, it doesn’t erase the content in the CPT “cyclist”.

    => How can I ensure that a user cannot fill out a registration form a second time? Is it possible (via the back office rather than through code) to make sure that an individual who wants to re-register with the same email address is refused a new registration?

    Form 3 : Creation of a Trip Form
    I have a CPT “trips” that records data from a “completed trips” form containing a group of “trip” fields.

    Here, I would like:

    The form to be filled out only by cyclists who have previously registered;

    The form to display two non-editable fields:

    A “cyclist” field which would be the concatenation of the “first name” and “last name” fields (display name in database) filled in via the “individual registration” form.
    The “team” field that was selected via the “individual registration” form.

    I imagine there is a link with “acf/save_post” but I do not understand how to use it or if this action is available in the backoffice user interface, without coding.

    The cyclist to be able to add trips as they complete them. I imagine a repeater will be needed but I do not yet know how to exploit it.

    I would appreciate some help as I am a beginner and not very comfortable with code. I can’t find anything conclusive in my research, because I don’t understand where I have to put the codes I found (function.php from the child theme ?).

    Thank you in advance for any help you could give me, mainly if this help is brought with step by step explanations.

  • Unread

    ACF Post Query with relationship showing 1 despite despite being 0

    I have created a custom post type with a relationship connected to another custom post type.

    Inside a query I have a count for the relationship field to show the total number of posts that have been selected. I thought at first it was working fine until I remove a post from the relationship and it still shows 1 instead of 0

    $posts = new WP_Query( 
        array(
            'post_type'     => 'group-clients',
            'post_status'   => 'publish',
            'orderby'       => '',
            'order'         => 'asc'
        ) 
    );
    $posts = $posts->get_posts();
    if ($posts) {
        foreach( $posts as $post ) { ?>    
            <div class="p-4">
                <?php the_title() ?>
            </div>
            <div class="p-4">
                <?php 
                    $properties = count( (array) get_field('properties') ); 
                    if($properties) {
                        echo $properties;
                    } else {
                        echo '0';
                    }
                ?>
            </div>                
        <?php
        }
    }
    wp_reset_postdata();

    Can anyone work out why?

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