Support

Account

Home Forums Search Search Results for 'taxonomy'

Search Results for 'taxonomy'

reply

  • Ok I think I understand what you are trying to do, but correct my if I’m wrong.

    You want to retrieve TERMS from the taxonomy CATEGORY, but only those terms that have a specific value filled out in a custom field.

    There is an article in the ACF documentation describing how to do this if you were querying posts instead of taxonomy-terms: https://www.advancedcustomfields.com/resources/creating-wp-archive-custom-field-filter/

    However, I believe the same principle can be applied to pre_get_terms (instead of pre_get_posts).
    The filter pre_get_terms is called inside WP_Term_Query so it should work for api requests: https://developer.wordpress.org/reference/classes/wp_term_query/get_terms/

  • <div class="cat-extra-dis">
      <?php 
    		$queried_object = get_queried_object(); 
    		$taxonomy = $queried_object->taxonomy;
    		$term_id = $queried_object->term_id;  
    
            the_field('tekst_under_posts', $taxonomy . '_' . $term_id);
    	
    ?>
        </div>
        <!-- /.cat-extra-dis -->
  • Hello @jarvis,
    Thanks for your help.
    I use this code :

    function my_pre_get_products( $query ) {
    	// do not modify queries in the admin
    	if( is_admin() ) {
    		return $query;
    	}
    	// only modify queries for 'product' post type
    	if( isset($query->query_vars['post_type']) && $query->query_vars['post_type'] == 'product' ) {
    		// allow the url to alter the query
    		if( isset($_GET['id_article_mercator']) ) {
        		$query->set('meta_key', 'id_article_mercator');
    			$query->set('meta_value', $_GET['id_article_mercator']);
        	}
    	}
    	return $query;
    }
    add_action('pre_get_posts', 'my_pre_get_products');

    Now I have a response on this url : https://mywebsite/wp-json/wc/v3/products?id_article_mercator=42771

    Now I want to have the same result for a category of the products.
    This url returns all the categories.
    https://mywebsite/wp-json/wc/v3/products/categories/

    I want to be able to filter a custom field added by ACF
    https://mywebsite/wp-json/wc/v3/products/categories/?myfield=testvalue

    Do you have an idea what to add as function for this ?
    What’s strange also, for the products, I can see in the rest api result the metadata with the values added by ACF
    For the category, the metadata aren’t visible.
    In the database the values are stored in termmeta for the categories and in postmeta for the products.
    If I’m right, the product is a post and the category is a taxonomy.

    Thanks in advance,

  • Yes, not impossible, but extremely (EXTREMELY) difficult to have archive pages based on ACf field values. If you need archive pages it is always better to use a taxonomy.

  • If each author can only have 1 country then it really does not matter. If you should want to list all authors in a specify country either a taxonomy or a custom field (single select) will perform just as well.

    If on the other hand each author could be listed in multiple countries then you are better off using a taxonomy field (custom taxonomy). Taxonomy queries are easier and perform better than querying for posts based on a multi select field. The reason for this is that a multi select stores values as a serialized array. Looking for one value is not a problem, but looking for posts that might match more than one value becomes complicated and the query performance degrades as you add more values to look for. See section 3 on this page https://www.advancedcustomfields.com/resources/query-posts-custom-fields/

  • You must supply the post ID

    If it is the same post and the field is already saved

    
    $parent = get_field('field_5f326eac0b9d8', $post_id);
    

    Otherwise look at this topic https://support.advancedcustomfields.com/forums/topic/filter-post-object-based-on-selected-taxonomy/

  • There isn’t any way to do that with WP_Query directly. This would take a more complex query then WP_Query is capable of.

    To be honest, I’m not even sure I help with the query you’d need because wp_posts is contected to wp_terms thought both wp_term_relationships and wp_term_taxonomy.

    A very simplified form or the WHERE would be

    
    WHERE (post_type = 'post' AND 
           term_id = 304) // this is completely wrong
           OR (post_type IN(your other post types))
    
  • Did you manage to do that with Elementor? I am having the same issue. A custom taxonomy’s featured image (under WooCommerce product post type) (field created with ACF) can’t be displayed. Although category’s featured image can be displayed…

  • The page in question is a custom admin sub page that mimics a taxonomy admin page. I haven’t got a clue how this is added or if there is any way to change it. I did a search on the subject and found no information on changing this page. Changing this page would require WC having some type of action hook that runs when showing this page that would allow you to add ACF field groups to the form. It appears that the only source of information on if this can be done would be WC. If you can get information on if/how it is possible to alter this page then I could probably help you to add ACF fields to the page.

    Then the next problem would be where the information is actually stored and how to retrieve it because this page is simply an interface that allows you to add product attributes. From my understanding of this, each “attribute” that is added is a actually a new custom taxonomy and then then list for each of these has sub terms. So the interface is actually letting you create your own custom taxonomies associated with WC. So there really isn’t anywhere that this information is stored or to store any information associated with it. This would be like having information stored that is used on all “categories” or “tags” there is nowhere in WP to store information like this. So even if you could figure out how to alter this page I think that the effort would be wasted.

  • Did you ever solve this? I was looking for something similar and hope to have found a solution in:

    Adding Custom Post Type UI. Then add a new custom posttype like “Attribute extras”. After that you can add a new group in ACF and add an image and extra description for example. Also you add a Taxonomy field with the field name matching the slug of the Attribute. You do this for each Attribute (in my case about 30).

    Finally when you add a new “Attribute Extra” you use the Title to match the slug of the actual attribute. In front you then make some custom code to display the image instead of the attribute value.

    Still testing this as I want to import all (2000+) Attribute Extra’s. I’ll let you know if it works

  • Never mind, I have deleted the custom taxonomy template and am not using it anymore. Thanks

  • I noticed that the custom Taxonomy Template does not display any of the fields.

  • To display these posts, I am using the Custom TaxonomyTemplate.

  • You need to loop the taxonomies and in doing so, get the taxonomy ID

    Once you have that, you can access the custom fields you store against the taxonomy.

    Something like:

    <?php if( $contacts = get_terms( array( 'taxonomy' => 'contact' ) ) ) :
    foreach( $contacts as $contact ) : 
    	$email_du_contact  = get_field('email_du_contact', 'term_' .$contact->term_id  );?>
    	<?php echo $email_du_contact; ?>
    <?php endforeach;      
    endif;
    ?>

    Code untested

  • The checkboxes on the film page will only be shown if a film is assigned, so it prevents someone clicking filters and having no results.
    The code is in place as fallback OR in case you wish to adjust this behaviour.

    With regards to the similar/related films on the single film page, it depends on whether a film is assigned to one or many categories?

    Basically, you get the genres associated to the film you’re on, you can then run a query on the film post type and loop the results, something like:

    <?php
    $genres = get_the_terms( $post->ID, 'genres' ); 
    $genre = $genres[0];
    
    // print object from first genre
    #print_r($genre);
    
    // or get the genre name
    #echo $genre->name.' '.$genre->term_id;	
    	
    global $wp_query;
    $paged = get_query_var('paged') ? get_query_var('paged') : 1;
    
    $args = array( 
    	'posts_per_page'	=> 3,
    	'post_type'			=> 'film',
    	'paged'				=> $paged,
    	'fields'			=> 'ids',
    	'post__not_in'		=> array( $post->ID )
    );
    if($genre):
    $args['tax_query'] = array (
    	'relation' => 'OR', 
    
    	array(
    		'taxonomy'	=> 'genres',
    		'field'		=> 'term_id',
    		'terms'		=> $genre->term_id
    	), 
    );
    endif;
    
    $wp_query = new WP_Query($args);
    if ($wp_query->have_posts()) :
    ?>	
    
    <h3>Similar Films</h3>
    <ul>
    	<?php while ($wp_query->have_posts()) : $wp_query->the_post(); ?>
    	<li><?php the_title(); ?></li>
    <?php endwhile;  ?>                       
    </ul>
    <?php endif; wp_reset_query(); ?>

    So basically, it you have multiples, it gets the first taxonomy only. You can of course adjust this but should help you out

  • Ok, so the following is based on your code and my suggestion.

    Before doing anything, backup your site.

    You already have the code in your functions file to create the film custom post type.

    So now you can add the following to your functions file:

    
    ########################
    # Add Taxonmoies
    ########################
    
    function register_taxonomies() {
    
    	$taxonomies = array(
    		
    		array(
    			'slug'         => 'genres',
    			'single_name'  => 'Genre',
    			'plural_name'  => 'Genres',
    			'post_type'    => 'film',
    			'hierarchical' => true,
    		),							
    		
    	);
    
    	foreach( $taxonomies as $taxonomy ) {
    		$labels = array(
    			'name' => $taxonomy['plural_name'],
    			'singular_name' => $taxonomy['single_name'],
    			'search_items' =>  'Search ' . $taxonomy['plural_name'],
    			'all_items' => 'All ' . $taxonomy['plural_name'],
    			'parent_item' => 'Parent ' . $taxonomy['single_name'],
    			'parent_item_colon' => 'Parent ' . $taxonomy['single_name'] . ':',
    			'edit_item' => 'Edit ' . $taxonomy['single_name'],
    			'update_item' => 'Update ' . $taxonomy['single_name'],
    			'add_new_item' => 'Add New ' . $taxonomy['single_name'],
    			'new_item_name' => 'New ' . $taxonomy['single_name'] . ' Name',
    			'menu_name' => $taxonomy['plural_name']
    		);
    		
    		$rewrite = isset( $taxonomy['rewrite'] ) ? $taxonomy['rewrite'] : array( 'slug' => $taxonomy['slug'] );
    		$hierarchical = isset( $taxonomy['hierarchical'] ) ? $taxonomy['hierarchical'] : true;
    	
    		register_taxonomy( $taxonomy['slug'], $taxonomy['post_type'], array(
    			'hierarchical' => $hierarchical,
    			'labels' => $labels,
    			'show_ui' => true,
    			'show_admin_column' => true,
    			'query_var' => true,
    			'rewrite' => $rewrite,
    		));
    	}
    	
    }
    add_action( 'init', 'register_taxonomies' );
    
    ##########################
    # Ajax filter Films
    ##########################
    function filter_films() {
    	
    	$args = array(
    		'post_type'			=> 'film',
    		'posts_per_page'	=> -1,
    	);
    
    	if( isset( $_POST['genre'] ) )
    		$args['tax_query'] = array(
    			array(
    				'taxonomy' => 'genres',
    				'field' => 'id',
    				'terms' => $_POST['genre']
    			)
    		);
    		
    
    	$query = new WP_Query( $args );
    	if( $query->have_posts() ) :
    		while( $query->have_posts() ): $query->the_post();
    		?>
    		<h2><?php the_title(); ?></h2>
    		<?php
    		endwhile;
    		wp_reset_postdata();
    	else :
    		echo 'No films found matching your criteria.';
    	endif;
    	
    	die();
    
    }
    // Fire AJAX action for both logged in and non-logged in users
    add_action('wp_ajax_filter_films', 'filter_films');
    add_action('wp_ajax_nopriv_filter_films', 'filter_films');

    The first part creates the custom taxonomy for Genres.
    The second part handles the filtering which we’ll come to next.

    Create a page called films.
    Now create a template file called page-films.php, from here you can add the following code:

    <?php
    /**
     * @package WordPress
     Template Name: Films 
    **/
    get_header();
    ?>
    
    <div id="filters">
    <?php
    $genres = array(
    	'taxonomy'		=> 'genres',
    );
    $genres = get_categories( $genres );
    ?>
    <?php foreach($genres as $genre): ?>
    	<input type="checkbox" value="<?php echo $genre->term_id; ?>" class="form-check-input genre" />
    	<label class="form-check-label" for="<?php echo $genre->cat_name; ?>"><?php echo $genre->cat_name; ?></label>       
    <?php endforeach; ?>
    <a href="#" class="btn" id="reset_genre">Reset Genres</a>  
    </div><!-- /filters -->
    
     
    <div id="ajax_filter_films">	      
    <?php      
    $args = array(
    	'post_type'			=> 'film',
    	'posts_per_page'	=> -1,
    );
            
    $query = new WP_Query( $args );
    if( $query->have_posts() ) :
    	while( $query->have_posts() ): $query->the_post();
        ?>
    	<h2><?php the_title(); ?></h2>
    	<?php
    	endwhile;
    	wp_reset_postdata();
    else :
    	echo 'No films found matching your criteria.';
    endif;
    ?>  
    </div><!-- /ajax_filter_films -->
    
    <?php
    get_footer();

    You can assign the template films to the page, but due to naming conventions, should work. I always add it as a fallback.

    Now, in your footer you can add:

    
    <script type="text/javascript">
    //filter the films
    jQuery(function($){
        filter_data();
    
        function filter_data()
        {
            $('.filter_data').html('<div id="loading" style="" ></div>');
            var action = 'filter_films';		
    		
            var genre = get_filter('genre');	
    		
    		$.ajax({
    			type        : "POST",
    			data		: { action:action, genre:genre},
    			dataType	: "html",
    			url			: '<?php echo admin_url('admin-ajax.php');?>', 
    
    			success     : function(data) {
    				//alert(this.data);
    				jQuery("#ajax_filter_films").html(data);
    			},
    			error       : function(xhr, status, error) {
    				var err = eval("(" + xhr.responseText + ")");
    				alert(err.Message);
    			}
    		});
    		return false;
        }
    
        function get_filter(class_name)
        {
            var filter = [];
            $('.'+class_name+':checked').each(function(){
                filter.push($(this).val());
            });
            return filter;
        }
    
        $('.form-check-input').click(function(){
            filter_data();
        });
    	
    	$("#reset_genre").click(function(){
    		// get the current selected values
    		var genre = [];
    		$('.genre:checked').each(function(){
    			genre.push($(this).val());
    		});
    		
    		// loop through and remove the selected checkobox
    		var i;
    		for (i = 0; i < genre.length; i++) {
    			$(".genre:checkbox[value="+genre[i]+"]").parent().removeClass('selected'); //remove the highlighted lable
    			$(".genre:checkbox[value="+genre[i]+"]").prop("checked", false); //uncheck the hidden checkbox
    		}		
    		
    		// reset the array
    		genre = []; 
    		console.log(genre); //debug
    	
    		// update the filter
    	 	filter_data();			  
    	});				
    	
    });
    </script>

    I’d probably flush the permalinks!

    You can now go to films within wp-admin and you should see a menu option called Genres.
    Add the ones you need
    Edit your films and assign one/multiples.
    Go to the films page on the front end (its basic but gives you the idea).
    You should now see all the films you’ve added plus a bunch of checkboxes.

    Tick one or many and the results should filter!

    The code is completely tested and works with a fresh WP install and the Twentytwentyone theme.

  • Yes that’s exactly what I meant but I couldn’t find how to create a custom taxonomy at the time.

    However, after a bit more research I found that I can install this plugin and create a custom taxonomy that way – would that be the best approach?

    https://en-ca.wordpress.org/plugins/custom-post-type-ui/

  • Why don’t you create your own custom genre taxonomy? That leaves the existing categories for the blogs. Assuming I’ve understood

  • Ok so I’ve thought about this a bit more and experimented with the taxonomy field type but quickly realised that I’d need a separate taxonomy from for example the default posts (e.g. tags or categories). I’m currently using the default posts for a blog part of the website so I don’t want to cross-pollinate between my custom post type and the default posts.

    I’ve tried looking into hiding the option on the default posts menu but all of the solutions result in errors in parts of the sidebar menu.

    Anyway – I resorted to going back to the tutorial Elliot created but I’m now getting an error with my foreach for some reason, no matter whether I’m viewing the standard view or the filtered view?

    https://apexcinemas.andrewcourtney.co.uk/films/
    https://apexcinemas.andrewcourtney.co.uk/films/?film_genre=Action

    Tutorial link again: https://www.advancedcustomfields.com/resources/creating-wp-archive-custom-field-filter/

    <div id=”search-filmgenre”>
    <?php

    $field = get_field_object(‘film_genre’);
    $values = explode(‘,’, $_GET[‘film_genre’]);
    $filmGenres = $field[‘choices’];

    ?>

      <?php foreach($filmGenres as $choice_value => $choice_label) : ?>

    • <input type=”checkbox” value=”<?php echo $choice_value; ?>” <?php if (in_array($choice_value, $values)) : ?>checked=”checked” <?php endif; ?> /><?php echo $choice_label; ?>
    • <?php endforeach; ?>

    </div>

    Any thoughts please? Thanks so much for your help so far.

  • Had to use

    <?php 
    $args = array( 'hide_empty=0', 
            'taxonomy'      => 'molecules_of_the_month',
            'childless'     => 1, 
            'number'        => 6,
            'orderby'       => 'ID', 
            'order'         => 'ASC'
            ); 
    $the_query = new WP_Term_Query($args);
    foreach($the_query->get_terms() as $term) :
    // foreach( $molecules_of_the_month as $month ) : ?>
        <!-- Post Content goes here -->
        <li class="post-grid-post splide__slide">
            <?php
            $summaryimage  = get_field('summary_preview_image', 'term_' .$term->term_id  ); // field, id and format value

    to make it work. Well, that seems to make most of what I want do. Need to limit description, tweak html to work on mobile. But will work well soon.

  • Seems that I need to use WP_Query to loads arguments

    $args = array( 'hide_empty=0', 
                    'childless'     => 1, 
                    'number'        => 6,
                    'orderby'       => 'ID', 
                    'order'         => 'ASC'
                    ); 

    if I want to use these in get_terms. See https://developer.wordpress.org/reference/classes/wp_term_query/get_terms/#user-contributed-notes

    example:

    <ul>
    <?php 
    $args = array(
        'taxonomy'               => 'category',
        'orderby'                => 'name',
        'order'                  => 'ASC',
        'hide_empty'             => false,
    );
    $the_query = new WP_Term_Query($args);
    foreach($the_query->get_terms() as $term){ 
    ?>
        <li><?php echo $term->name." (".$term->count.")"; ?></li>
    <?php
    }
    ?>
    </ul>

    Will look into that.

  • Okay, using this code

    <div id="<?php echo esc_attr($id); ?>" class="<?php echo esc_attr($className); ?>">
      <div class="slider mobile-slider splide" data-splide='{ "type" : "loop", "perPage": "3", "arrows": 0, "breakpoints": { "99999": { "destroy": 1 }, "767": { "perPage": "1" } } }'>
        <div class="splide__track">
            <ul class="post-grid splide__list">
                <?php 
                if( $molecules_of_the_month = get_terms( array( 'taxonomy' => 'molecules_of_the_month', $args ) ) ) :
                    foreach( $molecules_of_the_month as $month ) : 
                        $summaryimage  = get_field('summary_preview_image', 'term_' .$month->term_id  ); // field, id and format value
                        // $summaryimage = get_field('summary_preview_image', 'term_name_', 'molecules_of_the_month'); // NULL++
                        $size = 'full'; // (thumbnail, medium, large, full or custom size)
                        // var_dump($summaryimage);
                        echo '<a href="' . esc_url( get_term_link( $month ) ) . '" alt="' . esc_attr( sprintf( __( 'View all post filed under %s', 'drughunter' ), $month->name) ) . '">' 
                        . $month->name . '</a>';
                    endforeach;
                endif; ?>
            </ul>
        </div>
      </div>
    </div>

    I have the summaryimage loading ids but not in use yet as I need image url. This so I can load the image, title and short description and link it all.

    I also can still load term links using this loop and an echo so that is fine. But need to work out loading image first.

    Furthermore I need to include the $args I had before. Not sure how with current setup. Doing some trials still.

  • @jarvis I used your code with foreach loops:

    <div id="<?php echo esc_attr($id); ?>" class="<?php echo esc_attr($className); ?>">
            <div class="slider mobile-slider splide" data-splide='{ "type" : "loop", "perPage": "3", "arrows": 0, "breakpoints": { "99999": { "destroy": 1 }, "767": { "perPage": "1" } } }'>
                <div class="splide__track">
                    <ul class="post-grid splide__list">
                        <?php 
                        if( $molecules_of_the_month = get_terms( array( 'taxonomy' => 'molecules_of_the_month' ) ) ) :
                            foreach( $molecules_of_the_month as $month ) : 
                                $summaryimage  = get_field('summary_preview_image', 'term_' .$month->term_id  );
                                $size = 'full'; // (thumbnail, medium, large, full or custom size)
                                print_r($summaryimage);
                                // $molecules_of_the_month .= '<a href="' . esc_url( get_term_link( $month ) ) . '" alt="' . esc_attr( sprintf( __( 'View all post filed under %s', 'theme' ), 
                                // $month->name ) ) . '">' . $month->name . '</a><figure class="post-featured-image">' . 
                                // wp_get_attachment_image( $summaryimage, $size ) . '</figure>';
                            endforeach;
                        endif; ?>
                    </ul>
                </div>
            </div>
        </div>

    and I know get 328235043514 or this using var_dump

    NULL int(3282) bool(false) bool(false) bool(false) int(3504) int(3514) bool(false) NULL bool(false) bool(false) bool(false) bool(false) bool(false) bool(false) bool(false) bool(false) bool(false) bool(false) bool(false)

    so I am getting something now. So I guess I needed to load the image in the foreach loop. But I also see you used:

    <?php $summaryimage = get_field('summary_preview_image', 'term_' .$month->term_id );?>

    with term_ .$month->term_id which I am clearly not familiar enough with. Besides understanding this better I also need to load the image url so guess I do not want ID numbers only. How would I do that?

    NB had to post this 3 times to make it stick on the forum

  • @jarvis I used your code with foreach loops:

    <div id="<?php echo esc_attr($id); ?>" class="<?php echo esc_attr($className); ?>">
            <div class="slider mobile-slider splide" data-splide='{ "type" : "loop", "perPage": "3", "arrows": 0, "breakpoints": { "99999": { "destroy": 1 }, "767": { "perPage": "1" } } }'>
                <div class="splide__track">
                    <ul class="post-grid splide__list">
                        <?php 
                        if( $molecules_of_the_month = get_terms( array( 'taxonomy' => 'molecules_of_the_month' ) ) ) :
                            foreach( $molecules_of_the_month as $month ) : 
                                $summaryimage  = get_field('summary_preview_image', 'term_' .$month->term_id  );
                                $size = 'full'; // (thumbnail, medium, large, full or custom size)
                                print_r($summaryimage);
                                // $molecules_of_the_month .= '<a href="' . esc_url( get_term_link( $month ) ) . '" alt="' . esc_attr( sprintf( __( 'View all post filed under %s', 'theme' ), 
                                // $month->name ) ) . '">' . $month->name . '</a><figure class="post-featured-image">' . 
                                // wp_get_attachment_image( $summaryimage, $size ) . '</figure>';
                            endforeach;
                        endif; ?>
                    </ul>
                </div>
            </div>
        </div>

    and I know get 328235043514 or this using var_dump

    NULL int(3282) bool(false) bool(false) bool(false) int(3504) int(3514) bool(false) NULL bool(false) bool(false) bool(false) bool(false) bool(false) bool(false) bool(false) bool(false) bool(false) bool(false) bool(false)

    so I am getting something now. So I guess I needed to load the image in the foreach loop. But I also see you used:

    <?php $summaryimage = get_field('summary_preview_image', 'term_' .$month->term_id );?>

    with term_ .$month->term_id which I am clearly not familiar enough with. Besides understanding this better I also need to load the image url so guess I do not want ID numbers only. How would I do that?

Viewing 25 results - 901 through 925 (of 3,193 total)