Support

Account

Home Forums Search Search Results for '%s'

Search Results for '%s'

topic

  • Unread

    Category list with image

    Hi, I try to create list of child category with images thumbs.

    I add new field to taxonomy “image_category” and now I try to add this image to the list:

    <?php 
    
    $args = array('parent' => 3);
    $categories = get_categories( $args );
    
    $term = get_queried_object();
    $image_category = get_field('image_category', $term);
    
    foreach($categories as $category) { 
    
        echo '<div class="col-md-3 col-sm-12 col-xs-12 lista-kraje text-center pb-3"><img src="' . $image_category .  '"><h3><a href="' . get_category_link( $category->term_id ) . '" title="' . sprintf( __( "View all posts in %s" ), $category->name ) . '" ' . '>' . $category->name.'</a> </h3> ';
        echo '<p> <strong>Number post:</strong> '. $category->count . '</p></div>';  
    }
    
    ?>

    I see category list, name, number post. Only image dont work.

    Image link dont show. I have on consol only “img src=(unknown)”. What am I doing wrong?

  • Solved

    Allow specific fields from repeater field on frontend form

    Is it possible to have some specific repeater fields to display on frontend form. for example look at the “fields” parameter in below example.

    $options = array(
    	'field_groups' => ['group_602a592cf1805'],
    	'fields' => [
    			'my_name', //normal ACF field, (this works!)
    			'test_repeater_field' => ['hello'], //allowing only specific field with in a repeater field, (Not working)
    		],
    	'form_attributes' => array(
    		'method' => 'POST',
    		'action' => admin_url("admin-post.php"),
    	),
    	'html_before_fields' => sprintf(
    		'<input type="hidden" name="action" value="save_user_fields_form">
        <input type="hidden" name="user_id" value="user_%s">',
    		$user->ID
    	),
    	'post_id' => "user_{$user->ID}",
    	'form' => true,
    	'html_submit_button' => '<button type="submit" class="button margin-top-20 margin-bottom-20" value="Update Profile">' . __('Submit', 'text-domain') . '</button>',
    );
    
    acf_form($options);
  • Unread

    Using the Google Maps field to output segments of an address

    The documentation for the Google Map field demonstrates a really nice way to render addresses using the address entered into the field.

    <?php 
    $location = get_field('location');
    if( $location ) {
    
        // Loop over segments and construct HTML.
        $address = '';
        foreach( array('street_number', 'street_name', 'city', 'state', 'post_code', 'country') as $i => $k ) {
            if( isset( $location[ $k ] ) ) {
                $address .= sprintf( '<span class="segment-%s">%s</span>, ', $k, $location[ $k ] );
            }
        }
    
        // Trim trailing comma.
        $address = trim( $address, ', ' );
    
        // Display HTML.
        echo '<p>' . $address . '.</p>';
    }

    For my project I am working with small towns in the UK so city, state and country are not relevant. Instead, I would like to use postal_town and administrative_area_level_2 in place of these which should render the town and county respectively. So for the foreach I have

    foreach( array( 'street_number', 'street_name', 'postal_town', 'administrative_area_level_2', 'post_code' ) as $i => $k ) { ... }

    I had assumed that this would return: number, street, town, county, post-code. But the postal_town and administrative_area_level_2 both return nothing.

    Printing the array keys using <?php print_r(array_keys($location)); ?> appears to show only a limited set of options.

    I could as a compromise just use <?php echo $location['address']; ?> but this gives a slightly different version of the address (Business name, street, town, country), but it’s not quite what I’m after.

    Does anyone know how would I go about getting my chosen values to render to the front end without having to resort to a separate address input field?

  • Solving

    Acf form does not make posts in cpt

    Hello.
    I have registered a post type and i want to have posts on it with an acf form.
    The field group contains only one field. The field is file upload field.

    The connection with post type and field works ok because i tried make post from dashboard and the field is on the editor of post type.

    When i click the submit button the form works ok but there is not a post in my custom post type.

    What’s the problem?

    I send you the custom code if you want to help.
    Thank you.

    <?php acf_form_head();
    get_header();
    ?>
    <div class="container">
    <?php
      $settings = array(
        'id' => 'photos_form',
        'field_groups' => array("group_6025117548b3f"),
        'fields' => false,
        'submit_value' => __("Submit", 'acf'),
        'label_placement' => 'top',
        'html_submit_button' => '<input type="submit" id="submitbtn" class="acf-button button primary_btn" value="%s" />',
        'html_submit_spinner' => '<span class="acf-spinner"></span>',
        'updated_message' => '',
        'html_after_fields' => '',
    );
    acf_form($settings);?>
    </div>
    <?php get_footer(); ?>
  • Helping

    Don't recive taxonomy title

    Hi, i have form to add new taxonomy and i also need template with form for editing this taxonomy so have for editing taxonomy next form but problem is that i get all value for custom field but for title of taxonomy i didnt get.

    <?php acf_form(array(
        'post_id' => $_GET["post"],
        'post_title'	=> true,
        'field_groups' => array(
            'group_5f475552ca375'
         ),
        'submit_value'		=> 'Shrani',
        'html_submit_button'	=> '<input type="submit" class="acf-button btn btn-primary" value="%s" />',
        'uploader' => 'wp',
        )); 
    ?>

    $_GET[“post”] i get from url parameter and the post title input is vissible but it is empty

  • Solved

    create new taxonomy with acf form not new post

    Hi i want to save a new taxonomy, but i cant get the form to frontend.
    Custom field are sucess visible in backend but on frontend i cant see, i think becuse i dont have right code. My custom taxonomy name is “narocilnice” and code is:

    <?php acf_form(array(
        'id' => 'acf-form',
        'post_id' => true,
        'post_title'	=> true,
        'new_post'		=> array(
            'tax_name'		=> 'narocilnice',
        ),
        'submit_value'		=> 'Shrani',
        'html_submit_button'	=> '<input type="submit" class="acf-button btn btn-primary" value="%s" />',
        'uploader' => 'wp'
        )); 
    ?>

    On this picture printscreen you can see that i get on backend custom field but on frontend i can’t. So i need add new taxonomy to custom taxonomy name “narocilnice” not new post to custom post_type.

    Can someone tell me what is wrong?

  • Helping

    get_field_object not working with restrict_manage_posts action

    I am using the action restrict_manage_posts to create a custom filter for my posts:

    add_action( 'restrict_manage_posts', '_s_custom_filter' );
    
    function kiewit_locations_custom_filter($post_type){
    	
    	if ($post_type === 'custom_post_type'){
    		
    		$args = array(
    			'post_type'  => 'custom_post_type',
    			'parent'     => 0
    		);
    
    		$items = get_pages( $args );
            ?>
            <select id="filter_by_custom_post_type" name="filter_by_custom_post_type">
            <option value=""><?php _e('All Custom Posts', '_s'); ?></option>
            <?php
                $current_v = isset($_GET['filter_by_custom_post_type']) ? $_GET['filter_by_custom_post_type'] : '';
                foreach( $items as $item ) {
                    printf
                        (
                            '<option value="%s"%s>%s</option>',
                            $item->post_name,
                            $item->post_name == $current_v? ' selected="selected"':'',
                            $item->post_title
                        );
                    }
            ?>
            </select>
            <?php
        }
    }

    I also have custom columns set up on my custom_post_type to display selected meta data from a select field and try to display that data using get_field_object('custom_select_information');, however, that always returns false, even if I use the field key.

    Any ideas how to get that custom_select_information to display when filtering my posts?

  • Solving

    Sort Custom Post Type by Taxonomy.

    Hi
    I have a query I would like to resolve.

    The scenario is as follows:
    I have a custom post type called Auction.

    Auctions have an acf in relation to a custom post type product.
    Those products can be assigned taxonomies.

    My question is how to sort those products by taxonomy when I’m on the single-auction.php page.

    Following the documentation I can show all the products of an auction, but I would like to sort those products by their taxonomy.

    An image to clarify what I want to get :

    A brief explanation:

    Taxonomy Term A

    Product 1
    Product 2

    Taxonomy Term B

    Product 3
    Product 4
    Order custom post type by taxonomy

    My code :

    $featured_posts = get_field(‘products_in_this_auction’);
    (Note: get_field(‘products_in_this_auction’) is a Post Object)
    This is a post object and contains the ids of the products that are linked to the auction.

    But my problem is how to get those products sorted by taxonomy.
    I guess I have to use tax_query for my
    query.

    I have an old code that shows me all the custom post type products ordered by their taxonomy, as seen in the image, but what I need is to show only the custom post type products that depend on the current auction.

    I know those custom post type are in $featured_posts = get_field(‘products_in_this_auction’); but I don’t know how to get them.

    My code, something old-fashioned, is the following.

     $categories = get_terms('type_produc', 'orderby=count&order=DESC&hide_empty=1');
                          foreach( $categories as $category ): 
                          ?>
                          <h3 class="title_pru"><?php echo $category->name; // Prints the cat/taxonomy group title ?></h3>
                          <?php
                          $posts = get_posts(array(
                          'post_type' => 'myproduct',
                          'taxonomy' => $category->taxonomy,
                          'term' => $category->slug,
                          'nopaging' => true,
                          ));
                          foreach($posts as $post): 
                          setup_postdata($post); 
                          ?>
                         
                          <div id="post-<?php the_ID(); ?>">
                         
                        
                        <?php  the_title( sprintf( '<p class="title_pru"><a href="%s" rel="bookmark">', esc_url( get_permalink() ) ), '</a></p>' ); ?>
                         
                       
                         
                          </div><!-- #post-## --> 
                          <?php endforeach; ?>
                         
                         <?php endforeach; ?>

    This code shows the result of the image, but it doesn’t work for me.

    I hope someone can help.
    Thank you very much.

  • Solving

    InnerBlocks + Slick slider

    Hi,
    I’m trying to make hero section where one column has slick slider (repeater field with images) and second one with innerBlocks.

    Problem:
    When I edit slider in any way (change order of sub_fields/ add new/ remove one) block preview slick slider can’t re-initialize.

    If I comment out ‘jsx’ or change to ‘false’ – slider is working as expect.

    In demo version i just simplify everything and copy-paste from code examples – same effect:

    functions.php

    add_action('acf/init', 'my_acf_init_blocks');
    function my_acf_init_blocks() {
    
        // Check function exists.
        if( function_exists('acf_register_block_type') ) {
    
            // Register a restricted block.
            acf_register_block_type(array(
                'name'              => 'test',
                'title'             => 'Test',
                'description'       => 'A test content block.',
                'category'          => 'formatting',
                'mode'              => 'preview',
                'supports'          => array(
                    'align' => true,
                    'mode' => false,
                    'jsx' => true
                ),
                'enqueue_assets' 	=> function(){
                  $theme = wp_get_theme( );
                  $ver = $theme->version;
                  wp_enqueue_style( 'slick', 'https://cdn.jsdelivr.net/npm/[email protected]/slick/slick.css', array(), $ver );
                  wp_enqueue_style( 'slick-theme', 'https://cdn.jsdelivr.net/npm/[email protected]/slick/slick-theme.css', array(), $ver);
                  wp_enqueue_script( 'slick', 'https://cdn.jsdelivr.net/npm/[email protected]/slick/slick.min.js', array('jquery'), $ver, true );
                  wp_enqueue_style( 'test-css', get_template_directory_uri() . '/test.css', array(''), $ver, 'all' );
                  wp_enqueue_script( 'test-js', get_template_directory_uri() . '/test.js', array('jquery'), $ver, true );
                },
                'render_template' => 'test.php',
            ));
        }
    }

    test.php

    $classes = '';
    if( !empty($block['className']) ) {
        $classes .= sprintf( ' %s', $block['className'] );
    }
    if( !empty($block['align']) ) {
        $classes .= sprintf( ' align%s', $block['align'] );
    } ?>
    
    <div class="test <?php echo esc_attr($classes); ?>">
        <div class="test-col">
        	<InnerBlocks  />
        </div>
        <div class="test-col slider">
    			<?php if( have_rows('slides') ): ?>
    				<div class="slides">
    					<?php while( have_rows('slides') ): the_row();
    						$image = get_sub_field('image');
    						?>
    						<div>
    							<?php echo wp_get_attachment_image( $image['id'], 'full' ); ?>
    						</div>
    					<?php endwhile; ?>
    				</div>
    			<?php else: ?>
    				<p>Please add some slides.</p>
    			<?php endif; ?>
        </div>
    </div>

    test.js

    (function($){
        var initializeBlock = function( $block ) {
            $block.find('.slides').slick({
                dots: true,
                infinite: true,
                speed: 300,
                slidesToShow: 1,
                centerMode: true,
                variableWidth: true,
                adaptiveHeight: true,
    			focusOnSelect: true
            });
        }
    
        // Initialize each block on page load (front end).
        $(document).ready(function(){
            $('.slider').each(function(){
                initializeBlock( $(this) );
            });
        });
    
        // Initialize dynamic block preview (editor).
        if( window.acf ) {
            window.acf.addAction( 'render_block_preview/type=test', initializeBlock );
        }
    
    })(jQuery);

    As alternative option from formums: test.js

    (function($){
        var initializeBlock = function( $block ) {
            function getSliderSettings() {
                dots: true,
                infinite: true,
                speed: 300,
                slidesToShow: 1,
                centerMode: true,
                variableWidth: true,
                adaptiveHeight: true,
    			      focusOnSelect: true
            }
            $block.find('.slides').slick( getSliderSettings() );
        }
    
        // Initialize each block on page load (front end).
        $(document).ready(function(){
            $('.slider').each(function(){
                initializeBlock( $(this) );
            });
        });
    
        // Initialize dynamic block preview (editor).
        if( window.acf ) {
            window.acf.addAction( 'render_block_preview/type=test', initializeBlock );
        }
    
    })(jQuery);

    I believe there’s a solution to reint slick in better wahy, but maybe it’s just bug?

  • Unread

    multiple forms in front end user account

    Hi all.

    I’m building a website that is for booking events, the e-commerce platform is woocommerce. I’ve acted an action to add a new page to the user account called family, where I want the user to be able to manage their family members and contact info.

    So far I’ve added the page, created a repeater for user where they can add a family member and fill in that members information, it saves and all works great.

    Now I’d like to add an ACF group before the repeater that has main information such as emergency contact details and next of kin, but I can’t figure out how to display two fields (the group and the repeater) within the one action and only have one save button to save the details to the users account.

    This is what I have so far that works for the repeater, but if anyone could steer me in the right direction as to how to add the group field, it’d be hugely appreciated.

    <?php
      acf_form_head();
      get_header(); 
    ?>
    
    Family
    
    <div class="family-members-form"><?php 
    
     if ( !is_user_logged_in() ){ 
     echo 'You are not logged in. <br /> <a href="' . get_permalink(31) .'">Log In &rarr;</a>';
    
     } else {
    
     $user = wp_get_current_user();
     
    
    $options = array(
      // 'field_groups' => ['group_5cbd99ef0f584'],
      'fields' => ['field_5f24194f719ca'],
      'form_attributes' => array(
        'method' => 'POST',
        'action' => admin_url("admin-post.php"),
      ),
      'html_before_fields' => sprintf(
        '<input type="hidden" name="action" value="adaptiveweb_save_profile_form">
        <input type="hidden" name="user_id" value="user_%s">',
        $user->ID
      ),
      'post_id' => "user_{$user->ID}",
      'form' => true,
      'html_submit_button' => '<button type="submit" class="acf-button button button-primary button-large" value="Update Profile">Update Profile</button>',
    );
    
    acf_form($options);
     }
    
     ?>
     
     </div>
  • Solving

    Restricted-InnerBlocks example: content doesn\'t display

    Hey guys.
    I wanted to understand the new beta features, the innerblocks. So I copied the Code from here:

    https://www.advancedcustomfields.com/blog/acf-5-9-exciting-new-features/

    but nothing is working.

    function.php
    require get_template_directory() . ‘/enqueue/enqueue_blocks.php’;

    enqueue_blocks.php

    <?php
    
    /*Test*/
    add_action('acf/init', 'my_acf_blocks_init');
    function my_acf_blocks_init() {
    
        // Check function exists.
        if( function_exists('acf_register_block_type') ) {
    
            // Register a restricted block.
            acf_register_block_type(array(
                'name'				=> 'restricted',
                'title'				=> 'Restricted',
                'description'		=> 'A restricted content block.',
                'category'			=> 'formatting',
                'mode'				=> 'preview',
                'supports'			=> array(
                    '__experimental_jsx' => true
                ),
                'render_template' => get_template_directory_uri() . '/template-parts/blocks/restricted/restricted.php',
                'enqueue_style' => get_template_directory_uri() . '/template-parts/blocks/restricted/restricted.css'
            ));
        }
    }

    restricted.php

    <?php
    /**
     * Restricted Block Template.
     *
     * @param   array $block The block settings and attributes.
     * @param   string $content The block inner HTML (empty).
     * @param   bool $is_preview True during AJAX preview.
     * @param   (int|string) $post_id The post ID this block is saved to.
     */
    
    // Create class attribute allowing for custom "className" and "align" values.
    $classes = '';
    if( !empty($block['className']) ) {
        $classes .= sprintf( ' %s', $block['className'] );
    }
    if( !empty($block['align']) ) {
        $classes .= sprintf( ' align%s', $block['align'] );
    }
    
    // Load custom field values.
    $start_date = get_field('start_date');
    $end_date = get_field('end_date');
    
    // Restrict block output (front-end only).
    if( !$is_preview ) {
        $now = time();
        if( $start_date && strtotime($start_date) > $now ) {
            echo sprintf( 'Content restricted until %s. Please check back later.
    ', $start_date );
            return;
        }
        if( $end_date && strtotime($end_date) < $now ) {
            echo sprintf( 'Content expired on %s.
    ', $end_date );
            return;
        }
    }
    
    // Define notification message shown when editing.
    if( $start_date && $end_date ) {
        $notification = sprintf( 'Content visible from %s until %s.', $start_date, $end_date );
    } elseif( $start_date ) {
        $notification = sprintf( 'Content visible from %s.', $start_date );
    } elseif( $end_date ) {
        $notification = sprintf( 'Content visible until %s.', $end_date );
    } else {
        $notification = 'Content unrestricted.';
    }
    ?>
    <?php echo var_dump($start_date);?>
    
    <div class="restricted-block <?php echo esc_attr($classes); ?>">
        Test
    
        <span class="restricted-block-notification"><?php echo esc_html( $notification ); ?></span>
        <InnerBlocks  />
    </div>

    restricted.css

    .restricted-block{
        padding: 15px;
        background-color: #0c5460;
        border: 12px solid #20c997;
    }
    
    .restricted-block-notification
    {
        background-color: #43494e;
        padding: 5px;
        float: left;
        color: white;
    }

    I checked the Path – as I saw, the restricted.css file is loading. (network analysis, 304) Also the Data-Blocks is showing up on the right side.

    But the var-dump doesnt show anything and even when I messed up the .php, there doesn’t come a fatal error. But the Path is the Same as the CSS.

    I also made sure, that I downloaded the beta-version.

    so… what i am doing wrong?

reply

  • @nicmare I apologize. Completely my mistake on the formatting.

    add_filter( 'render_block_core/post-title', function( $block_content, $block ) {
    	if(!empty($block["attrs"]["className"]) && $block["attrs"]["className"] == "duration") {
    		return sprintf("<div style='margin-bottom:%s'><strong>%s</strong></div>%s","10px",get_field("clip_duration"),$block_content);
    	} else if (!empty($block["attrs"]["className"]) && $block["attrs"]["className"] == "readAuthor") {
    		$author = get_field('author');
    		foreach( $author as $theAuthor ) {
    			$authorName = get_the_title( $theAuthor->ID );	
    		}
    		return sprintf("<h4>Read / %s</h4>",$authorName,$block_content);
    	} else {
    		return $block_content;
    	}
    }, 10, 2 );
  • what do you think what i am? A machine? I can not read your comment / code. So i can not help you. But placing custom content before/after something is just like changing the order in the code. code for outputting the acf field after the title:

    add_filter( 'render_block_core/post-title', function( $block_content, $block ) {
    	if(!empty($block["attrs"]["className"]) && $block["attrs"]["className"] != "company") return $block_content;
    		
    	return sprintf("%s<div style='margin-top:%s'><strong>%s</strong></div>",$block_content,"10px",get_field("company"));
    }, 10, 2 );
  • @nicmare This worked great to get the contents of a text field output right after a title. But now I want to have multiple injections that show up in different places.

    I modified your code to combine the items. It throws no errors, but when I used your code to output one item, then the other, separately, they worked. After combining them, it no longer works. I wonder if you or anyone else could help.

    
    add_filter( 'render_block_core/post-title', function( $block_content, $block ) {
    	if(!empty($block["attrs"]["className"]) && $block["attrs"]["className"] == "duration") {
    		return sprintf("<div style='margin-bottom:%s'><strong>%s</strong></div>%s","10px",get_field("clip_duration"),$block_content);
    	} else if (!empty($block["attrs"]["className"]) && $block["attrs"]["className"] == "readAuthor") {
    		$author = get_field('author');
    		foreach( $author as $theAuthor ) {
    			$authorName = get_the_title( $theAuthor->ID );	
    		}
    		return sprintf("<h4>Read / %s</h4>",$authorName,$block_content);
    	} else {
    		return $block_content;
    	}
    }, 10, 2 );
    
  • Do you have an ACF field named “post_title”, if not and this is referring to the WP post_title then this is not a meta value and it cannot be searched with a meta query.

    When WP does a search is breaks the search string down into individual words and adds multiple “LIKE” clauses, 1 for each word.

    
    search string = "this is a search"
    LIKE "%this%"
    LIKE "%is%"
    LIKE "%a%"
    LIKE "%search%"
    

    Like queries require enclosing in % characters.

  • Hi there,

    You’re right, my first reply is for front-end orders only.

    Could you try the code below.
    Let me know if it helps (i could re-use it someday).

    Cheers,

    Rémi

    First, we write a small helper function to get and reorder your acf fields

    <?php
    //Helper function - Reorder acf datas
    function maybe_reorder_acf_fields($order_id) {
    	$name 		= get_field('{slug/key}', $order_id) ? get_field('{slug/key}', $order_id) : null; //CHANGE with your own acf slug/key
    	$start_date = get_field('{slug/key}', $order_id) ? get_field('{slug/key}', $order_id) : null; //CHANGE with your own acf slug/key
    	$adults 	= get_field('{slug/key}', $order_id) ? get_field('{slug/key}', $order_id) : null; //CHANGE with your own acf slug/key
    	$children 	= get_field('{slug/key}', $order_id) ? get_field('{slug/key}', $order_id) : null; //CHANGE with your own acf slug/key
    	
    	//Don't remember how datas are validated from get_field() - maybe esc/filter_var functions are useless
    	$custom_acf_metas = array(
    		'_acf_tour_customer_name' => esc_html($name),
    		'_acf_tour_start_date' 	  => esc_html($start_date),
    		'_acf_tour_adults_nbr' 	  => filter_var($adults, FILTER_SANITIZE_NUMBER_INT),
    		'_acf_tour_child_nbr' 	  => filter_var($children, FILTER_SANITIZE_NUMBER_INT)
    	);
    	
    	return $custom_acf_metas;
    }

    Next we use WP save_post hook to add OR overwrite custom metas each time an order is saved in backend.
    https://developer.wordpress.org/reference/hooks/save_post/

    Note : my_save_custom_order_metas() will add your acf datas to all products in an order.
    You may adapt this code and probably your acf datas depending on your needs.

    <?php
    //Add new metas to order item(s)
    add_action( 'save_post', 'my_save_custom_order_metas', 10, 3 );
    function my_save_custom_order_metas( $order_id, $order, $update ) {
    	//Not sure if post revisions are used for shop orders - it returns false on a valid $order_id
    	if ( !is_admin() || get_post_type( $order_id ) !== 'shop_order' || wp_is_post_revision( $order_id ) ) return;
    	
    	//Uncomment those two lines if you want to target specific order status
    	// $order_status = $order->get_status();
    	// if( $order_status !== 'wc-processing' ) return null;
    	
    	$custom_acf_metas = maybe_reorder_acf_fields($order_id);
    	//Loop over every items added to your order
    	if( $order->get_items() ) {
    		foreach ( $order->get_items() as $item_id => $item ) {
    			//Nested loop over reordered ACF datas
    			foreach($custom_acf_metas as $new_meta_key => $new_meta_value) {
    				//Uncomment the two lines below if you don't want to overwrite your values
    				//$new_meta_exists = wc_get_order_item_meta( $item_id, $new_meta_key, true);
    				// if( $new_meta_exists !== false ) continue;
    				if( $new_meta_value !== null ) {
    					//Probably not really needed too - could be useful
    					$new_meta_key = sanitize_key($new_meta_key);
    					$new_meta_value = sanitize_meta( $new_meta_key, $new_meta_value, 'order_itemmeta' );
    					//Add new meta
    					$item->add_meta_data(
    						$new_meta_key,
    						$new_meta_value,
    						true
    					);
    				}
    			}
    			//Don't forget to save modified order here
    			$order->save();
    		}
    	}
    }

    Finally we keep our last 2 woocommerce filters to modify back-end display key + email and customer account item details (human readable for both).

    <?php
    //Modify our custom meta key to make it human readable from back-end
    add_filter('woocommerce_order_item_display_meta_key', 'filter_wc_order_item_display_meta_key', 20, 3 );
    function filter_wc_order_item_display_meta_key( $display_key, $meta, $item ) {
    	//Don't know if there is a better way to retrieve $order_id (and related acf datas)
    	$item_datas = $item->get_data();
    	$order_id = $item_datas['order_id'];
    	$custom_acf_metas = maybe_reorder_acf_fields($order_id);
    	
    	// Change displayed label for specific order item meta key
    	foreach($custom_acf_metas as $new_meta_key => $new_meta_value) {
    		switch($new_meta_key) {
    			case '_acf_tour_customer_name' :
    				$new_display_key = '[your_display_key]'; //CHANGE with your own value
    			break;
    			case '_acf_tour_start_date' :
    				$new_display_key = '[your_display_key]'; //CHANGE with your own value
    			break;
    			case '_acf_tour_adults_nbr' :
    				$new_display_key = '[your_display_key]'; //CHANGE with your own value
    			break;
    			case '_acf_tour_child_nbr' :
    				$new_display_key = '[your_display_key]'; //CHANGE with your own value
    			break;
    		}
    		//Not sure if is_admin is necessary
    		if( is_admin() && $item->get_type() === 'line_item' && $meta->key === $new_meta_key ) {
    			$display_key = __($new_display_key, "my-text-domain" );
    		}
    	}
    	return $display_key;
    }
    
    // Add custom cart item data to emails AND customer account order details
    add_filter( 'woocommerce_order_item_name', 'my_custom_data_in_email', 10, 2 );
    function my_custom_data_in_email( $product_name, $item ) {
    	$item_datas = $item->get_data();
    	$order_id = $item_datas['order_id'];
    	$custom_acf_metas = maybe_reorder_acf_fields($order_id);
    	
    	// Change displayed label for specific order item meta key
    	foreach($custom_acf_metas as $new_meta_key => $new_meta_value) {
    		switch($new_meta_key) {
    			case '_acf_tour_customer_name' :
    				$new_display_key = '[your_display_key]'; //CHANGE with your own value
    			break;
    			case '_acf_tour_start_date' :
    				$new_display_key = '[your_display_key]'; //CHANGE with your own value
    			break;
    			case '_acf_tour_adults_nbr' :
    				$new_display_key = '[your_display_key]'; //CHANGE with your own value
    			break;
    			case '_acf_tour_child_nbr' :
    				$new_display_key = '[your_display_key]'; //CHANGE with your own value
    			break;
    		}
    		if( isset( $item[$new_meta_key] ) ) {
    			$product_name .= sprintf(
    			'<ul><li>%s: %s</li></ul>',
    			__( $new_display_key, 'RemSEO' ),
    			esc_html( $item[$new_meta_key] )
    			);
    		}
    	}
    	return $product_name;
    }
  • Hi Guys – just want to share my workaround idea here…
    assuming you want to place a custom field value before (or after) the post-title block in the loop template, you can give the block a unique classname like in my case “company” and then look for that classname in the following code you need to put in your functions.php

    add_filter( 'render_block_core/post-title', function( $block_content, $block ) {
    	if(!empty($block["attrs"]["className"]) && $block["attrs"]["className"] != "company") return $block_content;
    		
    	return sprintf("<div style='margin-bottom:%s'><strong>%s</strong></div>%s","10px",get_field("company"),$block_content);
    }, 10, 2 );

    thats a pretty robust solution because it uses core code. In my case i need to output the custom field “company” before the post title in of one post in the loop. This will work for the frontend only!

  • Hi there,

    I already made something similar but not with ACF datas.

    Maybe you could try something like below.
    Let me know if it helps.

    Rémi

    <?php
    
    // Add custom cart item data when a product is added to cart from product page
    add_filter( 'woocommerce_add_cart_item_data', 'my_custom_cart_datas', 10, 3 );
    function my_custom_cart_datas( $cart_item_data, $product_id, $variation_id ) {
    	if( !isset( $_POST['new_post_data'] ) ) {
    		$cart_item_data['new_post_data'] = get_field('name', $order_id);;
    	}
    	
    	return $cart_item_data;
    }
    
    // Displaying custom cart datas in cart
    add_filter( 'woocommerce_get_item_data', 'my_display_custom_cart_datas', 10, 2 );
    function my_display_custom_cart_datas( $item_data, $cart_item_data ) {
    	if( isset( $cart_item_data['new_post_data'] ) ) {
    		$item_data[] = array(
    			'name' => __( 'Displayed key', 'my-text-domain' ),
    			'value' => wc_clean($cart_item_data['new_post_data'])
    		);
    	}
    	return $item_data;
    }
    
    // Add custom meta to item (=product) in order (visible in order in back-end)
    add_action( 'woocommerce_checkout_create_order_line_item', 'my_custom_order_line', 10, 4 );
    function my_custom_order_line( $item, $cart_item_key, $values, $order ) {
    	if( isset( $values['new_post_data'] ) ) {
    		$item->add_meta_data(
    			'_new_item_line_meta',
    			$values['new_post_data'],
    			true
    		);
    	}
    }
    
    //Modify our custom meta key display
    add_filter('woocommerce_order_item_display_meta_key', 'filter_wc_order_item_display_meta_key', 20, 3 );
    function filter_wc_order_item_display_meta_key( $display_key, $meta, $item ) {
        // Change displayed label for specific order item meta key
        if( is_admin() && $item->get_type() === 'line_item' && $meta->key === '_new_item_line_meta' ) {
            $display_key = __("Displayed key", "my-text-domain" );
        }
        return $display_key;
    }
    
    // Add custom cart item data to emails
    add_filter( 'woocommerce_order_item_name', 'my_custom_data_in_email', 10, 2 );
    function my_custom_data_in_email( $product_name, $item ) {
    	if( isset( $item['new_post_data'] ) ) {
    		$product_name .= sprintf(
    		'<ul><li>%s: %s</li></ul>',
    		__( 'Displayed key', 'my-text-domain' ),
    		esc_html( $item['_new_item_line_meta'] )
    		);
    	}
    	return $product_name;
    }
  • Thank you John,

    I have simplified my code to the one below. However, upon form submit the WordPress site crashes. Is there anything wrong with this code?

    <?php
        acf_form_head();
        get_header();
    ?>
    
    <div id="content">
        <div class="wrap">
            <form id='post' class='acf-form' action='' method='post'>
    
                <?php
                    $field_groups = array('group_596925d98777d');
                    acf_form([
                        'field_groups'  => $field_groups,
                        'post_id'       => 'new_post',
                        'new_post'      => array(
                            'post_category' => 'academy',
                            'post_status'   => 'draft',
                            'post_title'    => $post_id,
                         ),                  
                        'post_content'  => false,
                        'form'          => false,
                        'submit_value'  => __("Submit post", 'acf'),
                        'updated_message' => __("Thank you!", 'acf'),
                        'html_updated_message' => '<div id="message" class="updated" style="display:block;"><p>%s</p></div>'
                    ]);
                ?>
    
            </form>
    
        </div>
    </div>
    
    <?php get_footer();
  • It’s interestingly enough related to the square brackets in the shortcode that I’m trying to store.

    The following works fine:

    
    'shortcode' => $user_monthly_fee['shortcode'] ?:
        sprintf('pricing_user_monthly_fee id="%s"', uniqid()),
    );
    

    While the following doesn’t store the shortcode:

    
    'shortcode' => $user_monthly_fee['shortcode'] ?:
        sprintf('[pricing_user_monthly_fee id="%s"]', uniqid()),
    );
    
  • You can Show this by using:
    <?php

    $tags = wp_get_post_tags(get_the_ID());
    if ($tags) {
    foreach ($tags as $tag) {
    if ($tag->description) {
    echo ‘<dt>term_id ) . ‘” title=”‘ . sprintf( __( “View all posts in %s” ), $tag->name ) . ‘” ‘ . ‘>’ . $tag->name.’</dt><dd>’ . $tag->description . ‘</dd>’;
    }
    }
    }

    ?>

  • It works with Desktop/Mobile.

    <?php 
    $location = get_field('location');
    if( $location ) {
    
        // Loop over segments and construct HTML.
        $address = '';
        foreach( array('street_number', 'street_name', 'city', 'state', 'post_code', 'country') as $i => $k ) {
            if( isset( $location[ $k ] ) ) {
                $address .= sprintf( '<span class="segment-%s">%s</span>, ', $k, $location[ $k ] );
            }
        }
    
        // Trim trailing comma.
        $address = trim( $address, ', ' );
    
        // Display HTML.
        echo '<p>' . $address . '. </p>';
    }
    ?>
    
    <a href="https://www.google.com/maps/place/<?php echo str_replace(' ','+',$location['address']); ?>" target="_blank"> Map adress link </a>
    
  • Hello, I’m currently experiencing the same thing, I’m getting a blank screen after form update/ submission.

    It was working fine until the latest version of WordPress and an upgrade to PHP 7.4.

    Did you ever solve this problem?

    My code to generate the form.

      acf_form(array(
            'id' => 'acf-form-quick',
            'post_title'  => false,
            'post_content' => true,
            'field_groups' => array('group_5a3824afd298b','group_5cb4e53b433ea','group_583f59f20ee1','group_5a38276e809f8','group_5a3827b18c5c0','group_57f6b7add6a3d'),
            'submit_value'  => __('Update Project', 'acf'),
            'html_submit_button'  => '<input type="submit" class="acf-button uk-button uk-button-primary btn3d uk-margin-large-bottom uk-align-center" value="%s" />',
            'return' => '%post_url%'
            ));
  • Just an quick update, this issue will work – but as @dominik_fuchshofer suggested, if there is a current autosave it will still be broken.

    We’ll need to do some more internal code changes to handle autosaves – but disabling them as Dominik’s code should solve the issue for now, while we can get the release ready.

    Could you try the following code, and see if you have any issues?

    function acf_filter_rest_api_preload_paths( $preload_paths ) {
    	global $post;
    	$rest_path    = rest_get_route_for_post( $post );
    	$remove_paths = array(
    		add_query_arg( 'context', 'edit', $rest_path ),
    		sprintf( '%s/autosaves?context=edit', $rest_path ),
    	);
    
    	return array_filter(
    		$preload_paths,
    		function( $url ) use ( $remove_paths ) {
    			return ! in_array( $url, $remove_paths, true );
    		}
    	);
    }
    add_filter( 'block_editor_rest_api_preload_paths', 'acf_filter_rest_api_preload_paths', 10, 1 );
  • Edit the right code :

    					<?php $args = array(
    						'taxonomy' => 'marques-produits',
    					    'orderby' => 'name',
    					    'order'   => 'ASC'
    					    );	
    					$cats = get_categories($args);
    					foreach($cats as $cat) {
    						$logo = get_field('logo_marque', 'marques-produits_'. $cat->term_id .'');
    						echo 
    						'<a href="' . get_category_link( $cat->term_id ) . '" title="' . sprintf( __( "Voir tout les produits %s" ), $cat->name ) . '">
    							<img src="' . $logo['url']; ?>" alt="<?php echo $logo['alt'] . '">
    						</a>';
    						}
    					?>
    
Viewing 25 results - 26 through 50 (of 180 total)