Support

Account

Home Forums Search Search Results for 'taxonomy'

Search Results for 'taxonomy'

reply

  • I just fixed it with acf/fields/taxonomy/wp_list_categories. I had to look up all the numerical value of the terms I want excluded, but it works

    function my_taxonomy_query( $args, $field) {
      
     $args['exclude'] = array(91,96,2,26,33,15,64,44,62,11,95,77,66,71,10,92,67);
    
        return $args;
        
    }
    
    add_filter('acf/fields/taxonomy/wp_list_categories', 'my_taxonomy_query', 10, 2);

    The acf/fields/taxonomy/query filter didn’t work for me at all for some reason, couldn’t even get the example code to work.

  • Actually, yes. You can use the acf/fields/taxonomy/query filter https://www.advancedcustomfields.com/resources/acf-fields-taxonomy-query/ and adjust the arguments for get_terms() https://developer.wordpress.org/reference/classes/wp_term_query/__construct/ using the “exclude” argument.

  • Hi, I seem to be having a bit of a problem. I used Beee’s code and altered it to fit my taxonomies, but unfortunately it’s not working as wanted.

    I have a custom post type with a taxonomy (‘type’), type can either be ‘movie’ or ‘series’.

    My ACF Radio button field has these choices, the value given is the value of the term:

    2 : Movie
    4 : Series

    This will output the value of the field, not the name or array.

    In my functions.php I have:

    function change_media_type( $post_id ) {
        // bail if no ACF data
        if ( empty($_POST['acf']) ) {
            return;
        }
        // get term id from $post_id (only 1 value is allowed, so it returns 1 value only)
        $stored_type = wp_get_post_terms($post_id, 'type');
        // get submitted value from acf form
        $posted_type = $_POST['acf']['field_picktype'];
        // get term_id for the submitted value
        $term_id = get_term_by( 'id', $posted_type, 'type' );
        // if stored value is not equal to posted value, then update terms
        if ( $stored_type != $posted_type ) {
            wp_set_object_terms( $post_id, $term_id->term_id, 'type' );
        }
    }
    add_action('acf/save_post', 'change_media_type', 20);

    But it doesn’t seem to change the taxonomy of the post as I want. It changes, but simply changes to “—”. Could anyone point me in the right direction?

  • Hi all,
    if you look at my try to achieve this:
    https://github.com/filippozanardo/redvolver-acfcleaner

    You see that ,expect some field that i didn’t found a way yet, can be made in 2 ways, one is as john say delete all the meta related to ACF on acf/save_post hook at high priority.
    The other a more difficcult way is to match the field in the database/json and then to delete the field that is not present anymore in the current saved data.
    I found a trick also to check if the field is a flexible field and delete the field.
    As far as i test works remember to backup db first.

    For now works on post and custom post type when i have time i want also to include a “Clean all ACF” tool that use this method, and i’m trying also to find a way to “clean” all the fields for taxonomy, user etc etc.

    Suggestions, ideas and pull requests are welcome.

  • When registering your custom taxonomy set meta_box_cb to false https://codex.wordpress.org/Function_Reference/register_taxonomy

  • I finally had to give up and use the Toolset Types plugin, which has some of the ACF function and inserts some of the custom field code into the wordpress itself. I can see two problems with this:

    1. It’s doing the dirty work for me. I still don’t know where it is putting the code or how it works.

    2. If I make a mistake or change my name about which field name to use, it could leave a trail of unused fields and code. I don’t know if that’s what it does, but I have no way of verifying either because I don’t know where it is inserting code into the theme.

    But after using it, I could use this snippit

     <?php if (get_the_term_list($post->ID, 'media-type', '', '<br />', '')): ?>
      <div>
      <h4><?php esc_html_e('Media:'); ?></h4>
      <div>
      <?php
      echo get_the_term_list($post->ID, 'media-type', '', ',&nbsp;', '');
    ?>
                                   </div>
                                </div>
    <?php endif; ?> 

    because now I have another custom category type built into my wordpress (right along side the existing “category” and “tag” options in wordpress).

    I also found out that the spaces (”) in places like this
    echo get_the_term_list($post->ID, 'media-type', '', ',&nbsp;', '');

    actually serve as a substitute for the

    if( count($values)){
        foreach($values as $k=>$value){
            if($k) echo ',  ';
           echo $value;
        }
    }

    part of the code and that it isn’t a good idea to use “if (count($values))” if the value is ever empty, but some of the problems associated with using anything with “empty()” was way over my head. Maybe someone can come along later and explain how someone could have an archive link (that part was solved by john) associated with the category name in a theme’s custom portfolio taxonomy.

  • Some further information after looking through stack traces: the warning is because WP, as part of restoring a revision, is calling normalize_whitespace() (which then calls trim()) on the values of ACF fields that are arrays, not strings.

    Two instances of ACF fields that triggered this:
    – A flex content’s base field
    – A list of categories selected from a taxonomy field

  • Oh, interesting approach regarding the closing out of php. I like it. Kind of like formal writing avoids contractions. Probably a good approach for me too since I’m just learning the intricacies of php but am fine with most html.

    Name instead of label… So that’s how taxonomy’s handle things differently then? I was using a snippit for handling custom fields. I tried using a snippit my own theme uses as well…
    <?php echo get_the_term_list( $post->ID, 'portfolio_skills', '', '<br />', '' ); ?>
    (this time closing the tags rather than mess with all the single quotes…especially since I’m not worried about spaces and line breaks right now)

    However, since ‘portfolio_skills’ (I used ‘media’ instead) is my theme’s own custom field and probably not a taxonomy per se (albeit the values are user generated), maybe $terms->ID would be better $terms->NAME or will I break the theme again?

    Maybe a better question is to ask what would be a good resource for learning and practicing php? I’m like the person learning a new language asking for a “tall refreshing glass of water”. I know that I’ll get a glass of water without understanding that “refreshing” is superfluous and “tall” is too specific for my needs.

    Thanks again for all your efforts. I know it’s a labor of love teaching without pay.

  • I’ve read all of your comments, but I may not understand what you’re looking for.

    I’m really not sure what you mean by “the linking option” in the pro version.

    You are using a taxonomy field and you want to output links to the terms that have been selected?

    If this is true then how you would code this depends on what you have the Return Value of the field set to. You would most likely be better off returning a term object.

    
    $terms = get_field('media');
    if ($terms) {
      foreach ($terms as $term) {
        ?>
          <a href="<?php echo get_term_link($term); ?>"><?php echo $term->name; ?></a>
        <?php 
      }  // end foreach
    } // end if
    
  • To clarify now that I understand more:

    I am using my theme’s existing custom taxonomy portfolio-category, but I don’t know how to perform a var_dump of that field (assuming it’s a field and not a subfield) outside of the loop. I want to eventually be able to use each category I assign via checkbox a link, and to use my portfolio’s existing archive view to view the posts under that category.

    In my theme:
    I have one category in my theme’s ‘portfolio-category’ named ‘media’ (slug is also media) and five children assigned under that category:
    Acrylic (slug: acrylic-media)
    Textured Acrylic (slug: textured-acrylic-media)
    Digital (slug: digital-media)
    Prismacolor (slug: prismacolor)

    In ACF
    Field label: Media
    field name (slug?): media
    field type: Taxonomy
    Taxonomy: portfolio_category
    Field Type: Checkbox
    Term is ID, not object.
    Null is currently not allowed

    Since I’m using a taxonomy, using anything like [‘label’] would be out of the question (right?), which is why any of the sub-field snippits I tried did not work, and that a value of 5 from the var_dump was because there is 1 field and 4 sub-fields in my theme’s taxonomy assigned the field ‘media’. So if this method is too complex, then I could resort to another option and attempt to create my own archive function in the (probably distant) future…

    If checkbox were chosen instead of taxonomy, I could assign each category a label and a variable in the choices fields in ACF

    So something like

    acrylic: https://www.mysite.com/acrylic
    prismacolor: https://www.mysite.com/prismacolor
    etc.

    would work if I wanted to set a value to an ‘href’. But…

    I would have to call each subfield by name to retrieve the values from that field, right? Or would there be any way to assign a x-variable type value so I can just add what I wanted to ACF as I add more subfields? A pain, but not quite as much writing code for every subfield in addition to adding to ACF and therefore having two areas to edit.

  • I got it working. As what I had above was showing the taxonomy term IDs I found how to turn these IDs into text terms that could be used within $the_query $terms array. I’m not sure if this is the best way to solve the problem so if you know any way to streamline this code, I’d greatly appreciate knowing how.

    global $post;
    $row1 = get_field('homepage_sidebar_sponsor_logos' );
    $first_row = $row1[0];
    $first_row_id = $first_row['contestant_year_category' ];
    $first_row_term = get_term_by('id', absint( $first_row_id ), 'year_type');
    $first_row_name = $first_row_term->name;
    
    $row2 = get_field('homepage_sidebar_sponsor_logos' );
    $second_row = $row2[1];
    $second_row_id = $second_row['contestant_year_category' ];
    $second_row_term = get_term_by('id', absint( $second_row_id ), 'year_type');
    $second_row_name = $second_row_term->name;
    
    $row3 = get_field('homepage_sidebar_sponsor_logos' );
    $third_row = $row3[2];
    $third_row_id = $third_row['contestant_year_category' ];
    $third_row_term = get_term_by('id', absint( $third_row_id ), 'year_type');
    $third_row_name = $third_row_term->name;
    
    $the_query = new WP_Query( array(
        'post_type' => 'contestants',
        'tax_query' => array(
        array(
          'taxonomy' => 'year_type',
          'field' => 'slug',
          'terms' => array( $first_row_name, $second_row_name, $third_row_name )
        )
      ))
    ) ;
  • I figured this out. In case anyone else wants to know…

    <div class="sponsors">
    <?php
    global $post;
    $the_query = new WP_Query( array(
        'post_type' => 'contestants',
        'tax_query' => array(
        array(
          'taxonomy' => 'year_type',
          'field' => 'slug',
          'terms' => array( 'term_1', 'term_2', 'term_3' )
        )
      ))
    ) ;
    
    if($the_query->have_posts()){
        while ( $the_query->have_posts() ) {
            $the_query->the_post();
    if( have_rows('sponsors', $post->ID) ):
        // loop through the rows of data
    
        while ( have_rows('sponsors') ) : the_row();
    
            // display a sub field value
            $image = get_sub_field('sponsor_logo');
            $url = get_sub_field('sponsor_url');
            $name = get_sub_field('sponsor_name');
    
            ?>
            <div class="sponsor"><a href="<?php echo $url; ?>" target="_blank" title="<?php echo $name; ?>"><img src="<?php echo $image; ?>" /></a></div>
        <?php endwhile;
    
    else :
        // no rows found
    endif;
    }
    }
    ?>
    </div>

    Please mark this thread closed. Thank you.

  • I had a similar requirement to yours and found this when searching for a solution.

    I have managed to get this working using the acf/fields/post_object/query filter.

    The way it brings in the information is a bit harder to debug as it’s all AJAX, but using WP_DEBUG_LOG and error_log to see what data was parsing through helped me come to the solution:

    function cxx_event_balance_individual_option( $args, $field, $post_id ) {
    	
    	// $post_id comes in here as term_# so we need to remove 'term_' to get the term ID
    	$prefix = 'term_';
    	
    	// Also if you are creating a new taxonomy, post_id = 'term_0' so then there's no point in adding a filter
    	if ( 'term_0' != $post_id && substr( $post_id, 0, strlen( $prefix )) == $prefix ) {
    		// Set $term_id to the ID part of $post_id
    		$term_id = substr( $post_id, strlen( $prefix ) );
    		
    		// And adjust the query to filter by specific taxonomy term
    		$args['tax_query'] = array(
    			array(
    				'taxonomy'  => 'product_event',
    				'field'     => 'term_id',
    				'terms'     => $term_id,
    			),
    		);
    	}
    	return $args;
    }

    Hope this helps you out.

  • The problem with image fields is that they store the Post ID of the image in the media library and the image does not exist in the other site and if the ID value does exist it is already used for another post. The first thing you need to do is to insert the image into the media library, get the new ID and then swap the ID from the site you’re copying from with the new ID for the site that you’re copying to.

    You’ll have the same problem with any field type that stores ID values for other WP objects including relationship fields, post object fields, taxonomy fields, etc.

    flex fields and repeaters will make a difference because you’ll need to know how ACF stores values in the DB in order to find the fields that need to be replaced with new ID values. Flex fields and repeaters are stored in a similar fashion.

    A repeater or flex field will have meta keys like
    "{$repeater_name}_{$index}_{$sub_field_name}"
    a nested repeater field will look like
    "{$repeater_name}_{$index}_{$sub_field_name}_{$index}_{$sub_field_name}"

  • I’ve created a Field Group called Brands, in that field group I’ve added a field with a field name of ‘select_brands’ of type Checkbox (to be able to select multiple). In the choices I’ve added this:

    
    bolou : Bolou
    c6 : C6
    deakin francis : Deakin Francis
    fope : FOPE
    piero milano : Piero Milano
    

    From this I generate a drop down on the front page, along a second drop down generated from categories (the built in widget in the admin interface).

    So, now I can pick – from two different drop downs – a combination of both Brand and Category. But, – I’ve now tried for three days to get the posts from the DB without any luck (yes, luck is actually what I’m counting on now, ’cause nothing seem to make sense).

    Now, from the 3.456.745 different versions of an $args array I’ve tried, none work. Now, I need some help understanding what parameters I actually need to put where, as I simply can’t grasp why this is so hard to get going.

    I would expect the following to get me; posts of custom post type ‘jewellery’ with a category of whatever is selected in the category drop down ($category is an integer from the option value in the drop down) that is also of a specific Brand ($brand is a string from the above options from the custom field).

    
    $args_jewellery = array(
    	'post_type' => 'jewellery',
    	'numberposts'	=> -1,
    	'tax_query' => array(
    		array(
    			'taxonomy' => 'category',
    			'terms' => array( $category )
    		)
    	),
    	'meta_query' => array(
    		array(
    			'key' => 'select_brands', <-- IS THIS RIGHT?
    			'value' => $brand <-- AND IS THIS?
    		)
    	)
    );
    

    How do the fields below relate to my custom post type and its value?

    'meta_query' => array(
    	array(
    		'key' => 'select_brands', <-- ?
    		'value' => $brand <-- ?
    	)
    )
    

    And WHY isn’t this working? What is it that I’m totally missing here … ?

  • I’m using trial and error with values I know exists:

    But no matter what I put it, I still get nothing:

    $args_jewellery = array(
    	'post_type' => 'jewellery',
    	'numberposts'	=> -1,
    	'tax_query' => array(
    		array(
    			'taxonomy' => 'category',
    			'terms' => array( 6 ) // Also tried category name as string 'Ringe', no difference
    		)
    	),
    	'meta_query' => array(
    		array(
    			'key' => 'select_brands',
    			'value' => 'bolou'
    		)
    	)
    );
    

    If I remove the meta_query part I get all rings. But why isn’t the meta_query part working – these are values I know exists. But I don’t know if that’s what I’m supposed to use!?

    ANY help is appreciated!

  • Thanks, John, but I have to adapt this to my code to fully understand it:

    I have a range of jewellery (using a Custom Post Type = jewellery) that I separate by Category (using the built in Categories of WP) and Brands (using a custom field to select the brand in the custom post type).

    From that I create two separate drop downs: Category with values of IDs of categories, and Brands with values of strings.

    So if the user select a Brand from one of the selects and a Category from the other select, the code you provide should look like this, right:

    'post_type' => 'jewellery',
    'tax_query' => array(
    		array(
    			'taxonomy' => 'category',
    			'terms' => array( $category ) // <-- THIS I GET FROM $_GET['c']
    		)
    	),
    	'meta_query' => array(
    	array(
    		'key' => 'select_brand', // <-- WHAT DO I PUT HERE (THE CUSTOM FIELD VALUE, this is what I named it.)
    		'value' => $brand // <-- THIS I GET FROM $_GET['b']
    	)
    )
    
  • I was going to answer last night but then I thought the way you worded it that it might be another taxonomy.

    Anyway, you just need to add both a tax query and a meta query

    
    $args = array(
      'post_type' => 'product', // or whatever
      'tax_query' => array(
        array(
          'taxonomy' => 'category',
          'terms' => array($term_id) // must be an array of term IDs
        )
      ),
      'meta_query' => array(
        array(
          'key' => 'brand',
          'value' => 'some brand'
        )
      )
    )
    

    https://codex.wordpress.org/Class_Reference/WP_Query

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

  • There isn’t a way that I know of to create infinite nesting of fields in ACF. Have you thought about using a hierarchical custom post type or custom taxonomy?

  • basically, if you want to get all of the posts in a term then you should use WP_Query https://codex.wordpress.org/Class_Reference/WP_Query and the documentation will lead you there https://developer.wordpress.org/reference/functions/query_posts/

    The important bit is the tax_query and the fact that your field is returning an term object. You could query by any of the fields of the returned object.

    If you want to see what the object looks like

    
    $department = get_field('department');
    echo '<pre>'; print_r($depearment'); echo '</pre>';
    

    Here is

    
    <?php 
      
      $department = get_field('department');
      
      $query = array(
        'post_type' => 'staff',
        'orderby' => 'menu_order',
        'order' => 'ASC',
        'posts_per_page' => -1,
        'tax_query' => array(
          array(
            'taxonomy' => 'departments',
            'field' => 'term_id', // not needed, default value
            'operator' => 'IN', // not needed, default value
            'terms' => array($department->term_id)
          )
        )
      );
      $team_query = WP_Query($args);
      if ($team_query->have_posts()) {
        while($team_query->have_posts()) {
          $team_query->the_post();
          // output stuff about this post
        }
        wp_reset_postdata();
      }
    

    more information about querying based on different types of acf fields can be fount here https://www.advancedcustomfields.com/resources/query-posts-custom-fields/

  • I have the taxonomy field setup to return as a Term Object

  • Is the taxonomy field returning the default Term ID or is it returning a Term Object?

  • Hi @blaasvaer

    Thanks for the follow up.

    That is quite tricky as you would need to implement some custom action to dynamically add items to the custom taxonomy by clicking on the add new link.

    I’m afraid that is currently not possible from the plugins API.

  • Indeed, it’s not possible with get_terms (get_categories) args, cause final query contains “INNER JOIN wp_termmeta” but acf doesn’t use this table

    So loop through it with usort()

    the shortest variant for now is

    
    usort($terms, function($a. $b) use ($taxonomy) {
       return get_field('sort_order', $taxonomy.'_'.$a->term_id) - get_field('sort_order', $taxonomy.'_'.$b->term_id);
    });
    
Viewing 25 results - 1,751 through 1,775 (of 3,193 total)