Support

Account

Home Forums Search Search Results for 'remove comma'

Search Results for 'remove comma'

topic

  • Solving

    Check Box Output Commas

    Hi, I have read many answers about using “implode” to solve the issue about arrays and commas. Those where applied on a template file or code. But my case is that I am calling the value via [acf field="myfield"], which is inserted on a WordPress Post.

    I was able to create and display the value, however, the outcome shows a comma right after each value. How can I remove it, or is there any other way to do it other than CheckBox? Here is an example of my output:

    This is sentence one.,
    This is sentence two.,
    This is sentence three.

    How can I remove those commas?

    Thanks in advanced.
    Russ

  • Solved

    Change Repeater to ul and remove “,” separator

    I want to remove the comma separator and make each name/object in the repeater field separated per line. Is that possible to do?

  • Solving

    Block preview is wrapped in “extra” div (same classes), affects appearance

    I would love to hear some thoughts on this one.

    I have multiple blocks on which I have a custom field for adding width classes to the block (I don’t like Gutenbergs approach, I need my own). The selected class is appended to the blocks other regular css classes on the object.

    On my ACF blocks I use get_block_wrapper_attributes() to get the classes and then add them to a wrapper div. Apparently these classes is also added to the preview wrapping div in admin which means I get a double effect of my css rules.

    It removes the attribute classes on the inner div whenever clicking on the block but it’s back again whenever I reload the page.

    Anyone got a clue on why this happens and how I can solve it (my soultion mught be bad, I’m of course open for other totally different solutions)? This worked fine, as far as I know, before the summer (just got back to work and discovered this after updating WP 6.2.2 -> 6.3. and ACF 6.1.7 -> 6.2.0).

    Preferably I would not want these classes on the preview wrapping div, however they should in that case not be removed on the inner div when clicking on the preview.

    Double width classes creates double distance from the edges

    Same classes added to both parent and child div in preview mode of ACF Gutenberg block

    My block code:

    
    <?php
    $custom_wrapper_classes = 'my-block';
    include_once (get_stylesheet_directory() . '/includes/blocks/block-functions.php');
    
    if (function_exists('hest_get_wrapper_attr')) :
    	$wrapper_attributes = hest_get_wrapper_attr($block, $custom_wrapper_classes);
    endif;
    
    $posts = get_field('my_relationship_field');
    
    if( $posts ): ?>
    
    	<div <?php echo wp_kses_data($wrapper_attributes); ?>>	
    
    		<div class="my-grid">
    			<?php
    			global $post;
    			foreach( $posts as $post): 
    				setup_postdata($post);?>
    
    				 <!-- Code for outputting data -->
    			<?php
    			endforeach; ?>
    		</div><!-- .my-grid -->
    
    	</div><!-- .wrapper -->
    
    	<?php
    	wp_reset_postdata();
    
    endif; ?>
    

    hest_get_wrapper_attr() looks like this:

    
    <?php
    /*
     * Converts Gutenberg saved data attributes (input field by IPM plugin) to 
     * a string to echo on the wrapping div
     */
    function conv_data_attributes($data_attributes) {
    
        $data_attr = '';
        // Regular expression pattern to match the value inside the brackets
        $pattern = '/\[(.*?)\]/';
    
        // Perform the regular expression match
        if (preg_match_all($pattern, $data_attributes, $matches)) {
            // Extract the matched values
            $values = $matches[1];
            // Remove the commas from each extracted value
            $data_attr = array_map(function ($value) {
                return str_replace(',', '', $value);
            }, $values);
            // Convert the array into a space-separated string
            $data_attr = implode(' ', $data_attr);
        }
    
        return $data_attr;
    }
    
    /*
     * Converts Gutenberg saved gap value to CSS
     * 
     */
    function conv_blockgap_value($gap) {
        
        $pattern = "/var:([^|]+)\|([^|]+)\|([^|]+)/";
    
        $result = preg_replace_callback($pattern, function ($matches) {
            $lastValue = $matches[3];
            $updatedLastValue = preg_replace("/(\d+)([a-zA-Z]?)/", "$1-$2", $lastValue);
            return "var(--wp--{$matches[1]}--{$matches[2]}--{$updatedLastValue})";
        }, $gap);
    
        $gap = "gap: " . $result . ";";
        
        return $gap;
    }
    
    /*
     * Main function to prepare all wrapper classes, styles and attributes
     * 
     */
    function hest_get_wrapper_attr($block, $custom_wrapper_classes) {
        
        $wrapper_attributes = '';
        $alignment_classes = '';
        $style = '';
    
        // Support custom anchor values.
        $anchor = '';
        if ( ! empty( $block['anchor'] ) ) {
            $anchor = 'id="' . esc_attr( $block['anchor'] ) . '" ';
            $wrapper_attributes .= $anchor;
        }
    
        // Create class attribute allowing for custom "className" and "align" values.
        if ( ! empty( $block['align'] ) ) {
            $alignment_classes .= ' align' . $block['align'];
        }
    
        if ($block['supports']['alignContent'] == 'matrix') {
            // If matrix
            // Replace spaces: center left becomes center-left
            $alignment_classes .= ' has-custom-content-position is-position-' . str_replace(" ", "-", $block['alignContent']);
        } else {
            if ( ! empty( $block['alignContent'] ) ) {
                // If not matrix, get the alignContent
                // either top, center, or bottom
                $alignment_classes .= ' is-vertically-aligned-' . $block['alignContent'];
            }
        }
    
        // Block text alignment
        if( !empty($block['alignText']) ) {
            $alignment_classes .= ' has-text-align-' . $block['alignText'];
        }
    
        // Check if the block has fullHeight turned on
        if( !empty($block['fullHeight']) ) {
            $style .= 'min-height: 100vh;';
        }
        
        // Check if we got custom data attributes to add to our main div
        $data_attr = $block['dataAttributes'] ?? null;
        if ($data_attr && function_exists('conv_data_attributes') ) :
            $data_attr = conv_data_attributes($data_attr);
        endif;
    
        // Add blockGap value to wrapper attributes
        $gap = $block['style']['spacing']['blockGap'] ?? null;
        if ($gap && function_exists('conv_blockgap_value') ) :
            $gap = conv_blockgap_value($gap);
        endif;
    
        $style .= $gap;
    
        $wrapper_attributes .= get_block_wrapper_attributes(
            [
                'class' => $custom_wrapper_classes . $alignment_classes,
                'style' => $style,
            ]
        );
    
        $wrapper_attributes = $wrapper_attributes . ' ' . $data_attr;
    
        return $wrapper_attributes;
    }
    
  • Solving

    update_field returning large int instead of bool

    I’m using ACF Pro to create a Learning Management System. I’ve only recently started having problems. The main one that’s giving me the most trouble is that update_field() is not actually updating the field, despite me giving it accurate information and it working on a local environment (but not a WP Engine Dev environment).

    Currently I’m allowing the user to create a new Course (or “Module”), based on a previous one, specifically for their class. They choose which students they’ll be including, the Module to use a template, then the Chapters (or “Documents”) from that Module.

    Then, on the final screen, they review information, and the “Submit” button starts through a series of AJAX calls that sends the information to the server, sends back the pertinent info, then moves on to the next step.

    I’m sending back the results from each delete_field() and update_field command. When replacing values, I am deleting the current value (with delete_field()) before using update_field(). This has helped some of my issues, but not all.

    Here is the pertinent PHP code:

    
    <?php
    // I've made the CPT "Module" its own Class to contain its helper methods 
    $module = new ACF_Module( intval($module_id) );
    
    // I store the Documents (or "Chapters") for each Module (or "Course") as a 
    //     repeater field containing the document_id and the order it should 
    //     appear within the Module.
    $document_ids = json_decode( $_POST['document_ids']);
    $documents_field = [];
    $count = 1;
    
    foreach( $document_ids as $document_id ) {
        $documents_field[] = [
            'document_id' => intval($document_id),
            'order' => floatval($count),
        ];
        $count++;
    }
    
    // In JS, $documents_field_deleted = (bool) true
    $documents_field_deleted = delete_field($module->documents_field, $module->ID);
    
    // In JS, $documents_field_updated = (int) 625785,, or a similarly large number,
    //     which does not correlate to ANY existing post ID or user ID, as the 
    //     newest post_id in this example is 43113 and largest user ID is 1126
    $documents_field_updated = update_field($module->documents_field, $documents_field, $module->ID);
    

    I don’t know that this will matter, but just in case, here’s my JS doing the AJAX calls:

    
    // Triggered when clicking submit button labelled "Next"
    $('#submit').click(function(e){
        e.preventDefault();
    
        // I'm just storing values in hidden <code><input></code> fields. Since these 
        //     classes are all taken on a job-site, where the student is 
        //     monitored, I'm not concerned as much for the user being able to 
        //     change these.
        var nextAction = '';
        actionStep = $('input[name="acf_action_step"]').val();
    
        var payload = {
            action: 'acf_action_function_name',
            action_step: actionStep,
            agency_id: parseInt($('input[name="acf_agency_id"').val()),
            module_id: parseInt($('input[name="acf_module"]').val())
        };
    
        switch (actionStep) {
            case 'module':
                payload.module_title = $('input[name="acf_module_title"]').val();
                nextAction = 'chapters';
                break;
            case 'chapters':
                payload.chapter_ids = $('input[name="acf_chapters"]').val();
                nextAction = 'user';
                break;
            case 'user':
                var user_object = JSON.parse( $('input[name="acf_users"').val() );
                nextAction = 'user';
    
                if( user_object.length == 1 ) {
                    nextAction = 'finish';
                }
    
                payload.user_id = parseInt( user_object.shift() );
                user_ids = JSON.stringify(user_object);
                $('input[name="acf_users"]').val(user_ids);
                break;
            case 'finish':
                $('#submit').prop('disabled', true);
                $('#submit').addClass('disabled');
                return;
            default:
                break;
        }
    
        $.ajax({
            url: ajax_object.ajax_url,
            type: 'post',
            data: payload,
            beforeSend: function(){            
                $('#submit').prop('disabled', true);
                $('#submit').addClass('disabled');
            },
            success: function(response) {
                var response_object = JSON.parse(response);
                progress.append(response_object.message);
    
                if( response_object.new_module_id ) {
                    $('input[name="acf_module"]').val( parseInt(response_object.new_module_id) );
                }
            },
            complete: function(response) {
                $('input[name="acf_action_step"]').val( nextAction );
                $('#submit').prop('disabled', false);
                $('#submit').removeClass('disabled');
            }
        });
    
        return;
    });
    
  • Helping

    Removing extra space after comma

    I am using the Short Text field in ACF, but when I add a number like, for example, $4,000 it displays as $4, 000, with a space after the comma. How can I remove that?

  • Unread

    how to remove comma from stackable dynamics block

    hello i got problem , i was using stackable to create some dynamics blocks

    i using multiple checkbox as like photo

    when i output as content will showing with “,” i want to change to <breank> or just blank

    how i can do it ?

  • Solved

    How to Remove last comma from Gallery Loop?

    Hello, please tell me how can I remove the last comma in the photo output loop

    it’s my loop code:

    
    <img class="location__image" src="<?php echo get_the_post_thumbnail_url(get_the_ID() , 'medium_large'); ?>"
             data-hover-slides='<?php $location_gallery_urls = get_field('location_gallery'); ?><?php if ($location_gallery_urls): ?><?php foreach (array_slice($location_gallery_urls, 0, 5) as $location_gallery_url): ?><?php echo esc_url($location_gallery_url); ?>, <?php
        endforeach; ?><?php
    endif; ?>'>
  • Unread

    Replace Comma to Dash

    Hello.

    I need help changing the output numbers 44, 22, 33, 55 to 44-22-33-55 or just remove the comma.

    The result from the table column is generated using a shortcode plugin using the field name ‘winning-numbers-major’.

    I make sure to group all the number field so I can display using the shortcode.

    I appreciate any help. Thanks.

  • Solving

    Problem with commas

    Hi everyone,
    I know that the problem has often been asked on the forum but despite having tried everything I do not understand how to remove the commas on the front when using checkboxes.
    I am not a developer and I have trouble understanding how to do it.
    Could someone help me? 🙂

    Thanks in advance !

  • Helping

    Remove comma from last checkbox item

    Hi there,

    I’m sure this is quite trivial for your but I’m not a coder eh eh…

    I’ve manage to achieve what I want but I think it can be improved.

    I have a checkbox field, and I want to retrieve both label and value and want to separate them with a comma. This part is working fine. However, I want to remove the comma from the last item. I can add the comma in a span and then target the last span with CSS and remove it but I want it to be better.

    This is what I came up with by reading the docs and searching other topics

    <?php
    
    $plans = get_field('plans');
    if ( $plans) : ?>
    <div>
    <?php foreach( $plans as $plan ): ?>
           <a target="_blank" title="<?php echo $plan['label']; ?>" href="<?php echo $plan['value']; ?>"><?php echo $plan['label']; ?></a><span>,</span>
        <?php endforeach; ?>
    </div>
    <?php endif; ?>
  • Helping

    How to remove commas in ACF

    How To remove commas when using checkboxes
    I am trying to insert some custom tags for each product in my website. I use checkboxes in order to select tags and display on frontend. But the tags are displayed each item seperated with a comma (,). Can someone advice to how to remove this?

  • Unread

    How can I remove (,) from checkboxes?

    hello, I’m making a website for a real estate company, and I’m registering the leisure areas, such as soccer fields, gyms, pet places, these things … but when I look at the website, these elements are separated by commas and I want to remove these commas, is there any way other than by PHP? I don’t know anything about programming and I need to remove these commas. If the only solution is for PHP, send me the code already ready and the directory where I must insert this code.

    Advanced Custom Fields PRO
    Version 5.9.5

  • Helping

    custom category

    I have created a category with this code

    
    function custom_post_type() {
    
    // Set UI labels for Custom Post Type
    $labels = array(
    'name'                => _x( 'products', 'Post Type General Name', 'twentythirteen' ),
    'singular_name'       => _x( 'product', 'Post Type Singular Name', 'twentythirteen' ),
    'menu_name'           => __( 'Products', 'twentythirteen' ),
    'parent_item_colon'   => __( 'Parent Product', 'twentythirteen' ),
    'all_items'           => __( 'All products', 'twentythirteen' ),
    'view_item'           => __( 'View Product', 'twentythirteen' ),
    'add_new_item'        => __( 'Add New Product', 'twentythirteen' ),
    'add_new'             => __( 'Add New', 'twentythirteen' ),
    'edit_item'           => __( 'Edit Product', 'twentythirteen' ),
    'update_item'         => __( 'Update Product', 'twentythirteen' ),
    'search_items'        => __( 'Search Product', 'twentythirteen' ),
    'not_found'           => __( 'Not Found', 'twentythirteen' ),
    'not_found_in_trash'  => __( 'Not found in Trash', 'twentythirteen' ),
    );
    
    // Set other options for Custom Post Type
    
    $args = array(
    'label'               => __( 'products', 'twentythirteen' ),
    'description'         => __( 'product news and reviews', 'twentythirteen' ),
    'labels'              => $labels,
    // Features this CPT supports in Post Editor
    'supports'            => array( 'title', 'editor', 'excerpt', 'author', 'thumbnail', 'comments', 'revisions', 'custom-fields','tags' ),
    // You can associate this CPT with a taxonomy or custom taxonomy.
    'taxonomies'          => array( 'genres' ),
    /* A hierarchical CPT is like Pages and can have
    * Parent and child items. A non-hierarchical CPT
    * is like Posts.
    */
    'hierarchical'        => true,
    'public'              => true,
    'show_ui'             => true,
    'show_in_menu'        => true,
    'show_in_nav_menus'   => true,
    'show_in_admin_bar'   => true,
    'menu_position'       => 5,
    'can_export'          => true,
    'has_archive'         => true,
    'exclude_from_search' => false,
    'publicly_queryable'  => true,
    'capability_type'     => 'page',
    );
    
    // Registering your Custom Post Type
    register_post_type( 'products', $args );
    register_taxonomy('categories', array('products'), array("hierarchical" => true, "label" => "Categories", "singular_label" => "Category", "rewrite" => array( 'slug' => 'products', 'with_front'=> false )));
    
    }
    
    /* Hook into the 'init' action so that the function
    * Containing our post type registration is not
    * unnecessarily executed.
    */
    
    //create two taxonomies, genres and tags for the post type "tag"
    function create_tag_taxonomies() 
    {
      // Add new taxonomy, NOT hierarchical (like tags)
      $labels = array(
        'name' => _x( 'Tags', 'taxonomy general name' ),
        'singular_name' => _x( 'Tag', 'taxonomy singular name' ),
        'search_items' =>  __( 'Search Tags' ),
        'popular_items' => __( 'Popular Tags' ),
        'all_items' => __( 'All Tags' ),
        'parent_item' => null,
        'parent_item_colon' => null,
        'edit_item' => __( 'Edit Tag' ), 
        'update_item' => __( 'Update Tag' ),
        'add_new_item' => __( 'Add New Tag' ),
        'new_item_name' => __( 'New Tag Name' ),
        'separate_items_with_commas' => __( 'Separate tags with commas' ),
        'add_or_remove_items' => __( 'Add or remove tags' ),
        'choose_from_most_used' => __( 'Choose from the most used tags' ),
        'menu_name' => __( 'Tags' ),
      ); 
    
      register_taxonomy('tag','products',array(
        'hierarchical' => true,
        'labels' => $labels,
        'show_ui' => true,
        'update_count_callback' => '_update_post_term_count',
        'query_var' => true,
        'rewrite' => array( 'slug' => 'tag' ),
      ));
    }
    
    add_action( 'init', 'create_tag_taxonomies', 0 );

    How can I display the list of posts of that taxonomy using the ÙŽACF plugin’s taxonomy feature?

    https://www.advancedcustomfields.com/resources/taxonomy/

  • Unread

    Remove commas on elementor

    Multiple Select Field – remove commas on elementor?

  • Solved

    Remove commas (checkbox)

    Hi!

    I use this code with my checkbox, but would like to remove the commas.

    `
    <p class=”shop-link”><?php the_field(‘shop’); ?></p>
    `
    I’ve searched the forum and tried different codes without any luck.

    For example, this didn’t work so I appreciate all help!

    `
    <p class=”shop-link”><?php $values = get_field(‘checkbox’);
    if ($values) {
    foreach ($values as $value) {
    echo str_replace(‘, ‘, ‘<br />’, $value);
    }
    } the_field(‘shop’); ?></p>
    `

    Thank you,
    Caroline

  • Solved

    Output comma separated list of repeater sub field values

    I have an ACF repeater field field_5f71d4eaaf381 for email addresses and I want to output a comma separate list of the sub field values (measurement_extra_email_address) to create a $to for the WordPress mail function.

    
    			$values			  = $_POST['acf'];
    			$extra_recipients = $_POST['acf']['field_5f71d4eaaf381'];
    
    			if ( $extra_recipients ) {
    				$list = array();
    				foreach( $extra_recipients as $extra_recipient ) {
    					$list[] = $extra_recipient['measurement_extra_email_address'];
    				}
    				$to = implode(',', $list);
    			}
    

    I thought above code should/would do it but no email is being send so I guess the code is incorrect..?

    Just a note: When I remove above part of the code and just try $to = '[email protected]'; an email is being send so the error should be in there…

  • Solving

    Display a linkable URL and Remove the comma

    Hello

    I’ve been using ACF and a few things have got me stumped.

    1st
    I have a site setup in elementor and have tried using the URL and Link fields in ACF to allow users to put in a website domain in a field for a member profile.
    However when ever it displays via ACF shortcode, the url is not linkable, how do i make it link to the URL thats been put in the ACF field?

    2nd
    https://www.cider.ordesign.me/member/westons/
    How do i remove the commas between the icons, under whats on offer?

    Thanks

  • Solved

    My post stopped working

  • Solved

    Remove the comma (,) in the line break.

    I would like to be able to remove (,) every time a newline occurs in the labels field.
    Can you help me, please?

    Thank you

    <h6 class="audio-tags">
                            <?php
                                $tags = get_field("etiquetas");
                                $tagArray = explode(",", $tags);
    
                                foreach($tagArray as $tag){
                                    echo("<div class='tag-wrap'>".$tag."</div>");
                                }
                            ?>
                        </h6>

reply

  • Ok i have updated the code and now it works but somehow you need to have atleast one layout in flexible content for dragging to work.

    add_action('acf/input/admin_footer', function () {
        ?>
        <script type="text/javascript">
    
            (function($) {
    
                acf.add_action('ready', function($el){
                    $(".acf-flexible-content .values").sortable({
                        connectWith: ".acf-flexible-content .values",
                        start: function(event, ui) {
                            acf.do_action('sortstart', ui.item, ui.placeholder);
                        },
                        stop: function(event, ui) {
                            acf.do_action('sortstop', ui.item, ui.placeholder);
                            $(this).find('.mce-tinymce').each(function() {
                                tinyMCE.execCommand('mceRemoveControl', true, $(this).attr('id'));
                                tinyMCE.execCommand('mceAddControl', true, $(this).attr('id'));
                            });
                        }
                    });
    
                    $(".acf-repeater .acf-flexible-content").sortable({
                        connectWith: ".acf-repeater .acf-flexible-content",
                        start: function(event, ui) {
                            acf.do_action('sortstart', ui.item, ui.placeholder);
                        },
                        stop: function(event, ui) {
                            acf.do_action('sortstop', ui.item, ui.placeholder);
                        }
                    });
                });
    
                acf.add_action('sortstop', function ($el) {
                    var $repeater = $($el).closest('.acf-input > .acf-repeater');
                    
                    if ($repeater.length) {
                        var $row = $el.closest('.acf-row');
                        var column_num = $row.attr('data-id');
    
                        // Loop through fields within the dropped element and update names
                        $el.find('[name^="acf[field_"]').each(function() {
                            var field_name = $(this).attr('name');
                            field_name = field_name.match(/\[([a-zA-Z0-9_-]+)\]/g);
                            field_name[1] = '[' + column_num + ']';
                            var new_name = 'acf' + field_name.join('');
                            $(this).attr('name', new_name);
                        });
    
                        // Loop through layouts within the flexible content field
                        $repeater.find('.acf-flexible-content .values > .layout').each(function(index) {
                            $(this).find('.acf-fc-layout-order:first').html(index + 1);
    
                            // Loop through fields within each layout and update names
                            $(this).find('[name^="acf[field_"]').each(function() {
                                var field_name = $(this).attr('name');
                                field_name = field_name.match(/\[([a-zA-Z0-9_-]+)\]/g);
                                var tempIndex = parseInt(field_name[3].match(/([0-9]+)/g));
                                field_name[3] = field_name[3].replace(tempIndex, index);
                                var new_name = 'acf' + field_name.join('');
                                $(this).attr('name', new_name);
                            });
    
                            // Trigger click on selected buttons to activate conditional logic
                            $(this).find('.acf-button-group label.selected').trigger('click');
                        });
                    }
                });
    
            })(jQuery);
    
            function GetSubstringIndex(str, substring, n) {
                var times = 0, index = null;
                while (times < n && index !== -1) {
                    index = str.indexOf(substring, index + 1);
                    times++;
                }
                return index;
            }
    
        </script>
        <?php
    });
    
  • Hello,

    I have the same problem and I read all the posts about this, have you found a solution please ?
    I’am using the checkox ACF and elementor to display it, and I only need to remove the comma between the values. I don’t want to execute JS to do this if it is possible.
    Regards,

  • I have solved several issues using the following:

    _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _

    1 – ACF Field Setup

    I have setup fields as FILED TYPE > LAYOUT > GROUP
    https://www.advancedcustomfields.com/resources/group/

    This allows us to target the fields with a given ACF field group using the field group name.

            if( have_rows('group_name')){
                while(have_rows('group_name')){
                    the_row();  
    
                    if( $subfields = get_row()) {
    

    I am outputting the custom post type, ACF data, to a table using a foreach loop.
    The code is then displayed on our post using a [shortcode]

    <?php
    
    class CUSTOM_SHORTCODES {
    
    			public static function register_shortcodes() {
    				add_shortcode( 'custom_specs', array( __CLASS__, 'boat_specs' ) );
    			}
    
    public static function custom_specs($atts) {
      
    		$out = '';
    		$out .= '<div>';
    		$out .= '<table>';
    		$out .= '<tbody>';
    
    		$subfields = get_row();
    		$field = get_sub_field_object( $key );
    		if( have_rows('specifications')){
    			while(have_rows('specifications')){
    				the_row();  
    				if( $subfields = get_row()) {
    					foreach ($subfields as $key => $value) {
    						if ( !empty($value) ) {
    
    							if(is_array($value)) {
    							$value = @implode(', ', $value);
    							}
    							$field = get_sub_field_object($key);
    								$out .= '<tr class="tb-row"><td class="tb-cell"><span class="acf-label">' . $field['label'] . '</span></td><td class="tb-cell"><span class="acf-value">' . $value . '</span></td></tr>';
    						}
    					}  
    				}
    			}
    		}
    		$out .= '</tbody></table></div>';
    
    		return $out;
    	}	
    		
    }
    CUSTOM_SHORTCODES::register_shortcodes();
    

    In this instance, the demo shortcode is [custom_specs]

    In our foreach loop, we can check to see if a field has value. If it has no value i.e. null then the field does not show in our for each loop.

    if ( !empty($value) ) {
    OR
    https://www.advancedcustomfields.com/resources/hiding-empty-fields/

    If the returned value is an array, we can convert the array to a comma list.

    
    if(is_array($value)) {
    $value = @implode(', ', $value);
    }
    

    Using this method, we can segment our ACF data into different foreach loop shortcodes for our use case scenario.

    Specifications = [custom_specs]
    Standard Features = [custom_feat]
    Options = [custom_opt]

    _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
    2 – Omit / Remove ACF field from the foreach loop.

    The ‘price’ is recorded as an ACF field in our field group ‘specifications’.
    However, the client does not want to show the ‘price’ field on the table on the front end.

    How do we remove the ACF field ‘price’ from our ‘specifications’ foreach loop?

    OPTION 1 – “SIMPLE”
    Move the ACF field ‘price’ out of the current field group ‘specifications’ so it’s not returned in the shortcode loop [custom_specs].

    If OPTION 1 does not fit your requirements, then try this alternative.

    OPTION 2 – “ACF continue”
    ACF Support has come back with the following. Interestingly, there is no mention of this in the current ACF documentation.

    if( have_rows('specifications')){
                while(have_rows('specifications')){
                    the_row();  
    
                    if( $subfields = get_row()) {
    
                        foreach ($subfields as $key => $value) {
    
                                // Omit 'price' sub field - enter the field key
                                if ($key == 'field_123456789') { //skip this!
                                                    continue;
                                }
    

    Using the ACF field key and continue; we can now remove any ACF field inside our foreach loop.

    Fantastic!
    _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _

    3 – Removing Conditional Logic Parent > Child ACF fields from our foreach loop.

    In this scenario, we have the PARENT FIELD1 and the CHILD FIELD2
    The fields can be any ACF field Type: Select, Checkbox, Radio Button, Button Group.

    PARENT FIELD1 (*Required? = Yes)
    ( ) ABC
    ( ) MNO
    ( ) XYZ > Show CHILD FIELD2

    CHILD FIELD2 (*Required? = Yes + Allow Null? = Yes )
    ( ) Choice 1
    ( ) Choice 2
    ( ) Choice 3

    We have conditional logic CHILD FIELD2
    Show this field if <PARENT FIELD1> Value is equal to <XYZ>

    Great!
    If PARENT FIELD1 (•) XYZ is selected, we expect CHILD FIELD2 Choices to show.
    If PARENT FIELD1 ( ) XYZ is de-selected, we can expect FIELD2 to hide.

    • • • • • • • • • • • • • • • • • • • • • •

    Now, this is where it gets tricky.

    As part of our strategy, we want to make it easy for the Client to update the data without making things worse.

    The Client Selects <PARENT FIELD1>(•) XYZ
    CHILD FIELD2 choices are shown.
    All choices are null – they are empty.
    The Client doesn’t make a selection from CHILD FIELD2 and updates the post.
    We get a validation warning – CHILD FIELD2 is set to (*Required) so now we have to make a selection.
    The Client selects CHILD FIELD2 (•) Choice 2
    We validate, and the post is saved.

    CHILD FIELD2 > Choice 2 is saved to the database.

    We run our shortcode loop and CHILD FIELD2 is output into our table.

    The Client decides, no, actually I didn’t want (•) XYZ, I really wanted ( ) ABC
    The Client de-selects ( ) XYZ and selects (•) ABC
    CHILD FIELD2 is hidden.

    Even though <PARENT FIELD1>( )XYZ is not selected, our foreach loop is still outputting CHILD FIELD2 in the table.

    Why ! – you ask?

    In the database CHILD FIELD2 still has a saved value = Choice 2.
    Our foreach loop condition is “only include fields that have value”.
    So CHILD FIELD2 is still showing.

    This stems from core ACF functionality – If the field is set to (*Required) ignore the null.
    https://github.com/elliotcondon/acf/issues/591

    How do we fix this?
    • • • • • • • • • • • • • • • • • • • • • •
    METHOD 1 – On all CHILD FIELD(s) disable (*Required)
    (*Required? = No)
    Each CHILD FIELD2 choice can be toggled ON or OFF. Allowing us to de-select our previous selected option. The post can be validated and saved without having a choice selected. The Database value is cleared on Post Update.

    But wait – this now requires the Client to understand that the CHILD FIELD2 needs to be un-selected before unselecting the PARENT FIELD1.

    LOL
    Sometimes the simplest of workflow solutions are the hardest for clients to remember.
    • • • • • • • • • • • • • • • • • • • • • •
    METHOD 2 – JQuery

    Use jQuery to null the CHILD FIELD when the PARENT FIELD is un-selected.

    This improves our Method 1 workflow, as the Client doesn’t have to remember to unselect the CHILD FIELD2. Our jQuery Function will handle this.

    For this to work, I changed my CHILD FIELD2 field Type to a ‘select’.
    When the Field Type ‘select’ is set to (Allow Null? = Yes) a null choice is added to the top of the dropdown select “-Select-“.
    https://www.advancedcustomfields.com/resources/select/
    I used JQuery to select the first item on the CHILD FIELD2 ‘select’ list
    when the Parent is de-selected.

    In my WordPress Child theme functions.php file I am loading a JS file when is_admin()

    define( 'CHILD_THEM_URI', get_stylesheet_directory_uri() );
    define( 'CHILD_THEM_DIR', get_stylesheet_directory() );
    // register scripts for the wp_admin section
    add_action( 'admin_head', 'register_admin_scripts' );
    function register_admin_scripts() {
        if ( is_admin() ) {
            wp_enqueue_script( 'admin_js', CHILD_THEM_URI . '/includes/admin.js', array( 'jquery' ) );
    
        }
    }

    In the JS File I have the following simple click function.

    
    jQuery(document).ready (function ($) {
    
    $('#parent_field_id').on('click',function () {
                    if ($(this).is(':checked')) {
                        //alert('You have Checked it');
                    } else {
                        //alert('You Un-Checked it');
                        // Set Conditional Select to null  - First Item on the list
                        $("#child_field_id").prop("selectedIndex", 0);
    
                    }
                });
    });
    

    • • • • • • • • • • • • • • • • • • • • • •

    METHOD 3 – delete_field()

    We could write a custom function if PARENT FIELD1 is de-selected then dynamically delete the conditional logic CHILD FIELD2 value from the database. Seems heavy to me!

    delete_field()
    delete_sub_field()

    Someone with better PHP skills than me may wish to provide a solution.
    I look forward to your responses.

    • • • • • • • • • • • • • • • • • • • • • •

    METHOD 4 – FUNCTION REQUEST

    Have an additional toggle option on the ACF CHILD FIELD next to the (AllowNull? = Yes) to turn ON or OFF the required functionality.

    If conditional logic PARENT Field is un-selected – return CHILD FIELD VALUES to the default Null State.

    _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _

    I think thats covers everything for now.

    Hopefully this helps someone else in the future

  • Hi,
    Please see this for better understanding: https://infoobox.com/person/sunil-butolia

    Currently user can fill their parents details in single text box but I want to create separate for mother and father and want to show in single line as mentioned in above link.

    But what if someone only fills one details mother or father then how to remove ‘comma’.

  • Yes, if I remove the function below I don’t have any error :

    add_action('pre_get_posts', 'my_pre_get_posts'); 
    function my_pre_get_posts( $query ) {
    
    	$meta_query = $query->get('meta_query');
    	
    	if( isset($_GET['coup_de_coeur']) )
    	{
    		$meta_query[] = array(
    			'key' => 'coup_de_coeur',
    			'value' => $_GET['coup_de_coeur'],
    			'compare' => 'LIKE',
    		);
    	}
    	$query->set('meta_query', $meta_query);
    	return;
    
    }
    

    I checked and it seems like everything is correctly closed, no comma missing…
    Unfortunatelu the critical error doesn’t provide any line of code so I’m a bit in the dark…
    I tried to put WP Debug to true but no luck either.

  • Saw something funny happening to the quotes so used decimal code for quotes:

    // Variables
    $number_of_events = get_field( 'number_of_events' );
    // print_r($number_of_events);
    $terms = get_field('events_category');
    // print_r($terms);
    // $term_slugs = $terms()->slug;
    $term_slugs ='';
    foreach ( $terms as $term ):
        $term_slugs .= "'" . esc_html( $term->slug ) . "'" . ',';
        endforeach;
    $term_slugs = substr($term_slugs, 0, -1); //Removes very last comma.
    // print_r($term_slugs);
    // local,virtual,
    
    $args = array(
        'post_type' => 'event',
        'posts_per_page' => $number_of_events,
        // 'event_category' => $term_slugs
        'tax_query' => [
            'taxonomy'         => 'event_category',
            'include_children' => false,
            'field'            => 'name',
            // 'terms'            => array_values($term_slugs),
        ],
    );

    still no filtering on event category..

Viewing 25 results - 1 through 25 (of 51 total)