Support

Account

Home Forums Search Search Results for 'q'

Search Results for 'q'

reply

  • Group field, the field has a value that was updated on the frontend with update_field(), I’m able to pull the value and display it normally.

    However, the problem is only when filtering with “meta_query”, I’m not able to pull users with that value unless I manually update the user in the backend (without changing anything).

    Just by doing that it will work and display the user in the loop, otherwise it doesn’t work, but I can’t manually update all users every time.

    So again, everything works, I can update the value and display it, etc. But when using “meta_query” to filter users it doesn’t work until I manually update that user.

  • Still nothing, same issue.

    Not including the group name always returns empty. In addition to that, all tutorials I’ve read asked to add the group name, so much so that it works, but with the problem that I mentioned:

    $speaks = 9;

    (no quotes) ‘value’ => $speaks = returns a partial match too (9, 19, 29…)

    (with quotes) ‘value’ => ‘”‘.$speaks.'”‘ = returns a full match as it should, but only if I, at some point, manually clicked on “Update user” in the backend.

  • @room34 – this very annoying and very perplexing issue showed up for me as well, also on a multisite installation. I just wanted to say that, while you got no response here to your question, thanks to you returning to the forum with your solution, you likely saved me hours and hours of troubleshooting (and several gray hairs).

    Thanks for sharing your knowledge!

    (It also appears that there’s some semi-significant bug somewhere that may need further investigation)

  • Yes, you need to wrap the value in quotes

    
    'value' => '”'.$speaks.'”',
    

    your meta key should be just the field name, do not include the field group name

    
    'key' => 'user_lang_spoken',
    
  • I am experiencing this as well. I cannot make changes to an existing group.

    TypeError: Cannot convert undefined or null to object
        at Function.entries (<anonymous>)
        at acf.Model.addProLocations (acf-field-group.min.js?ver=6.2.0:1:25790)
        at acf.Model.initialize (acf-field-group.min.js?ver=6.2.0:1:25516)
        at acf.Model.e (acf.min.js?ver=6.2.0:1:3259)
        at o (acf.min.js?ver=6.2.0:1:1405)
        at Object.doAction (acf.min.js?ver=6.2.0:1:575)
        at n.doAction (acf.min.js?ver=6.2.0:1:19006)
        at HTMLDocument.<anonymous> (acf.min.js?ver=6.2.0:1:28275)
        at e (load-scripts.php?c=0&load%5Bchunk_0%5D=jquery-core,jquery-migrate,utils,wp-polyfill-inert,regenerator-runtime,wp-polyfill,wp-hooks&ver=6.2.2:2:30158)
        at t (load-scripts.php?c=0&load%5Bchunk_0%5D=jquery-core,jquery-migrate,utils,wp-polyfill-inert,regenerator-runtime,wp-polyfill,wp-hooks&ver=6.2.2:2:30460)
  • Here’s what I think is the complete rundown:

    I’m using this URL:

    /testing/?image_id=8324

    There’s nothing on that page except for:

    [test_shortcode]

    And just to confirm I’m using the correct field name, here’s the source code of the field in the backend when editing an image:

    
    <tr class="acf-field acf-field-number acf-field-64e143e0efab0" data-name="image_meta_image_id" data-type="number" data-key="field_64e143e0efab0">
    <td class="acf-label">
    <label for="acf-field_64e143e0efab0">Image ID</label></td>
    <td class="acf-input">
    <div class="acf-input-wrap"><input type="number" id="acf-field_64e143e0efab0" name="acf[field_64e143e0efab0]" value="8324" step="any"></div></td>
    </tr>
    

    And here’s the complete shortcode:

    
    function get_test_shortcode() {
      $image_meta_image_id = $_GET["image_id"];
      // echo $image_meta_image_id;
      // *********************** FROM ACF FORUM 09-01-2023 ***********************
      // first you do a query for attachments looking for the exact image_meta_image_id
      $args = array(
          'fields' => 'ids', // return only IDs to use in the next query
          'posts_per_page'    => 1, // there should only be one image
                                    // with this "image_meta_image_id"
          'post_type'      => 'attachment',
          'meta_query'    => array(
        		array(
        			'key'	 	=> 'image_meta_image_id',
        			'value'	  	=> $image_meta_image_id
        		)
        	)
      );
      $attachment_query = new WP_Query( $args );
      $attachments = $attachment_query->posts();
    
    echo "<pre>";
      var_dump( $attachments );
    echo "</pre>";
    
    }
    add_shortcode( 'test_shortcode', 'get_test_shortcode' );
    

    The only thing showing on the page is the page title TESTING and bool(false).

    Do you see anything amiss?

    Thanks again!!

  • Here’s var_dump( $attachment_query );

    
    object(WP_Query)#3978 (52) {
      ["query"]=>
      array(4) {
        ["fields"]=>
        string(3) "ids"
        ["posts_per_page"]=>
        int(1)
        ["post_type"]=>
        string(10) "attachment"
        ["meta_query"]=>
        array(1) {
          [0]=>
          array(2) {
            ["key"]=>
            string(19) "image_meta_image_id"
            ["value"]=>
            string(5) "17574"
          }
        }
      }
      ["query_vars"]=>
      array(66) {
        ["fields"]=>
        string(3) "ids"
        ["posts_per_page"]=>
        int(1)
        ["post_type"]=>
        string(10) "attachment"
        ["meta_query"]=>
        array(1) {
          [0]=>
          array(2) {
            ["key"]=>
            string(19) "image_meta_image_id"
            ["value"]=>
            string(5) "17574"
          }
        }
        ["error"]=>
        string(0) ""
        ["m"]=>
        string(0) ""
        ["p"]=>
        int(0)
        ["post_parent"]=>
        string(0) ""
        ["subpost"]=>
        string(0) ""
        ["subpost_id"]=>
        string(0) ""
        ["attachment"]=>
        string(0) ""
        ["attachment_id"]=>
        int(0)
        ["name"]=>
        string(0) ""
        ["pagename"]=>
        string(0) ""
        ["page_id"]=>
        int(0)
        ["second"]=>
        string(0) ""
        ["minute"]=>
        string(0) ""
        ["hour"]=>
        string(0) ""
        ["day"]=>
        int(0)
        ["monthnum"]=>
        int(0)
        ["year"]=>
        int(0)
        ["w"]=>
        int(0)
        ["category_name"]=>
        string(0) ""
        ["tag"]=>
        string(0) ""
        ["cat"]=>
        string(0) ""
        ["tag_id"]=>
        string(0) ""
        ["author"]=>
        string(0) ""
        ["author_name"]=>
        string(0) ""
        ["feed"]=>
        string(0) ""
        ["tb"]=>
        string(0) ""
        ["paged"]=>
        int(0)
        ["meta_key"]=>
        string(0) ""
        ["meta_value"]=>
        string(0) ""
        ["preview"]=>
        string(0) ""
        ["s"]=>
        string(0) ""
        ["sentence"]=>
        string(0) ""
        ["title"]=>
        string(0) ""
        ["menu_order"]=>
        string(0) ""
        ["embed"]=>
        string(0) ""
        ["category__in"]=>
        array(0) {
        }
        ["category__not_in"]=>
        array(0) {
        }
        ["category__and"]=>
        array(0) {
        }
        ["post__in"]=>
        array(0) {
        }
        ["post__not_in"]=>
        array(0) {
        }
        ["post_name__in"]=>
        array(0) {
        }
        ["tag__in"]=>
        array(0) {
        }
        ["tag__not_in"]=>
        array(0) {
        }
        ["tag__and"]=>
        array(0) {
        }
        ["tag_slug__in"]=>
        array(0) {
        }
        ["tag_slug__and"]=>
        array(0) {
        }
        ["post_parent__in"]=>
        array(0) {
        }
        ["post_parent__not_in"]=>
        array(0) {
        }
        ["author__in"]=>
        array(0) {
        }
        ["author__not_in"]=>
        array(0) {
        }
        ["search_columns"]=>
        array(0) {
        }
        ["ignore_sticky_posts"]=>
        bool(false)
        ["suppress_filters"]=>
        bool(false)
        ["cache_results"]=>
        bool(true)
        ["update_post_term_cache"]=>
        bool(true)
        ["update_menu_item_cache"]=>
        bool(false)
        ["lazy_load_term_meta"]=>
        bool(true)
        ["update_post_meta_cache"]=>
        bool(true)
        ["nopaging"]=>
        bool(false)
        ["comments_per_page"]=>
        string(2) "50"
        ["no_found_rows"]=>
        bool(false)
        ["order"]=>
        string(4) "DESC"
      }
      ["tax_query"]=>
      object(WP_Tax_Query)#3417 (6) {
        ["queries"]=>
        array(0) {
        }
        ["relation"]=>
        string(3) "AND"
        ["table_aliases":protected]=>
        array(0) {
        }
        ["queried_terms"]=>
        array(0) {
        }
        ["primary_table"]=>
        string(8) "wp_posts"
        ["primary_id_column"]=>
        string(2) "ID"
      }
      ["meta_query"]=>
      object(WP_Meta_Query)#3983 (9) {
        ["queries"]=>
        array(2) {
          [0]=>
          array(2) {
            ["key"]=>
            string(19) "image_meta_image_id"
            ["value"]=>
            string(5) "17574"
          }
          ["relation"]=>
          string(2) "OR"
        }
        ["relation"]=>
        string(3) "AND"
        ["meta_table"]=>
        string(11) "wp_postmeta"
        ["meta_id_column"]=>
        string(7) "post_id"
        ["primary_table"]=>
        string(8) "wp_posts"
        ["primary_id_column"]=>
        string(2) "ID"
        ["table_aliases":protected]=>
        array(1) {
          [0]=>
          string(11) "wp_postmeta"
        }
        ["clauses":protected]=>
        array(1) {
          ["wp_postmeta"]=>
          array(6) {
            ["key"]=>
            string(19) "image_meta_image_id"
            ["value"]=>
            string(5) "17574"
            ["compare"]=>
            string(1) "="
            ["compare_key"]=>
            string(1) "="
            ["alias"]=>
            string(11) "wp_postmeta"
            ["cast"]=>
            string(4) "CHAR"
          }
        }
        ["has_or_relation":protected]=>
        bool(false)
      }
      ["date_query"]=>
      bool(false)
      ["request"]=>
      string(472) "
    			SELECT SQL_CALC_FOUND_ROWS  wp_posts.ID
    			FROM wp_posts  INNER JOIN wp_postmeta ON ( wp_posts.ID = wp_postmeta.post_id )
    			WHERE 1=1  AND ( 
      ( wp_postmeta.meta_key = 'image_meta_image_id' AND wp_postmeta.meta_value = '17574' )
    ) AND ((wp_posts.post_type = 'attachment' AND (wp_posts.post_status = 'publish' OR wp_posts.post_status = 'acf-disabled' 
    OR wp_posts.post_status = 'private')))
    			GROUP BY wp_posts.ID
    			ORDER BY wp_posts.post_date DESC
    			LIMIT 0, 1
    		"
      ["posts"]=>
      array(0) {
      }
      ["post_count"]=>
      int(0)
      ["current_post"]=>
      int(-1)
      ["before_loop"]=>
      bool(true)
      ["in_the_loop"]=>
      bool(false)
      ["comment_count"]=>
      int(0)
      ["current_comment"]=>
      int(-1)
      ["found_posts"]=>
      int(0)
      ["max_num_pages"]=>
      int(0)
      ["max_num_comment_pages"]=>
      int(0)
      ["is_single"]=>
      bool(false)
      ["is_preview"]=>
      bool(false)
      ["is_page"]=>
      bool(false)
      ["is_archive"]=>
      bool(false)
      ["is_date"]=>
      bool(false)
      ["is_year"]=>
      bool(false)
      ["is_month"]=>
      bool(false)
      ["is_day"]=>
      bool(false)
      ["is_time"]=>
      bool(false)
      ["is_author"]=>
      bool(false)
      ["is_category"]=>
      bool(false)
      ["is_tag"]=>
      bool(false)
      ["is_tax"]=>
      bool(false)
      ["is_search"]=>
      bool(false)
      ["is_feed"]=>
      bool(false)
      ["is_comment_feed"]=>
      bool(false)
      ["is_trackback"]=>
      bool(false)
      ["is_home"]=>
      bool(true)
      ["is_privacy_policy"]=>
      bool(false)
      ["is_404"]=>
      bool(false)
      ["is_embed"]=>
      bool(false)
      ["is_paged"]=>
      bool(false)
      ["is_admin"]=>
      bool(false)
      ["is_attachment"]=>
      bool(false)
      ["is_singular"]=>
      bool(false)
      ["is_robots"]=>
      bool(false)
      ["is_favicon"]=>
      bool(false)
      ["is_posts_page"]=>
      bool(false)
      ["is_post_type_archive"]=>
      bool(false)
      ["query_vars_hash":"WP_Query":private]=>
      string(32) "79faba4333b88670ed32918a2aeeae58"
      ["query_vars_changed":"WP_Query":private]=>
      bool(false)
      ["thumbnails_cached"]=>
      bool(false)
      ["allow_query_attachment_by_filename":protected]=>
      bool(false)
      ["stopwords":"WP_Query":private]=>
      NULL
      ["compat_fields":"WP_Query":private]=>
      array(2) {
        [0]=>
        string(15) "query_vars_hash"
        [1]=>
        string(18) "query_vars_changed"
      }
      ["compat_methods":"WP_Query":private]=>
      array(2) {
        [0]=>
        string(16) "init_query_flags"
        [1]=>
        string(15) "parse_tax_query"
      }
    }
    
  • Not sure what is wrong with the first query. If it is returning false then it’s not finding any posts (attachments) that match. Number of posts or meta rows should not matter.

    Try dumping $attachment_query

  • Thanks for the help. This makes sense to me, but I’m getting bool(false) when I var_dump the first query.

    Using this:

    
      $image_meta_image_id = $_GET["image_id"];
      echo $image_meta_image_id;  // doing this to make sure it's getting it from the URL.
      // first you do a query for attachments looking for the exact image_meta_image_id
      $args = array(
          'fields' => 'ids', // return only IDs to use in the next query
          'posts_per_page'    => 1, // there should only be one image
                                    // with this "image_meta_image_id"
          'post_type'      => 'attachment',
          'meta_query'    => array(
        		array(
        			'key'	 	=> 'image_meta_image_id',
        			'value'	  	=> $image_meta_image_id
        		)
        	)
      );
      $attachment_query = new WP_Query( $args );
    
      $attachments = $attachment_query->posts();
    
      echo "<pre>";
      var_dump( $attachments );
      echo "</pre>";
    

    I’ve confirmed that the image I’m trying to get has the correct value for its image_meta_image_id field (It’s 17574).

    Any ideas?

    Thanks a bunch for the help!

  • 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;
    }
  • 
    // first you do a query for attachments looking for the exact image_meta_image_id
    $args = array(
        'fields' => 'ids', // return only IDs to use in the next query
        'posts_per_page'    => 1, // there should only be one image 
                                  // with this "image_meta_image_id"
        'post_type'      => 'attachment',
        'meta_query'    => array(
      		array(
      			'key'	 	=> 'image_meta_image_id',
      			'value'	  	=> $image_meta_image_id
      		)
      	)
    );
    $attachment_query = new WP_Query();
    $attachments = $attachment_query->posts();
    
    // now you need to do a query to get all of the posts what use that attachment
    // if it was found
    if (!empty($attachments)) {
      $args = array(
        'post_type' = 'your post type',
        'posts_per_page' => -1,
        'meta_query' => array(
          array(
            'key' => 'gallery field name',
            'value' => '"'.$attachments[0].'"',
            'compare' => 'LIKE'
          )
        )
      ); 
    } // end if attachments found
    
  • You lost me here

    The field group is associated with user role

    Do you mean a user? ACF cannot be associated with a “Role”, unless you mean that the field group is only shown on the user edit page when the logged in user has a specific role.

  • The ACF relationship field uses the built in search mechanism. If any word you type is in the title or content of the post then it will appear in the list. If the exact phrase appears then it should be closer to the top, but it needs to be exact.

    How WP Search Works

    ACF only loads a few posts at a time, not sure of the number. If it stops before it has shown all the possibilities then there might be an error during the AJAX request. You might be able to figure out the error by turning on error logging.

  • Quick addendum to this thread because I used it today to update the site_icon. It seems the custom_logo is set by using theme_mod, not update_option (did not work for me).

    The complete code for updating the website logo should be:
    set_theme_mod('custom_logo',get_field('field_name','options', false), true);

    Hopefully this helps someone.

  • The user must already exist so that the user ID you are importing actually matches a user ID already added. You will not be able to import the users and do the relationships in the same import.

    Absolutely right!
    Thanks for your advice and your help!

  • check out my query loop solution with some custom code

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

  • Yes it is a permission issue. I don’t know the specifics of what you need to do.

    This has come up often in the past and one of those topics might have a solution.
    [Forum Search Results]

  • To get an ACF field associated with the user you need to provide the user id in the form of "user_{$user_id}" or the user object as returned by wp_get_current_user()

    
    $user_id = get_current_user_id();
    $value = get_field('field_name', 'user_'.$user_id);
    
    // OR
    
    $user = wp_get_current_user();
    $value = get_field('field_name', $user);
    
  • I have had this happen before when someone clicks on the buttons that allow reordering of field groups. I don’t know what causes it but it appears to happen when moving a metabox might change the location (high, normal, side).

    To correct this you need to go into the usermeta table in the DB and delete and find the users meta box order entry for the post type and delete it. The meta key will be "meta-box-order_{$post_type}"

    You will find a lot of posts on the internet about this, but no good solutions. There are sometimes plugins that can be used but they are generally not maintained well.

  • You’re URL is going to be different dependent on if they use the “URL” from the browser bar or the URL from the “Share” feature on youtube. Parsing out the id will require accounting for all possibilities.

    A URL field must have a valid URL, only a text field would work for holding just the video ID, so you cannot modify a URL field to hold just the video ID. If you did this then then the field may be blank when the admin reloads and if not it would create a validation error on the next save.

    Updating one field based on another field is as simple as using an acf/save_post action that gets the value from the URL field, parses out the video id and then use update_field() to update the other field.

    I would not do this, instead I would create and acf/format_value filter with a priority > 10 to run after ACF and I would parse out the video id in and return it in this filter.

  • even when I type in the exact post name the content won’t populate

    Does that mean that you see nothing at all or that you see a lot of results?

  • This topic has come up multiple times and some of those have code in them
    [Forum Search Results]

  • 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;
    }
  • Hi there,

    This is an old thread but if my code could be useful, i let it here.

    IMPORTANT : Please test it in a dev environment before.
    I adapted and didn’t test the multisite adaptations.
    It works on a single wordpress installation on ACF 5.1.5+ (tested on acf 6.2)

    Note 1 : i hooked on ‘admin_init’ but maybe there is a better hook.
    Note 2 : Tested on WP 6.2 only but i guess it would work far below as we only use get_post() and wp_update_post()

    Feel free to correct it and share it 🙂

    
    <?php
    //Modify ACF group/fields setting and save it globally (DB + local JSON)
    add_action('admin_init', 'modify_acf_settings');
    function modify_acf_settings() {
    	//Working on specific fields/posts/groups - REPLACE with your own keys
    	$acf_posts_to_update = array(1234);
    	$acf_groups_to_sync = array('group_12345678abcde'); //Used only if you're using local JSON
    	$acf_fields_to_update = array( 'field_12345678abcde' );
    	$stored_posts = array();
    	$stored_acf_groups = array();
    	
    	//You could modify any field settings from here
    	//@see https://www.advancedcustomfields.com/resources/acf-update_field/
    	foreach($acf_fields_to_update as $field) {
    		$is_field_exists = get_field_object($field);
    		if($is_field_exists !== false) {
    			$filter_identifier = strval('acf/update_field/key='.$field);
    			add_filter($filter_identifier, function($field) {
    				//$field['required'] = true;
    				//etc...
    			}, 10, 1);
    		}
    	}
    	
    	//Then we use WP native functions to modify ACF posts
    	$updated_post = false;
    	$i = 0;
    	foreach($acf_posts_to_update as $post_to_update) {
    		$post_obj = get_post($post_to_update);
    		//You could grab and modify any datas returned with get_post()
    		// Example -> $post_content = $post_obj->post_content;
    		
    		if($post_obj !== null) {
    			//Here i want to active a disable group if woocommerce is active
    			//All we have to do is change the post status (as ACF groups are basically custom post types)
    			if (&& in_array( 'woocommerce/woocommerce.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ) ) ) {
    				$current_status = $post_obj->post_status;
    				if($current_status == 'acf-disabled') {
    					$post_obj->post_status = 'publish';
    				}
    				//Don't forget to update post and validate/re-serialize modified datas if needed
    				wp_update_post( $post_obj );
    				$updated_post = true;
    				$stored_post[$i] = $post_obj;
    			} else {
    				//Disable it if woocommerce is not active and the group is publish
    				$current_status = $post_obj->post_status;
    				if($current_status == 'publish') {
    					$post_obj->post_status = 'acf-disabled';
    				}
    				wp_update_post( $post_obj );
    				$updated_post = true;
    				$stored_post[$i] = $post_obj;
    			}
    		}
    	$i++;
    	}
    	
    	//Last step - Sync modified posts with JSON files
    	//note : using $updated_post but you could use any check
    	$update_modified_group = false;
    	if ( $updated_post === true ) {
    		$i = 0;
    		foreach($acf_groups_to_sync as $acf_group) {
    			$group_to_save = acf_get_field_group($acf_group);
    			$group_to_save['active'] = 1;
    			$update_modified_group = acf_write_json_field_group( $group_to_save );
    			//Add an admin notice is group was not savec correctly
    			if( boolval($update_modified_group) !== true ) {
    				add_action( 'admin_notices', 'acf_not_sync_notice' );
    			} else {
    				$stored_acf_groups[$i] = $group_to_save;
    			}
    		$i++;
    		}
    	}
    	
    	//Finally, we will sync changes in other $blog in a multisite network
    	$current_blog_id = get_current_blog_id();
    	$sites = get_sites( 
    		array( 
    			'number' => 50,
    			'site__not_in' => $current_blog_id, // exclude current site from the loop
    		) 
    	);
    	foreach( $sites as $site ) {
    		switch_to_blog( $site->blog_id );
    		if( is_array($stored_post) && !empty($stored_post) ) {
    			foreach($stored_post as $post) {
    				wp_update_post( $post );
    			}
    		}
    		
    		if( is_array($stored_acf_groups) && !empty($stored_acf_groups) ) {
    			foreach($stored_acf_groups as $group) {
    				$update_modified_group = acf_write_json_field_group( $group );
    			}
    		}
    	}
    	
    	//Don't forget to restore environnement
    	restore_current_blog();
    }
    
    function acf_not_sync_notice() {
        ?>
        <div class="notice error my-acf-notice is-dismissible" >
            <p><?php _e( 'Some ACF fields were not synced correctly. Please save the group fields manually.', 'my-text-domain' ); ?></p>
        </div>
    
        <?php
    }
Viewing 25 results - 3,226 through 3,250 (of 21,345 total)