codingdir logo sitemap sitemap |
Home
PHP
C#
C++
ANDROID
JAVA
JAVASCRIPT
PYTHON

Show related posts by taxonomy Wordpress


By : , Category : php

Did you tried adding the following argument to your WP_Query array of arguments?

  'tax_query' => array(array('taxonomy' => 'product_cat'))

The code will look like this (of course after removing the category parameter):

<?php
global $post;

$loop = new WP_Query( array( 'post_type' => 'product','post__not_in' => array($post->ID),  'tax_query' => array(array('taxonomy' => 'product_cat'))) ); ?>

<?php while ( $loop->have_posts() ) : $loop->the_post(); ?>

<?php the_title( '<h2 class="entry-title"><a href="' . get_permalink() . '" title="' . the_title_attribute( 'echo=0' ) . '" rel="bookmark">', '</a></h2>' ); ?>

<?php endwhile; ?>
ReLated :

Try this:

$post_terms = wp_get_object_terms($post->ID, 'your-taxonomy', array('fields'=>'ids'));

$args = array(
    'post_type' => 'current-products',
    'tax_query' => array(
        array(
            'taxonomy' => 'your-taxonomy',
            'field' => 'id',
            'terms' => $post_terms
        )
    )
);
$the_query = new WP_Query( $args );
if ( $the_query->have_posts() ) {
        echo '<ul>';
    while ( $the_query->have_posts() ) {
        $the_query->the_post();
        ?>
                    <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
            <?php
    }
        echo '</ul>';
} else {
    // no posts found
}
wp_reset_postdata();

You should replace occurrences of your-taxonomy in the code with your taxonomy type in order this code to work.

As I already stated, your code is completely wrong and will not work. I'm not going to go into details about your code as I would just scrap your code and start from the beginning

Here is a copy of a post I have recently done on WPSE. This is basically a copy and paste solution, the only thing here being that posts aren't radomly ordered, so you need to add random ordering into the query arguments.

Here is the post:

I would just just scrap the function above as there are several bugs in the code and is also not quite effecient. I am actually surpriced that it really works for you.

Your best solution here would be to write a complete new function. Here is want we want to do and how we are going to accomplish this

  • Get the current post object on the single post page. $post is unreliable, so we are going to use the main query object here which we will return with get_queried_object(). From here we can use the post ID and post type to get other related info

  • Get the terms of the current post being viewed with wp_get_post_term(). We will set the fields paremeter to only get the term ids. This returnes array of term ids can then be used in our tax_query

  • Add in some validation to validate the user input and also sanitize the input

Lets put that all in code (CAVEAT: This is all untested and requires at least PHP 5.4+)

function get_related_posts( $taxonomy = '', $args = [] )
{
    /*
     * Before we do anything and waste unnecessary time and resources, first check if we are on a single post page
     * If not, bail early and return false
     */
    if ( !is_single() )
        return false;

    /*
     * Check if we have a valid taxonomy and also if the taxonomy exists to avoid bugs further down.
     * Return false if taxonomy is invalid or does not exist
     */
    if ( !$taxonomy ) 
        return false;

    $taxonomy = filter_var( $taxonomy, FILTER_SANITIZE_STRING );
    if ( !taxonomy_exists( $taxonomy ) )
        return false;

    /*
     * We have made it to here, so we should start getting our stuff togther. 
     * Get the current post object to start of
     */
    $current_post = get_queried_object();

    /*
     * Get the post terms, just the ids
     */
    $terms = wp_get_post_terms( $current_post->ID, $taxonomy, ['fields' => 'ids'] );

    /*
     * Lets only continue if we actually have post terms and if we don't have an WP_Error object. If not, return false
     */
    if ( !$terms || is_wp_error( $terms ) )
        return false;

    /*
     * Set the default query arguments
     */
    $defaults = [
        'post_type' => $current_post->post_type,
        'post__not_in' => [$current_post->ID],
        'tax_query' => [
            [
                'taxonomy' => $taxonomy,
                'terms' => $terms,
                'include_children' => false
            ],
        ],
    ];

    /*
     * Validate and merge the defaults with the user passed arguments
     */
    if ( is_array( $args ) ) {
        $args = wp_parse_args( $args, $defaults );
    } else {
        $args = $defaults;
    }

    /*
     * Now we can query our related posts and return them
     */
    $q = get_posts( $args );

    return $q;
}

Now that we have a better function in place, we can use it in our single post page or content template parts depending on your exact use case. As you might have noticed, our new function get_related_posts() has two parameters, the first one which accepts a single taxonomy value, and the second an array of arguments. This arguments will the arguments passed to our query, so you can pass any valid array of arguments that is acceptible to WP_Query and get_posts here.

Example:

You need one post to be returned, so you can try the following: (Please note, do not use the post type parameter or any of the taxonomy type parameters here, you might get unexpected output)

if ( function_exists( 'get_related_posts' ) ) {
    $related_posts = get_related_posts( 'my_taxonomy_name', ['posts_per_page' => 1] );
    if ( $related_posts ) {
        foreach ( $related_posts as $post ) {
            setup_postdata( $post ); 
            // Use your template tags and html mark up as normal like
            the_title();
            the_content();
            // etc etc
        }
        wp_reset_postdata();
    }
}

EDIT

From comments it seems that your PHP version is older than 5.4 which does not support the new short array syntax ([]), and therefor you get the dreaded WSOD. For this to work, you need change the new array syntax to the old syntax (array()).

You can try the following:

function get_related_posts( $taxonomy = '', $args = array() )
{
    /*
     * Before we do anything and waste unnecessary time and resources, first check if we are on a single post page
     * If not, bail early and return false
     */
    if ( !is_single() )
        return false;

    /*
     * Check if we have a valid taxonomy and also if the taxonomy exists to avoid bugs further down.
     * Return false if taxonomy is invalid or does not exist
     */
    if ( !$taxonomy ) 
        return false;

    $taxonomy = filter_var( $taxonomy, FILTER_SANITIZE_STRING );
    if ( !taxonomy_exists( $taxonomy ) )
        return false;

    /*
     * We have made it to here, so we should start getting our stuff togther. 
     * Get the current post object to start of
     */
    $current_post = get_queried_object();

    /*
     * Get the post terms, just the ids
     */
    $terms = wp_get_post_terms( $current_post->ID, $taxonomy, array( 'fields' => 'ids') );

    /*
     * Lets only continue if we actually have post terms and if we don't have an WP_Error object. If not, return false
     */
    if ( !$terms || is_wp_error( $terms ) )
        return false;

    /*
     * Set the default query arguments
     */
    $defaults = array(
        'post_type' => $current_post->post_type,
        'post__not_in' => array( $current_post->ID),
        'tax_query' => array(
            array(
                'taxonomy' => $taxonomy,
                'terms' => $terms,
                'include_children' => false
            ),
        ),
    );

    /*
     * Validate and merge the defaults with the user passed arguments
     */
    if ( is_array( $args ) ) {
        $args = wp_parse_args( $args, $defaults );
    } else {
        $args = $defaults;
    }

    /*
     * Now we can query our related posts and return them
     */
    $q = get_posts( $args );

    return $q;
}

And then to use the code in templates, change to

if ( function_exists( 'get_related_posts' ) ) {
    $related_posts = get_related_posts( 'my_taxonomy_name', array( 'posts_per_page' => 1) );
    if ( $related_posts ) {
        foreach ( $related_posts as $post ) {
            setup_postdata( $post ); 
            // Use your template tags and html mark up as normal like
            the_title();
            the_content();
            // etc etc
        }
        wp_reset_postdata();
    }
}

Add orderby rand in your arguments and use it like below,

<?php 
   $posts = get_posts('orderby=rand&numberposts=5'); 
   foreach($posts as $post) { ?>
   <a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a>
<?php } ?>

Amended Answer

Using a custom get post should fix it.

<?php
$args = array(
     'post_type' => 'recipe',
     'slug' => 'soups',
     'post_status' => 'publish'
);
$show_recipes= get_posts( $args );
echo $show_recipes->post_count;
?>

Function Reference

Comments


Message :
Login to Add Your Comments .
How to disable registered OpenCL platforms on Windows?
Is Observable broken in Angular 2 Beta 3?
Cross-thread operation not valid when using Invoke
How to pass an IEnumerable or queryable list of properties from Controller to View
Finding numbers after a certain keyword using Python
Pocketsphinx recognizes random phrases in a silence
Passing non-thread-safe objects through thread-safe containers
React scroll nav
BizTalk WCF-BasicHttp Adapter does not allow Empty string for Service Certificate Props
Why property ''cause" of Exception is repeating forever?
Privacy Policy 2017 © codingdir.com All Rights Reserved .