Support

Account

Home Forums Search Search Results for 'q'

Search Results for 'q'

reply

  • calling acf_form_head() is required before get_header() or before any output is created in header.php. Nothing will be created if you don’t because this function, or functions called by this function is where the apply_filters('acf/pre_save_post'... is called. Basically, nothing will be saved if this acf_form_head() is not called.

    The only error I see in your filter is

    
    
        //register user
        $user_id = wp_create_user( $username, $password, $email );
    
        //update other user info
        wp_update_user( array(
            'ID'            => $user_id,
            'first_name'    => $_POST['fields']['field_593642087f8f5'],
            'last_name'     => $_POST['fields']['field_593642267f8f6'],
            'display_name'  => $_POST['fields']['field_593642087f8f5'] . ' ' . $_POST['fields']['field_593642267f8f6']
        ) );
    
       // if you don't want the above fields also saved as custom fields for the user
      unset(
        $_POST['fields']['field_593642087f8f5'],
        $_POST['fields']['field_593642267f8f6'],
        $_POST['fields']['field_593642087f8f5'],
        $_POST['fields']['field_593642267f8f6']
      )
        
        // for ACF, you need to return
        return 'user_'.$user_id;
    
  • Good points John. It makes my head hurt just thinking about the variations that can exist with those complex fields and nesting. I’ve seen similar situations discussed involving a range of other features as well. It makes me wonder if there is some better system for handling nested field data to avoid the use of indexes in the meta key names… not sure if I’m describing that clearly enough but I’m referring to ‘flex_field_1_text’ where as you mentioned we often need to “figure out how many layouts the second post already has and then substitute the correct index”.

    I think the approach I might prefer (of course I understand I may not be thinking of all the requirements here) is to have nested field data assigned a unique id and then referenced by json. Essentially so that if you could access that main reference data, you would then be able to track down it’s rows.

    If I were to tackle something like this I this I’d try to utilize the loading and storage native to the ACF API as much as possible. Meaning first try to identify if the fields/types/groups are used for the given post. Don’t try to copy or get the data at that point, just organize the results of that test. Then use the get_field() and save_field(). It seems more likely that we could deal with the various complexities by loading the data with get_field(), but I think processing that before using save_field() would still be a massive undertaking.

  • sub fields do not need to have unique names.

    Technical reason: Sub fields are stored as "{$repeater_name}_{$index}_{$sub_field_name}" It is important that the top level fields have unique names.

  • this looks like a good place to start https://wordpress.stackexchange.com/questions/30869/how-to-use-a-custom-post-type-as-front-page

    EDIT: Oh, I don’t think you can change the options to show custom post types in the drop down. That drop down calls this function to get the list of pages wp_dropdown_pages() https://developer.wordpress.org/reference/hooks/wp_dropdown_pages/. this function only has one filter https://codex.wordpress.org/Function_Reference/wp_dropdown_pages and it is for the HTML string that’s returned with no way of really knowing what the string is generated for so if you altered this you’d pretty much be altering the output no matter where it is used.

  • In copying something like a layout in a flex field, the problem becomes complex. Here is an example. Let’s say that the post where your copying from has 2 layouts and you want to copy the second one and the post you’re copying to has a different number, in this case let’s say it has 3 already and the copy will become the forth. Let’s say for this example, to make it simple, that the flex field is named “flex_field” and it has just one text field in the layout named “text” and let’s say that the field key of the flex field is “field_123” and the field key of the sub field is “field_321”. Let’s say also to make it really simple there is only one layout named “layout_1”

    The database will look something like this for the post you are copying the layout from

    
    meta_key           | meta_value
    flex_field         | a:2:{i:0;s:8:"layout_1";i:1;s:8:"layout_1";}
    _flex_field        | field_123
    flex_field_0_text  | content for first layout text field
    _flex_field_0_text | field_321
    flex_field_1_text  | content for second layout text field
    _flex_field_1_text | field_321
    

    and this would be to db content for the post you want to copy to

    
    meta_key           | meta_value
    flex_field         | a:3:{i:0;s:8:"layout_1";i:1;s:8:"layout_1";i:2;s:8:"layout_1";}
    _flex_field        | field_123
    flex_field_0_text  | content for first layout text field
    _flex_field_0_text | field_321
    flex_field_1_text  | content for second layout text field
    _flex_field_1_text | field_321
    flex_field_2_text  | content for 3rd layout text field
    _flex_field_2_text | field_321
    

    The entry for the flex field is a serialized array containing the names of each layout. Each entry in the db for a field has a corresponding entry that starts with _ to hold the field key of that field. And you can see that each sub field is a concatenation of the flex field name, the index of the row and the sub field name.

    To copy the 2nd layout of the 1st post to the second post you need to get the flex field array from both and append the layout name from the 1st post to the 2nd post. You then need to get the content of the row from the 1st post, figure out how many layouts the second post already has and then substitute the correct index for the current index of all of the field keys.

    The above is the simplest example, but to do this within ACF this is not the only example you need to worry about. What if the flex field is actually a sub field of another repeater type field (repeater, flex or clone) then you’ve also go to take the parent field names and row indexes into consideration as well. Not to mention a possible grand parent repeater. These things may seem unlikely, but they are completely possible since ACF puts no limit on the depth that we can nest repeaters. If this was built into ACF all of the possibilities would need to be accounted for. There is also the possibility that the post that is being copied to does not yet have any entry for the flex field yet (or the parent, or the grand parent, etc). I’m not saying that it’s not possible, but what seems simple to start with becomes an extremely complex problem to solve. This could be a contributing factor for why this has been requested often but has not been built by the developer, not while there’s lower fruit on the tree.

    While it would be great to have something like this built into ACF, for someone that want to provide this functionality to a client it would be much, much easier to build some type of copy function for a specific set of conditions rather than the endless number of conditions that may exist to built it into the core of ACF.

  • If we call that feature say “selective copying of field data” meaning you can select specific fieldtype, or fieldgroup, then yes I’d agree that’s more of an ACF-specific feature.

    I think there might be a couple of different ways to do that but something like the process below would be needed:

    1. Pass in the selection of fieldtypes, fieldgroups to the class, perhaps an arguments array like $args = array(‘fieldtypes’ => array( ‘repeater’ ));. Or a setter like $copyPost->setAcfFieldTypes( array(‘image’, ‘flex’) );

    2. When looping over all meta data, load the field associated using the meta name to find the key. Then check if the fieldtype matches that array of fieldtypes to copy. Similar idea for fieldgroups, essentially find out if they that meta data item should be copied. Use continue to skip over meta that doesn’t match the criteria.

    3. When matches are found, copy it the same as shown in that snippet using the queries.

    Having to handle the data one item at a time might not be very efficient in terms of queries but it’s probably possible to delay the query until all the data has been organized.

  • I am using the 'form' => false, option to provide the ACF fields within my own form HTML.

    I just added my own plain html field with the id acf-_post_title and name acf[_post_title] and everything worked as expected.

    <input type="hidden" id="acf-_post_title" name="acf[_post_title]" value="Anonymous Response">

    I provided a default title that worked for me, and then used a bit of jQuery to change the value based on user input to other fields. My example fills in the first and last name fields if they are not empty and if an anonymous checkbox is not checked.

    $('#acf-field_590bacbe30591, #acf-field_590bacd630592, #acf-field_590bad1230595').on('change', function() {
    	var fname = $('#acf-field_590bacbe30591').val();
    	var lname = $('#acf-field_590bacd630592').val();
    	var anon = $('#acf-field_590bad1230595').attr('checked');
    	if ( anon == 'checked' || ( fname == '' && lname == '' ) ) {
    		$('#acf-_post_title').val("Anonymous Response");
    	}
    	else {
    		$('#acf-_post_title').val("Response from " + fname + " " + lname);
    	}
    });
  • Well, bust my buttons!! You’re right! Duplicate Post does include all custom fields (I just tested it on a site). Sometimes it’s sweet to be wrong.

    Regarding the other issue, I checked out the code for the QuizMaster plugin and the method for copying all custom fields for the CPT’s is very succinct, just 2 queries. What would be the method, however, for targeting a specific field group, like a flex field group, and copying only those contents to another post?

    By the way, I understand that this isn’t necessarily an ACF issue, but a WordPress custom fields issue. However, doing such a duplication would most likely happen in the context of ACF, making it the more practical arbiter of the situation. Does that make sense?

    Thanks, goldhat!

  • This reply has been marked as private.
  • Well, here’s how to do it in 5.5.13:

    add_filter('acf/load_value/key= key_58c7ee3a37aee', 'default_value_ key_58c7ee3a37aee', 10, 3);
    function default_value_ key_58c7ee3a37aee($value, $post_id, $field) {
        if ($value === false) {
            $value = array(
                array(
                    'field_58984ddb5b8cc' => 'My title',
                    'field_58985045abac0' => 'My content',
                ),
                array(
                    'field_58984ddb5b8cc' => 'Another title for a content-less row',
                ),
            );
        }
        return $value;
    }

    Same syntax, only difference is you put it inside the appropriate filter. I prefer to use this code in the same file that I have exported the field in question.

  • Mark, I’d be surprised to learn that Duplicate Post (https://co.wordpress.org/plugins/duplicate-post/) doesn’t copy the ACF field content, because it is meta data and I’d expect it to support any meta data attached? In my plugin QuizMaster (which uses ACF5 Pro for all fields) we wanted to provide a copy feature for quizzes and questions, which are both custom post types. I just looked over the class we adapted from a tutorial on copying posts, and although it never specifically handles ACF, it loops over all metadata and creates a perfect copy. Newly copied posts have all the same field settings as the original. Here is a gist of that class which is a helper in QuizMaster: https://gist.github.com/goldhat/dbe670097922d3cfd6dac2630f1d19a8

    I’d imagine ACF developers might take the view this is beyond the scope of ACF, because it’s more about posts/copying than it is about fields/data. I’d tend to agree with that, because I think if you’re building a plugin with CPT’s (or a site that uses CPT’s) you can make a class that handles copying, that gist is the full extent of our copy feature and it’s only 129-lines. If ACF provided that feature, it would have to include various options, because for instance we only want to apply the copy option to our own CPT’s, not to all the post types.

  • No, there shouldn’t be any difference between front end and back. If I create a text field that is require field and I edit the post/page that the field is shown on front end or admin, I get the same result, a validation error without the page loading or showing the error page that you report.

    I did find one other thing that could be causing this, that is any output created by anything other than the proper JSON response to the AJAX query. In other words, something else somewhere is generating output. This problem can be almost impossible to track down. The best way to start is to deactivate all plugins except ACF and change to and unmodified version of one of the 20XX themes and then start adding things until you get the same issue and go from there.

  • Yesterday I ended up passing var in acf.add_filter as a.exclude and retrieving it in acf/fields/post_object/query/ with $_REQUEST[‘exclude’].
    Thank you.

  • I am an idiot… I found your tutorial:
    https://www.advancedcustomfields.com/resources/querying-relationship-fields/

    Solved, sorry for this.
    Please delete this post.

    Thanks,
    Kubajjz

  • I did experiment:

    – fresh install, latest versions of components – WP 4.7.5, Woocommerce 3.0.7 and ACF 5.5.14;
    – extremely minimal theme, with empty index.php, empty style.css, and function.php file with content for creating custom product type:

    // initial actions
    function custom_init() {
    
    	// add custom product type term
    	add_custom_product_type_term();
    
    	// custom product type class
    	class WC_Product_Test extends WC_Product {
    		public function __construct($product) {
    			$this->product_type = 'test';
    			parent::__construct($product);
    		}
    	}
    }
    add_action('init', 'custom_init');
    
    // add custom product type to product type selector
    function custom_product_type_selector ($types) {
    
    	$types['test'] = 'Test';
    	return $types;
    }
    add_filter('product_type_selector', 'custom_product_type_selector');
    
    // add custom product type term
    function add_custom_product_type_term() {
    
    	$product_types_existing = get_terms(array(
    		 'taxonomy'   => 'product_type'
    		,'hide_empty' => false
    	));
    
    	$exists = false;
    
    	foreach ($product_types_existing as $pte)
    		if ($pte->slug == 'test')
    			$exists = true;
    
    	if (!$exists)
    		wp_insert_term('test', 'product_type');
    }

    – two product categories (‘Category 1’ and ‘Category 2’) and two tags (‘Tag 1’ and ‘Tag 2’);
    – field group created, for post type ‘product’ with product_type ‘test’;
    – field group created, for post type ‘product’ with tag ‘Tag 1’;

    I run same actions:

    1. Creating / editing product: on product type ‘Test’ select / deselect, corresponding acf group doesn’t appears / disappears.
    No PHP errors logged. Console shows nothing.

    2. Creating / editing product: on adding / removing tag ‘Tag1’, corresponding acf group doesn’t appears / disappears.
    No PHP errors logged. Console shows nothing.

    3. Editing product with type ‘test’, acf group is visible. Selecting / deselecting product categories causes acf group disappearing.

    Initial state – both categories are selected.

    After one category deselected, ajax fires with form data:

    post_id:668
    post_taxonomy[]:
    post_taxonomy[]:15
    action:acf/post/get_field_groups
    exists[]:group_593352f539930
    exists[]:group_58a595ba1534b
    nonce:55b5acd041

    Response:
    {"success":true,"data":[]}

    After one category selected, ajax fires with form data:

    post_id:668
    post_taxonomy[]:
    post_taxonomy[]:15
    post_taxonomy[]:16
    action:acf/post/get_field_groups
    nonce:55b5acd041

    Response:
    {"success":true,"data":[]}

    After other category deselected, ajax fires with form data:

    post_id:668
    post_taxonomy[]:
    post_taxonomy[]:16
    action:acf/post/get_field_groups
    nonce:55b5acd041

    Response:
    {"success":true,"data":[]}

    Disappearing of acf groups, when adding / removing product image, or adding / removing tag – such behavior is not observed yet.

    So for the moment the biggest issue still exists, and it seems, that ajax call with action ‘acf/post/get_field_groups’ causes the problem. Am I right?

  • The default $args that ACF sets and passes to your filter does not include this argument and ACF does not check for extra argument passed in the AJAX request. In your filter you need to check $_POST[‘post__not_in’], I think.

  • All of these cases, where the ACF field groups do not show or for some reason the field groups do not change as expected probably have the same root cause.

    When the page loads ACF determines what fields to display, this is the case when you need to save a page to make the field groups appear as expected.

    After a page is loaded, immediately on some pages and also when something that should trigger ACF to update the field groups, ACF does an AJAX request to check on what field groups should be shown. If anything goes wrong with this request then what happens is nothing. This is what I suspect is causing all of your issues.

    First, check for JavaScript errors in console. If there are any, try to clear them up. Second, turn on debugging and logging https://codex.wordpress.org/WP_DEBUG and check your log to see if there are any PHP errors that could be causing the AJAX request to fail.

    You can also try deactivating other plugins and/or switching themes to help narrow down what could be causing the issues.

  • I was thinking like this:
    image

    having looked at the documentation here: https://www.advancedcustomfields.com/resources/textarea/

    I think the thing I’m getting confused by is the difference between textarea and wysiwyg.

    Here’s the problem:

    I have a get_field php call inside of a p tag like this

    <p class="class-name"> get_field(etc etc); </p>

    And it outputs like this

    <p class=class-name> </>
    
    <p> 
     <ul>the content that I put into my field </ul>
       <li>content</li>
       <li>content</li>
       <li>content</li>
       <li>content</li>
     </p>
    
    <p> </p>

    Which is super ugly and no good.

  • great – the second part is what I was asking.

    I’ll go from here – thanks for the quick answer!

  • I will keep that error_log in mind for future projects. I got it to work by including $post_id in get_field() function.

    Here is the working code:

    function my_post_object_query( $args, $field, $post_id ) {
    
    $cat = get_the_category($post_id);
    $sport = $cat[0]->slug;
    
    /*
    echo '<pre>';
    	print_r($x['class']);
    echo '</pre>';
    */
    
    $round = get_field('round',$post_id);
    $division = get_field('class',$post_id);
    
    if($round == 'prelim'):
    	$next_round = 'quarterfinal';
    
    elseif($round == 'quarterfinal'):
    	$next_round = 'semifinal';
    
    elseif($round == 'semifinal'):
    	$next_round = 'regional final';
    
    elseif($round == 'regional final'):
    	$division = array('A','B','C','D');
    	$next_round = 'state_championship';
    
    else:
    	$division = array($division,'A','B','C','D');
    	$next_round = array('quarterfinal','semifinal','regional final','state championship');
    endif;	
    	
    
    $args = array(
       // 'meta_key' => 'game_date_2',// priority
       'orderby' => 'ID',
       'order' => 'ASC',
       'post_status' => 'publish',
       'post_type' => 'game',
       'posts_per_page' => 10,
       'category_name' => $sport,
       'meta_query' => array('relation' => 'AND',
    
            array(
                'key' => 'playoff_game',
                'value' => 1
                ),
    
             array('relation' => 'OR',
           array(
                'key' => 'class',
                'value' => $division,
                ),
    ),
            array('relation' => 'OR',
            		array(
                'key' => 'round',
                'value' => $next_round,//array('quarterfinal','semifinal','regional final','state hampionship'),
                ),
         	  ),
    
            ),
    
        );
    
        return $args;
     
    }
    
    // filter for every field
    // add_filter('acf/fields/post_object/query', 'my_post_object_query', 10, 3);
    
    // filter for a specific field based on it's name
    //add_filter('acf/fields/post_object/query/name=my_post_object', 'my_post_object_query', 10, 3);
    
    // filter for a specific field based on it's key
    add_filter('acf/fields/post_object/query/key=field_593060bd83376', 'my_post_object_query', 10, 3);
    
    

    This for your help with this!

  • I don’t know if this will work or not

    
    $meta_query = array(
      array(
        'year_clause' => array(
          'key' => 'year',
          'compare' => 'EXISTS',
          'type' => 'NUMERIC'
        )
      ),
      array(
        'month_clause' => array(
          'key' => 'month',
          'compare' => 'EXISTS',
          'type' => 'NUMERIC'
        )
      )
    );
    
  • Thank you SO much, John – you have been a great help and this seems to be working really well. How then do I apply meta_value_num (so that month ’10’ is greater than month ‘2’ etc?) Adding ‘meta_value_num’ to the orderby array doesn’t seem to work. Here’s what I have now:

    function exhibition_pre_get_posts( $query ) {
    
    	if( is_admin() ) {
    		return $query;
    	}
    	
    	if( isset($query->query_vars['post_type']) && $query->query_vars['post_type'] == 'exhibition' ) {
    
    $meta_query = array(
      array(
        'year_clause' => array(
          'key' => 'year',
          'compare' => 'EXISTS'
        )
      ),
      array(
        'month_clause' => array(
          'key' => 'month',
          'compare' => 'EXISTS'
        )
      )
    );
    $query->set('meta_query', $meta_query);
    $query->set('orderby', array('year_clause' => 'DESC', 'month_clause' => 'DESC'));
    
    	}
    
    	// return
    	return $query;
    }
    
    add_action('pre_get_posts', 'exhibition_pre_get_posts');
  • You need to set the meta_query just like you set the other query parameters in your filter.

    
    $meta_query = array(
      array(
        'year_clause' => array(
          'key' => 'year',
          'compare' => 'EXISTS'
        )
      ),
      array(
        'month_clause' => array(
          'key' => 'month',
          'compare' => 'EXISTS'
        )
      )
    );
    $query->set('meta_query', $meta_query);
    $query->set('orderby', array('year_clause' => 'DESC', 'month_clause' => 'DESC'));
    
    
  • Thank you for your reply, John. I did find this post, but couldn’t figure out how to use this in pre_get_posts.

    Here’s what I have tried, but of course it doesn’t work:

    function exhibition_pre_get_posts( $query ) {
    	
    	// do not modify queries in the admin
    	if( is_admin() ) {
    		return $query;
    	}
    	
    	if( isset($query->query_vars['post_type']) && $query->query_vars['post_type'] == 'exhibition' ) {
    		$query = new WP_Query( array(
        'meta_query' => array(
            'relation' => 'AND',
            'year' => array(
                'key' => 'year',
            ),
            'month' => array(
                'key' => 'month',
                'compare' => 'EXISTS',
            ), 
        ),
        'orderby' => array(
            'year' => 'DESC',
            'month' => 'DESC',
        ) 
    ) );
    	}
    
    	// return
    	return $query;
    }
    
    add_action('pre_get_posts', 'exhibition_pre_get_posts');

    I’m sure this is a rookie mistake and a misunderstanding of the fundamentals – I’m still very much a beginner, I’m afraid!

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