WordPress.org

Ready to get started?Download WordPress

Forums

Same category and at less one common tag (3 posts)

  1. sugardaddy
    Member
    Posted 2 years ago #

    Hi !
    I wrote a little piece of code to display custom posts in a particular custom category.
    And it works ;-)
    I wanted to limit these posts to the ones who share at less 1 tag.
    And it doesn't work... surprisingly ^^

    <?php
    $tags = wp_get_post_tags($post->ID);
    	$tag_ids = array();
    	foreach($tags as $individual_tag) $tag_ids[] = $individual_tag->term_id;
    
    	$args = array(
    	'post_type' => 'antidot-pages',
    	'antidot-taxo' => 'references',
    	'tag__in' => $tag_ids,
    	'post_status' => 'publish',
    	'posts_per_page' => 4,
    	'orderby' => 'rand'
    	);
    
    $ref = new WP_Query( $args );
    
    <?php while($ref->have_posts()) : $ref->the_post(); ?>
    <div class="widget widget-solutions-refs">
    <?php the_title(); ?>
    </div>
    <?php endwhile; ?>

    Thanks to all for your help

    PS : sorry, it's a local dev for now, no url to see

  2. sugardaddy
    Member
    Posted 2 years ago #

    I found this : http://wordpress.org/support/topic/show-posts-with-same-tags-as-current-single-post
    But this doesn't work at all for me.
    I'm trying to do that in a (php) widget with the Hybrid framework (child theme).

  3. sugardaddy
    Member
    Posted 2 years ago #

    The french team gave me an answer to find out a goof solution.
    Here's the code (in a widget).

    <?php
    global $wp_query;
    $PostID = $wp_query->post->ID; // get the ID (depends on your theme construction)
    
    $tags = wp_get_post_tags($PostID); // get the tags
    $tags_id = array();
    foreach($tags as $individual_tag) {
    $tags_id[] = $individual_tag->term_id; // parse it individually
    }
    $ref = new WP_Query( array(
        'post_type' => 'antidot-pages', // your custom post type
        'tax_query' => array( // you must do that to combine category and tags
        	'relation' => 'AND',
        	array( 'taxonomy' => 'antidot-taxo', 'field' => 'slug', 'terms' => array( 'references' )), // your custom taxonomy
        	array( 'taxonomy' => 'post_tag', 'field' => 'id', 'terms' => $tags_id)
        ),
        'post_status' => 'publish',
        'posts_per_page' => 4, // whatever you want !
        'orderby' => 'rand'
        ) );
    ?>
    
    <?php while($ref->have_posts()) : $ref->the_post(); ?>
    <div class="widget widget-solutions-refs">
    <a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>">
    <?php the_title(); ?></a>
    </div>
    <?php endwhile; ?>

    That works beautifully !!

Topic Closed

This topic has been closed to new replies.

About this Topic