Support

Account

Home Forums Search Search Results for 'taxonomy'

Search Results for 'taxonomy'

reply

  • I think you just shot over my ability to help you here, but I will give it a go.

    I suspect that it is something to do with getting values from the root site and switching sites…… but I’m not sure

    Another guess is that it may have something to do with the taxonomy/term not existing on the sub site. When ACF attempts to get the term/value for the current post it’s not finding any and the result is that the value is cleared in the admin, but I cannot be sure. I really suspect that this is the case, ACF does not know what to set the value to when the page is loaded. If this is the case, I’m not sure there is a way to fix it. You might be able to use the acf/load_value hook to attempt to…

    You’ll have to excuse the rambling of this post, I’m doing some digging through the code figure it out as I go.

    When ACF loads the value of the field it does

    
    $value = acf_get_valid_terms($value, $field['taxonomy']);
    

    This reads through all the terms that have been set to see if it’s a valid term, if not they are removed. So this where you’re problem is.

    Going back to what I said, you may be able to correct this by adding an acf/load_value filter https://www.advancedcustomfields.com/resources/acf-load_value/. Set the priority > 10 so it runs after ACf and then reset the correct values. In your filter you will likely need to use get_post_meta() to get the current value of the field because you will need to completely bypass ACF in order to avoid ACF’s check for valid terms.

  • Here’s some more info I’ve found. So to my knowledge the php hook that occurs right before field render is acf/prepare_field. Dumping the field shows that the value is present. Now the big question is, why isn’t it making it into the select2 jQuery object, and what handles the creation of that piece?

    array (size=31)
      'ID' => int 0
      'key' => string 'field_59e61ff30ff19_field_5c2d0d1860d0f' (length=39)
      'label' => string 'Select People Type' (length=18)
      'name' => string 'acf[field_5953fae740968][0][field_59e61ff30ff19_field_5c2d0d1860d0f]' (length=68)
      'prefix' => string 'acf[field_5953fae740968][0]' (length=27)
      'type' => string 'taxonomy' (length=8)
      'value' => int 123
      'menu_order' => int 5
      'instructions' => string '' (length=0)
      'required' => int 0
      'id' => string '' (length=0)
      'class' => string '' (length=0)
      'conditional_logic' => 
        array (size=1)
          0 => 
            array (size=1)
              0 => 
                array (size=3)
                  ...
      'parent' => string 'field_5953fae740968' (length=19)
      'wrapper' => 
        array (size=3)
          'width' => string '' (length=0)
          'class' => string '' (length=0)
          'id' => string '' (length=0)
      '_name' => string 'peopletype_taxonomy_list' (length=24)
      '_prepare' => int 1
      '_valid' => int 1
      'taxonomy' => string 'furman-person-type' (length=18)
      'field_type' => string 'select' (length=6)
      'allow_null' => int 0
      'add_term' => int 1
      'save_terms' => int 0
      'load_terms' => int 0
      'return_format' => string 'id' (length=2)
      'multiple' => int 0
      '_clone' => string 'field_59e61ff30ff19' (length=19)
      'parent_layout' => string '59e61fe0a4879' (length=13)
      '__key' => string 'field_5c2d0d1860d0f' (length=19)
      '__name' => string 'peopletype_taxonomy_list' (length=24)
      '__label' => string 'Select People Type' (length=18)
  • Thanks John,

    I’m defining the fields in the php, which I will include below. The taxonomy list is generated from a taxonomy defined on the root site. On subsites, I use the query and results hooks to switch to the root site for the query then back to the originating site after the query. I can also include the php and js hooks I’m using. The fields in question are ‘peopletype_taxonomy_list` which filters ‘people_by_type’.

    		acf_add_local_field_group(array(
    			'key' => 'group_59d53ce54567f',
    			'title' => 'People Group',
    			'fields' => array(
    				array(
    					'key' => 'field_59dd3068b24e6',
    					'label' => 'Copy',
    					'name' => 'copy',
    					'type' => 'wysiwyg',
    					'instructions' => '',
    					'required' => 0,
    					'conditional_logic' => 0,
    					'wrapper' => array(
    						'width' => '',
    						'class' => '',
    						'id' => '',
    					),
    					'default_value' => '',
    					'tabs' => 'all',
    					'toolbar' => 'full',
    					'media_upload' => 1,
    					'delay' => 0,
    				),
    				array(
    					'key' => 'field_5c27f7a668daf',
    					'label' => 'Add By Individual',
    					'name' => 'add_by_individual',
    					'type' => 'true_false',
    					'instructions' => '',
    					'required' => 0,
    					'conditional_logic' => 0,
    					'wrapper' => array(
    						'width' => '',
    						'class' => '',
    						'id' => '',
    					),
    					'message' => '',
    					'default_value' => 0,
    					'ui' => 1,
    					'ui_on_text' => '',
    					'ui_off_text' => '',
    				),
    				array(
    					'key' => 'field_5c27f7d868db0',
    					'label' => 'Add By People Type',
    					'name' => 'add_by_people_type',
    					'type' => 'true_false',
    					'instructions' => '',
    					'required' => 0,
    					'conditional_logic' => 0,
    					'wrapper' => array(
    						'width' => '',
    						'class' => '',
    						'id' => '',
    					),
    					'message' => '',
    					'default_value' => 0,
    					'ui' => 1,
    					'ui_on_text' => '',
    					'ui_off_text' => '',
    				),
    				array(
    					'key' => 'field_5c27f7eb68db1',
    					'label' => 'Add By Site',
    					'name' => 'add_by_site',
    					'type' => 'true_false',
    					'instructions' => '',
    					'required' => 0,
    					'conditional_logic' => 0,
    					'wrapper' => array(
    						'width' => '',
    						'class' => '',
    						'id' => '',
    					),
    					'message' => '',
    					'default_value' => 0,
    					'ui' => 1,
    					'ui_on_text' => '',
    					'ui_off_text' => '',
    				),
    				array(
    					'key' => 'field_59d53cee6770e',
    					'label' => 'People as Individuals',
    					'name' => 'people_as_individuals',
    					'type' => 'repeater',
    					'instructions' => '',
    					'required' => 0,
    					'conditional_logic' => array(
    						array(
    							array(
    								'field' => 'field_5c27f7a668daf',
    								'operator' => '==',
    								'value' => '1',
    							),
    						),
    					),
    					'wrapper' => array(
    						'width' => '',
    						'class' => '',
    						'id' => '',
    					),
    					'collapsed' => '',
    					'min' => 0,
    					'max' => 0,
    					'layout' => 'table',
    					'button_label' => '',
    					'sub_fields' => array(
    						array(
    							'key' => 'field_59d53d266770f',
    							'label' => 'Person',
    							'name' => 'person',
    							'type' => 'post_object',
    							'instructions' => '',
    							'required' => 0,
    							'conditional_logic' => 0,
    							'wrapper' => array(
    								'width' => '',
    								'class' => '',
    								'id' => '',
    							),
    							'post_type' => array(
    								0 => 'furman-person',
    							),
    							'taxonomy' => '',
    							'allow_null' => 0,
    							'multiple' => 0,
    							'return_format' => 'object',
    							'ui' => 1,
    						),
    					),
    				),
    				array(
    					'key' => 'field_5c2d0d1860d0f',
    					'label' => 'Select People Type',
    					'name' => 'peopletype_taxonomy_list',
    					'type' => 'taxonomy',
    					'instructions' => '',
    					'required' => 0,
    					'conditional_logic' => array(
    						array(
    							array(
    								'field' => 'field_5c27f7d868db0',
    								'operator' => '==',
    								'value' => '1',
    							),
    						),
    					),
    					'wrapper' => array(
    						'width' => '',
    						'class' => '',
    						'id' => '',
    					),
    					'taxonomy' => 'furman-person-type',
    					'field_type' => 'select',
    					'allow_null' => 0,
    					'add_term' => 1,
    					'save_terms' => 0,
    					'load_terms' => 0,
    					'return_format' => 'id',
    					'multiple' => 0,
    				),
    				array(
    					'key' => 'field_5c27fa0480c21',
    					'label' => 'People by Type',
    					'name' => 'people_by_type',
    					'type' => 'repeater',
    					'instructions' => '',
    					'required' => 0,
    					'conditional_logic' => array(
    						array(
    							array(
    								'field' => 'field_5c27f7d868db0',
    								'operator' => '==',
    								'value' => '1',
    							),
    							array(
    								'field' => 'field_5c2d0d1860d0f',
    								'operator' => '!=empty',
    							),
    						),
    					),
    					'wrapper' => array(
    						'width' => '',
    						'class' => '',
    						'id' => '',
    					),
    					'collapsed' => '',
    					'min' => 0,
    					'max' => 0,
    					'layout' => 'table',
    					'button_label' => '',
    					'sub_fields' => array(
    						array(
    							'key' => 'field_5c27fa0480c22',
    							'label' => 'Person',
    							'name' => 'person',
    							'type' => 'post_object',
    							'instructions' => '',
    							'required' => 0,
    							'conditional_logic' => 0,
    							'wrapper' => array(
    								'width' => '',
    								'class' => '',
    								'id' => '',
    							),
    							'post_type' => '',
    							'taxonomy' => '',
    							'allow_null' => 0,
    							'multiple' => 0,
    							'return_format' => 'object',
    							'ui' => 1,
    						),
    					),
    				),
    				array(
    					'key' => 'field_5c2d0d734763e',
    					'label' => 'Select Site',
    					'name' => 'site_taxonomy_list',
    					'type' => 'taxonomy',
    					'instructions' => '',
    					'required' => 0,
    					'conditional_logic' => array(
    						array(
    							array(
    								'field' => 'field_5c27f7eb68db1',
    								'operator' => '==',
    								'value' => '1',
    							),
    						),
    					),
    					'wrapper' => array(
    						'width' => '',
    						'class' => '',
    						'id' => '',
    					),
    					'taxonomy' => 'furman-site',
    					'field_type' => 'select',
    					'allow_null' => 0,
    					'add_term' => 1,
    					'save_terms' => 0,
    					'load_terms' => 0,
    					'return_format' => 'id',
    					'multiple' => 0,
    				),
    				array(
    					'key' => 'field_5c28136b1102f',
    					'label' => 'People by Site',
    					'name' => 'people_by_site',
    					'type' => 'repeater',
    					'instructions' => '',
    					'required' => 0,
    					'conditional_logic' => array(
    						array(
    							array(
    								'field' => 'field_5c27f7eb68db1',
    								'operator' => '==',
    								'value' => '1',
    							),
    							array(
    								'field' => 'field_5c2d0d734763e',
    								'operator' => '!=empty',
    							),
    						),
    					),
    					'wrapper' => array(
    						'width' => '',
    						'class' => '',
    						'id' => '',
    					),
    					'collapsed' => '',
    					'min' => 0,
    					'max' => 0,
    					'layout' => 'table',
    					'button_label' => '',
    					'sub_fields' => array(
    						array(
    							'key' => 'field_5c28136b11030',
    							'label' => 'Person',
    							'name' => 'person',
    							'type' => 'post_object',
    							'instructions' => '',
    							'required' => 0,
    							'conditional_logic' => 0,
    							'wrapper' => array(
    								'width' => '',
    								'class' => '',
    								'id' => '',
    							),
    							'post_type' => '',
    							'taxonomy' => '',
    							'allow_null' => 0,
    							'multiple' => 0,
    							'return_format' => 'object',
    							'ui' => 1,
    						),
    					),
    				),
    			),
    			'location' => array(
    				array(
    					array(
    						'param' => 'post_type',
    						'operator' => '==',
    						'value' => 'post',
    					),
    				),
    			),
    			'menu_order' => 0,
    			'position' => 'normal',
    			'style' => 'default',
    			'label_placement' => 'top',
    			'instruction_placement' => 'label',
    			'hide_on_screen' => '',
    			'active' => 1,
    			'description' => '',
    		));

    Here are the hooks being used.

    /*
     * Action hooks to modify query arguments within the People Group module
     */
    
    /*
     * Sets query args for Individual People Field
     */
    function individualPeopleQuery( $args, $field, $post_id ) {
    	$args['post_type'] = \Furman\PostTypes\People::POST_TYPE;
    
    	return $args;
    
    }
    
    add_filter('acf/fields/post_object/query/key=field_59d53d266770f', 'individualPeopleQuery', 10, 3);
    
    /*
     * Ensures that the title is correct when querying from child sites
     */
    function individualPeopleResult( $title, $post ) {
    	if ( strpos( $title, 'no title' ) ) {
    		$title = $post->post_title;
    	}
    
    	return $title;
    }
    
    add_filter('acf/fields/post_object/result/key=field_59d53d266770f', 'individualPeopleResult', 10, 3);
    
    function peopleTypeTaxonomyQuery( $args, $field, $post_id ) {
    	if ( ! Site::isRoot() ) {
    		$currentSite = get_current_blog_id();
    		switch_to_blog( Site::getRootBlogId() );
    		set_transient( 'peopleTypeTaxonomyQuery', $currentSite );
    	}
    
    	return $args;
    }
    
    add_filter('acf/fields/taxonomy/query/key=field_5c2d0d1860d0f', 'peopleTypeTaxonomyQuery', 10, 3);
    
    function peopleTypeTaxonomyResult( $title ) {
    	$originatingSite = get_transient( 'peopleTypeTaxonomyQuery' );
    	if ( Site::isRoot() && $originatingSite ) {
    		delete_transient( 'peopleTypeTaxonomyQuery' );
    		switch_to_blog( $originatingSite );
    	}
    
    	return $title;
    }
    
    add_filter('acf/fields/taxonomy/result/key=field_5c2d0d1860d0f', 'peopleTypeTaxonomyResult', 10, 3);
    
    //add_filter('acf/load_field/key=field_5c2d0d1860d0f', 'peopleType');
    
    /*
     * Set up custom query args received from AJAX requests.
     */
    function peopleByTypeQuery( $args, $field, $post_id ) {
    
    	if ( ! Site::isRoot() ) {
    		$currentSite = get_current_blog_id();
    		switch_to_blog( Site::getRootBlogId() );
    		set_transient( 'peopleByTypeQuery', $currentSite );
    	}
    
    	$args['post_type'] = \Furman\PostTypes\People::POST_TYPE;
    
    	if ( isset( $_POST['query-args'] ) ) {
    		$termId = $_POST['query-args']['term_id'];
    		$args['tax_query'] = array(
    			array(
    				'taxonomy' => \Furman\Taxonomies\PeopleTypes::TAXONOMY,
    				'field' => 'term_id',
    				'terms' => $termId
    			)
    		);
    	}
    
    	return $args;
    
    }
    
    add_filter('acf/fields/post_object/query/key=field_5c27fa0480c22', 'peopleByTypeQuery', 10, 3);
    
    function peopleByTypeResult($title) {
    	$originatingSite = get_transient( 'peopleByTypeQuery' );
    	if ( Site::isRoot() && $originatingSite ) {
    		delete_transient( 'peopleByTypeQuery' );
    		switch_to_blog( $originatingSite );
    	}
    
    	return $title;
    }
    
    add_filter('acf/fields/post_object/result/key=field_5c27fa0480c22', 'peopleByTypeResult', 10, 3);
    
    function peopleSiteTaxonomyQuery( $args, $field, $post_id ) {
    	if ( ! Site::isRoot() ) {
    		$currentSite = get_current_blog_id();
    		switch_to_blog( Site::getRootBlogId() );
    		set_transient( 'peopleSiteTaxonomyQuery', $currentSite );
    	}
    
    	return $args;
    }
    
    add_filter('acf/fields/taxonomy/query/key=field_5c2d0d734763e', 'peopleSiteTaxonomyQuery', 10, 3);
    
    function peopleSiteTaxonomyResult( $title ) {
    	$originatingSite = get_transient( 'peopleSiteTaxonomyQuery' );
    	if ( Site::isRoot() && $originatingSite ) {
    		delete_transient( 'peopleSiteTaxonomyQuery' );
    		switch_to_blog( $originatingSite );
    	}
    
    	return $title;
    }
    
    add_filter('acf/fields/taxonomy/result/key=field_5c2d0d734763e', 'peopleSiteTaxonomyResult', 10, 3);
    
    function peopleBySiteQuery( $args, $field, $post_id ) {
    
    	if ( ! Site::isRoot() ) {
    		$currentSite = get_current_blog_id();
    		switch_to_blog( Site::getRootBlogId() );
    		set_transient( 'peopleBySiteQuery', $currentSite );
    	}
    
    	$args['post_type'] = \Furman\PostTypes\People::POST_TYPE;
    
    	if ( isset( $_POST['query-args'] ) ) {
    		$termId = $_POST['query-args']['term_id'];
    		$args['tax_query'] = array(
    			array(
    				'taxonomy' => \Furman\Taxonomies\Sites::TAXONOMY,
    				'field' => 'term_id',
    				'terms' => $termId
    			)
    		);
    	}
    
    	return $args;
    
    }
    
    add_filter('acf/fields/post_object/query/key=field_5c28136b11030', 'peopleBySiteQuery', 10, 3);
    
    function peopleBySiteResult($title) {
    	$originatingSite = get_transient( 'peopleBySiteQuery' );
    	if ( Site::isRoot() && $originatingSite ) {
    		delete_transient( 'peopleBySiteQuery' );
    		switch_to_blog( $originatingSite );
    	}
    
    	return $title;
    }
    
    add_filter('acf/fields/post_object/result/key=field_5c27fa0480c22', 'peopleBySiteResult', 10, 3);

    Here are the JS API hooks in use

    document.addEventListener('DOMContentLoaded', () => {
    
        acf.add_action('select2_init', function( $select, args, settings, field ){
            console.log('SELECT2_SELECT:', $select);
            console.log('SELECT2_ARGS:', args);
            console.log('SELECT2_SETTINGS:', settings);
            console.log('SELECT2_FIELD:', field);
            // $select (jQuery) select element
            // args (object) args given to the select2 function
            // settings (object) settings given to the acf.select2 function
            // field (object) field instance
        });
        /*
        Uses the ACF JS API.  These filters allow the post object fields to be filtered based on a separate acf taxonomy field.
         */
        acf.add_filter('select2_ajax_data', function (data, args, $input, field, instance) {
            //People Type filter
            if (field[0].dataset.key === 'field_5c27fa0480c22') {
                let taxonomySelect = $('.acf-field-5c2d0d1860d0f').find('.select2-hidden-accessible').select2('data');
                data['query-args'] = {
                    'taxonomy': 'furman-person-type',
                    'term_id': taxonomySelect[0].id,
                    'term_title': taxonomySelect[0].text
                };
            }
            //Site filter
            if (field[0].dataset.key === 'field_5c28136b11030') {
                let taxonomySelect = $('.acf-field-5c2d0d734763e').find('.select2-hidden-accessible').select2('data');
                data['query-args'] = {
                    'taxonomy': 'furman-site',
                    'term_id': taxonomySelect[0].id,
                    'term_title': taxonomySelect[0].text
                };
            }
    
            // return
            return data;
    
        });
    
    });
  • You used a field group, but did you use a taxonomy field or eventually create a custom taxonomy

    Whilst I experimented with this, I chose ACF Checkbox for all such “company” sub-descriptions, as there are multiple of them. On the one hand, I feared over-use of taxonomies but, on the other, it would have certainly afforded me native taxonomy term page creation like this.

    So,

    Method 1) Page:
    Write a template file, apply it to a Page and pass the ACF Checkbox “tag” values to the Page, in a link from wherever I’m linking. I guess I’m going to need to learn how a Page can pick up those parameters and how to interpret them (Eg. https://dmjcomputerservices.com/blog/passing-url-parameters-to-a-wordpress-page/ ?)

    Method 2) Rewrite rules:
    So the page in this case is “company-type”?

    And then add custom rewrite rules to WP to transform the URL and add the correct query string

    So would this effectively be the same method as Method 1), ie. it needs to utilise URL query string parameters? And then it just uses rewrites to make the user-facing URLs prettier?

    Thanks.

  • You used a field group, but did you use a taxonomy field or eventually create a custom taxonomy? If this were the case the standard WP template hierarchy would manage this by creating a template for the taxonomy. I’m not sure if I covered that or not in the other discussion.

    If not then this is going to be difficult to do. There may be other methods, but this is what I would do if I needed to create a dynamic page based on only an ACF field.

    1) I would create a “Page” post. This will be used similar to the WP page_on_front or page_for_posts, page. It’s basically a place holder page.

    2) I would create a custom template file to be used on this page. This template file would dynamically generated.

    3) Links would need to include a query variable, for example ?company-type=some-company-type

    4) Use the query variable in 3 to dynamically generate the content for 2

    Alternately, instead of a query string variable in the url you could have the page named something like `https://www.yoursite.com/company-type/{$COMPANY_TYPE} and then add custom rewrite rules to WP to transform the URL and add the correct query string. I would probably do this, but the details of doing this are not something I know off the top of my head.

  • That’s all I can think of and the only thing I can remember that will cause an ACF field to be disconnected from a term when it is edited, or a post to become disconnected from a term. However, there is no end to the way filters and actions could be also effecting it, but this is probably where I’d start, first carefully looking at the term ID values and the term/taxonomy relationships. Maybe these categories are older that you think they are.

    What happens to the values selected for the business type and subcategory when you edit one of the types or subcategories associated with a post?

  • I realise I am necroposting, but I found this answer useful and wanted to post a small improvement.

    The first function remove_custom_taxonomy can be eliminated if meta_box_cb is set to false when making the initial register_taxonomy call.

    Or, if you don’t have control of the registration, you can filter the args later:

    
    function removeTaxonomyInEditor($args, $taxonomy)
    {
         if ($taxonomy === 'INSERTYOURTAXONOMYNAME') {
            $args['meta_box_cb'] = false;
        }
        return $args;
    }
    add_filter('register_taxonomy_args', removeTaxonomyInEditor, 10, 2);
    
  • No, you are correct. Regardless of the time of field, it the field does not exist, especially a field like a taxonomy field that contains more than simple text, you cannot get the value of the field after using update_field() with the field name. ACF cannot create the field key reference and this is why the field appears blank even when it has content. You need to use the field key to do the updates. It is possible to get the field keys, you are already using the field name, that you have to code in some way, you just need to substitute the field keys.

    Generally when I need to do this I create an array that holds field name => field key pairs

    
    $fields_refs = array(
      'name of field 1' => 'field_123456',
      'name of field 2' => 'field_234567',
      // etc...
    )
    

    Then I can do something like

    
    update_field($field_refs['name of field 1'], $value, post_id);
    
  • Theory: $field is blank for the same reason as the starting issue – that, until a field value is actually saved, the object does not actually have a field value obtainable by its name (?). And it will actually be impossible for me to programmatically obtain a field key using a field name, until that field is actually saved with some values? Am I right/wrong?

    Assuming that’s right, okay, I’ll bow to hard-code the field keys instead…

               // Convert Json
               $json_object = json_decode($json_result_string);
    
               // SAVE TO ACF GROUP:
    
               // Categories (source stdClass object):
    
               // sector
              $field_key = 'field_5c1bb19b00004';
              update_field($field_key, $json_object->category->sector, $org_id_prefixed);
    
              // industryGroup
              $field_key = 'field_5c1bb1f100005';
              update_field($field_key, $json_object->category->industryGroup, $org_id_prefixed);
    
              // industry
              $field_key = 'field_5c1bb36d55bf7';
              update_field($field_key, $json_object->category->industry, $org_id_prefixed);
    
              // subIndustry
              $field_key = 'field_5c1bb474dfb1a';
              update_field($field_key, $json_object->category->subIndustry, $org_id_prefixed);
    
              // sicCode
              $field_key = 'field_5c1bb495dfb1b';
              update_field($field_key, $json_object->category->sicCode, $org_id_prefixed);
    
              // naicsCode
              $field_key = 'field_5c1bb4bddfb1c';
              update_field($field_key, $json_object->category->naicsCode, $org_id_prefixed);
    
              // Tags (source Array):
              $field_key = 'field_5c0a9d251831a';
              update_field($field_key, $json_object->tags, $org_id_prefixed);

    For a test, I have wiped the pre-fixed “Choices” out of all fields in the field group editor, and re-saved the group. Also, I have run this code on a taxonomy term which has not previously had any of the values set. The outcome is this…

    That is, the values are saving to the fields, but still not in the way intended re: cementing Choices as per my original problem. Only the values for the “Tags” Checkbox field have been set as Choices, the rest have not…

    One thing that’s noticeable (this may be coincidence, or not) is that the source for “Tags” is an array from the Json (“tags”), whilst the source for the rest of the values is a “std Class Object”. See the red/green rectangles in each of the screengrabs…

    Any correlation in this discrepancy, or am I already doing things correctly?

  • I also just realized that you are using update_field($field_name, $value). If these fields to not already have values for these posts, in other words, you are adding the post and then immediately trying to update them where they have never had a value, then update field will not work using the field name and you must use the field key.

    For info, in my case, I am attempting to save field values for taxonomy terms, rather than posts. In current test phase, the term/s in question already exist.

    I think you’re saying – if the term already exists but if it has not yet had a value for the ACF field eg. “sector” already saved previously, I have to use update_field with the field key, not name…

    This gets me thinking, “rather than hard-code in the field key, can I programmatically obtain the field key from the field name?
    I see in the post Get field key by name, @almbay uses…

    $field = get_field_object('listing_type');
    $field_key = $field['key'];

    So maybe I could/should do…

    $field = get_field_object('sector');
    $field_key = $field['key'];
    update_field($field_key, $json_object->category->sector, $org_id_prefixed);

    But, I tried. And, in this situation, $field_key is assigned no value.

    I’ve checked the get_field_object docs. Maybe I should add $org_id_prefixed as a get_field_object parameter… ?

    $field = get_field_object('sector', $org_id_prefixed);
    $field_key = $field['key'];
    update_field($field_key, $json_object->category->sector, $org_id_prefixed);

    But, no, $field_key is still blank.
    In fact, before that, $field itself is also blank.

    So, why is $field = get_field_object('sector', $org_id_prefixed); failing to put anything in $field?

    FYI, $org_id_prefixed‘s value is like company_7456, corresponding to a taxonomy term ID formulation, and this value is present.

    (My previous topic attempt did not appear to save and the forum asked me to send a ticket instead).

  • I am building a products page with a selectable options sidebar. I have 2 custom post types for this ‘products’ for the main products and ‘options’ for the extra selectable options they can request for each product.

    The ‘options’ post type also uses the ‘option-categories’ taxonomy to categories the available options.

    Inside the New Post for ‘products’ I’ve added the ‘taxonomy’ (opt_tax) and ‘relationship’ (prod_options) field. The idea being that my client and select which options he wants to added to the sidebar.

    I wanted to do this with just the ‘relationship’ field but that doesn’t seem to be possible as it doesn’t seem to relate the posts to the taxonomies.

    What I can’t do at the moment is just get the ‘option-categories’ taxonomies to display according to the ones selected in the taxonomy field (opt_tax). At the moment this is my current code below. The ‘relationship’ part works as I’d like it to, I need to display the relevant taxonomies either with the relationship field or the taxonomy field.

    Thanks for any help on this.

     <?php
    
          $taxoIds = get_field('opt_tax');
    
          $tax = 'option-categories';
    
          $optArgs = array(
            'taxonomy'   => $tax,
          );
    
          $options_cat = get_terms($optArgs);
          foreach ($options_cat as $opt_parent) {
    
            $optID = $opt_parent->term_id;
    
             echo $opt_parent->name;
    
              $optIds = get_field('prod_options', false, false);
    
              $prodOpts = array(
                'post_type'    => 'options',
                'orderby'      => 'name',
                'order'        => 'DESC',
                'post__in'			=> $optIds,
                'tax_query'    => array(
                  array(
                    'taxonomy' => $tax,
                    'field'    => 'term_id',
                    'terms'    => $optID,
                  ),
                )
              );
    
              $wc_query = new WP_Query($prodOpts);
    
              if ($wc_query->have_posts()){ ?>
                <div class="card-body">
                  <ul>
                    <?php
                   
                    while ($wc_query->have_posts()){
                     
                      $wc_query->the_post();
    
                    ?>
                        <li>
                          <?php the_title(); ?>
                        </li>
    
                    <?php } ?>
                  </ul>
                </div>
              <?php wp_reset_postdata(); } } ?>
    
  • This screenshot is for a different entry, but illustrates how some values saved only with update_field have not solidified as Choices but others which have since been saved-over manually appear to have done so…

    NB. I am doing all this on a taxonomy term.

  • I’m not sure why I was trying to include a menu that way when I posted, but if I was doing it now I would:

    • Add a plugin that lets me assign a specific sidebar to a page or taxonomy term.
    • Put my menu in a widget in that sidebar.
  • ACF does not support taxonomies for media files because this is not supported natively by WP. Customization needs to be done in WP to do this, either through code or by using a plugin. I’ve looked into the ACF code and there isn’t any way to filter images for a gallery by taxonomy and there isn’t any way to add taxonomies to the array of images returned.

    (I suppose that you could add a load value filter https://www.advancedcustomfields.com/resources/acf-load_value/ or maybe a format value filter https://www.advancedcustomfields.com/resources/acf-format_value/ to the gallery field to add this information to the value before it is returned, but I’m not 100% sure on how to do this.)

    I’m not exactly sure where you want to do this filtering.

    If you want to do it in the admin you’d need to build a new type of gallery field that includes filters for your custom media taxonomy https://www.advancedcustomfields.com/resources/creating-a-new-field-type/. It may also be possible to add field settings to the existing gallery field https://www.advancedcustomfields.com/resources/adding-custom-settings-fields/ and then add filters to the gallery field to alter how it works to use these settings to filter images, but I’m not even sure this is possible. The gallery field works in conjunction with the standard WP media library popup and dealing with this can be complicated if it can be done at all.

    If you want to filter them on the front end…. if it were me I’d add a filter to the gallery load value hook, or more likely I would loop though all the images that ACF returns and only show the ones that should be shown based on additional queries.

    Sorry for the long answer that probably didn’t help you, but there isn’t a simple solution to this and any solution is going to involve a lot of coding to accomplish.

  • Sorry I did not get back to this sooner.

    But to try and answer the question….

    Even if I was going to add a field on a page to allow the client to select the testimonials that they want to show on that page I would still set up testimonials as a custom post type and create a custom taxonomy to allow categorization. I might even add multiple custom taxonomies depending on the clients needs. Why? Because this keeps things organized and allows for the most flexibility. If needed I can show all of the “posts” in an archive. I can show all of the posts in a specific category, etc. I could also build an interface that is use on pages with ACF to allow the client to select what testimonials to show, wither by category or allow them to select specific testimonials to display. If they wanted to show the most recent 5, I could give them a number field to determine how many to show. If they wanted to have “featured testimonials” shown on the home page, I could created a checkbox field on the testimonial to they could mark which ones they want featured and then I can display those. Using a custom post type and taxonomy removes any duplication of work, they just have to enter it once and there is freedom to do whatever is needed with the “Posts”.

  • Hi John, thanks for the reply!

    These fields would not be visible to the User. There’s only one Admin of the site and it would be up to them to fill out this Member taxonomy for each Post created. Basically, the only goal is to be able to sort Posts on the front-end by Members (similar to how Tags work).

    So far, I have the custom Taxonomy for Members added in the functions.php and it works great, I can add/edit those in the WP Dashboard (again, similar to Tags). I also added an ACF Taxonomy field to my Posts so that I can then choose any taxonomy Member that should be related to a Post.

    The final step here that I’m trying to solve is if a certain Member doesn’t exist yet, it would be ideal to be able to create that new Member from within the Post (rather than having to close the draft post, add the Member in the custom taxonomy area, then re-edit the post and select the member).

    The Create Terms setting does work perfect and I tried that but, like you pointed out, it only allowed me to create the new Member’s name. Is there any way possible that I can have the Create Terms setting also give me fields for slug and description?

  • A further suggestion of using existing tech, then: perhaps look into using either a custom taxonomy or a “Feature” CPT, then you can pull that in to each Provider/Product using a Relation field. That way, the editor can add whichever features they need, then apply them to the main CPT freely. This would work in the same way as categories and tags on regular posts.

  • It really depends on how you’re using this. Is this a front end form or an admin form? Is this something that the “Users” are entering on the front then? Is this something you’re doing in the admin?

    The easiest solution might be “Create Terms” setting for the taxonomy field, but this just let’s you create the term and set the name, it does not let you edit the description and will not let you edit anything else about the term.

  • @nano09 Take a look at the “Return Value” field in the Taxonomy field configuration. https://www.advancedcustomfields.com/resources/taxonomy/ It allows you to choose whether you want the Term ID or the Term Object in your code.

  • You can configure the return value of the field to give you the Taxonomy (category) object instead of the ID.

  • I’m struggling with this and the documentation doesn’t really make it clear…

    I have the following field types in a field group placed on a Taxonomy “company”…

    • Group: “Categories”, org_categories
    • Checkbox: “Sector”, org_cat_sector
    • Checkbox: “Industry Group”, org_cat_industrygroup
    • Checkbox: “Industry”, org_cat_industry

    How do I save values in to those checkboxes?

    $org_id_prefixed = 'company_'. $organisation->term_id; already gives the prefixed ID.

    Elsewhere, I’m successfully using the following to save to a Checkbox that is NOT in a Group…

    // Save "tags" (array) in ACF "org_tags" (checkbox)
    update_field('org_tags', $json_string->tags, $org_id_prefixed);

    What I want to save to org_cat_sector is $json_string->category->sector

    Most of the documentation around update_sub_field refers to Repeater. I’m unclear if I need to use have_rows stuff.

    The following…

    update_sub_field(
    array(‘org_categories’, 1, ‘org_cat_sector’), // Selector
    $json_string->category->industryGroup, // Value
    $org_id_prefixed // Object ID
    );

    … results in PHP throwing: ( ! ) Warning: Invalid argument supplied for foreach() in /home/myfolder/public_html/wp-content/plugins/advanced-custom-fields-pro/includes/fields/class-acf-field-checkbox.php on line 490

  • Just curious to add a couple of things/questions here…

    1. Does the code I have used above match the kind of suggestion you had given the circumstances?

    (To convey a company type, I have weighed up using either 1) a taxonomy, linked to the company term via an ACF field, or 2) just an ACF field itself. My code above uses a taxonomy).

    2. I’m now considering that the “company type” descriptor may actually need to be multiple

    In other words, I may have available multiple source pieces of data with which to describe my companies…

    1. “tags”
    2. “category: sector”
    3. “category: industryGroup”
    4. “category: industry”
    5. “category: subIndustry”
    6. “category: sicCode”
    7. “category: naicsCode”

    I am now considering that, if I choose to use them all, this is clearly too much to fit in to one “company type” as taxonomy.

    So I am now considering going back to baking the company descriptive field/s in to the company term itself as ACF fields, and not using a separate “company type” taxonomy…

    i)

    I had initially believed that doing it that way would make the looping slower.

    But, since I am already currently linking that taxonomy to a term using an ACF field anyway, maybe there is no impact to just pulling that data from term meta (ACF fields on “company”) when it’s open (?).

    ii)

    I will still want to output posts by company type in various ways. I’d value discussing this…

    It seems that using a taxonomy to describe “company type” gives the natural advantage of spinning up template pages (eg. taxonomy-orgtype-agency.php to output posts for all “agency” companies).

    If I move to storing all “company type” fields as ACF fields against “company” terms themselves, how would I go about grouping output of posts per company type?

    To simplify that question – say I have 200 ‘company” terms with a Checkbox “org_tag” value of “agency”. How do you output only those? …

    Because, unlike a taxonomy, I assume there is no relation between entities with the same value? Is there an ACF field that does have this relational database-ability? Leaving aside the Relationship, which seems to want a relationship with a Post.

  • Screenshot for register_taxonomy

  • As I would like to create a few taxonomies on a Custom Post Type I have done for Custom Theme. The Taxonomy location works and shows the custom taxonomy I created, but when it comes to the terms I added to it, I am unable to get the location option to work for term. Considering if I choose Taxonomy location and the custom taxonomy, it will show fields in main Taxonomy edit screen plus term editing screen.

  • Yes, I think that was a similar logic that I had been using…

        Add a field for the taxonomy term
        Get all companies
        For each, check the addtional ACF field
        If it matches the one we want to constrain, add its ID to an array
        When done, use that array to feed specific company term IDs to the WP_Query. In other words, narrow things

    I had concluded that this method may be slower than desirable. I have know decided that I’ll just have to lumnp it, it doesn’t take light years.

    However, the big switch I have made since first trying this method is this – whilse I initially added an ACF Select field as the additional, cosntraining field on the company term, now I am using an actual Taxonomy field. That is, I registered a new taxonomy, Organisation Type (orgtypetax), and have added that as an ACF field. For good measure, I ensured the taxonomy regisgtration code also attaches to the “company” object – though I suspect this is wishful thinking and actually may not be possible.

    For reference…

          // GET ALL ORGANISATIONS
    
           $organisations = get_terms(
             array(
                'taxonomy' => "company",
             )
          );
    
          // NARROW ONLY SPECIFIC ORG TYPE
    
          // Initialise array we will use to feed the WP_Query
          $orgs_filtered = array();
          // Slug of the orgtypetax taxonomy
          $target_type = "agency";
    
          // Check every organisation's orgtypetax for $targettype - if found, add to array
          foreach ($organisations as $organisation) {
    
             // Construct prefixed field ref for this organisation
             $org_id_prefixed = 'company_'. $organisation->term_id;
    
             // Get ID organisation's orgtypetax taxonomy term
             $orgtypetax_term_id = get_field( 'orgtypetax', $org_id_prefixed );
             // Now use ID to get the actual object
             $orgtypetax_term_obj = get_term( $orgtypetax_term_id );
    
             // If the found term matches the target term, add to our array
             if ( $orgtypetax_term_obj->slug == $target_type ) {
                   array_push($orgs_filtered, $organisation->term_id);
             }
    
          }
    
          // Query posts
          $paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;
          $args = array(
            // pagination
            'nopaging' => false,
            'posts_per_page' => 50,
            'paged' => $paged,
            // posts
            'post_type' => 'article',
            // order
            'orderby' => 'date',
            'order'   => 'DESC',
            // taxonomy
            'tax_query' => array(
              array(
                'taxonomy' => 'format',
                'field'    => 'slug',
                'terms'    => 'viewpoint'
              ),
              // Only organisations filtered above
              array(
                'taxonomy' => 'company',
                'field'    => 'id',
                'terms'    => $orgs_filtered
              ),
           ),
          );
          // the query
          $this_query = new WP_Query($args);
          if ( $this_query->have_posts() ) :
              set_query_var('my_query', $this_query   );
              set_query_var('name',     ucfirst($target_type).' Views' );
              set_query_var('count',    $this_query->found_posts);
              set_query_var('columns',  'col-md-6 col-lg-6 mb-4');
              // Template part
              get_template_part('partials/card', 'medialist');
              wp_reset_postdata(); ?>
           <?php else : ?>
             Nothing here.
           <?php endif;
    
           ?>
    
Viewing 25 results - 1,426 through 1,450 (of 3,194 total)