Site logo

Archived topic

Wp Show Post Related Post Hook

7 replies · Started by Samuel on May 23, 2020

Viewing posts 1–8 of 8

Hi,

I used the hook to display related posts with Wp Show post but I'm in front an issue I didn't find how to fix.

I use a 3 column template on Wp show post to display 3 related posts. But when there is only 1 o 2 posts in a category (as this is a new website) it displays a blank space. Most of my posts are in 2 different categories, so if one category contains less than 3 posts is there a possibility to search for a post in the other category to fill the empty columns ?

Here is the function I'm using :


<?php
if ( is_single() ) {
    $cats =  get_the_category();
    $cat = $cats[0];
} else {
    $cat = get_category( get_query_var( 'cat' ) );
}

$cat_slug = $cat->slug;
$list = get_page_by_title( 'related', 'OBJECT', 'wp_show_posts' );
wpsp_display( $list->ID, 'tax_term="' . $cat_slug . '"' );
?>

Here is a post where you can see the problem at the end : https://destinationsudouest.com/visiter-la-bastide-clairence-pays-basque/

Hi Tom, thanks for your reply,

I red this thread and tried to understand it but I can't figure out how to adapt it to my situation.

If I understood the final function in this thread permits to display related post by tag and if there's no post in tag to display by category right ?

Is it possible to do the opposite ? to display by category and then by tags ?

I tried naively to just replace "tags" with cats" and "cats" but "tags" in the function but obviously it does not work as I really don't know how php's work.

Hi there

So you would want it to:

1. Display by the current category if it exists.
2. If it doesn't exist, display it by the current tag.

Is that correct?

Yes !

In that case, you could try this:

<div class="wpsp-related-posts1  grid-container">
    <h2>Related Posts</h2>
    <?php
    $tax = 'category';
    $tax_term = '';

    if ( is_single() ) {
        $cats =  get_the_category();
        $tax_term = $cats[0]->slug;

        $args = array(
            'numberposts' => 5,
            'category_name' => $tax_term,
            'post__not_in' => array( get_the_ID() )
        );

        $posts = get_posts( $args );

        if ( ! empty( $posts ) ) {
            $tax_term = $tax_term;
        } else {
            $tags =  get_the_tags();
            $tax_term = $tags[0]->slug;
            $tax = 'post_tag';
        }
    }

    $list = get_page_by_title( 'related', 'OBJECT', 'wp_show_posts' );
    wpsp_display( $list->ID, 'taxonomy=' . $tax . '&tax_term=' . $tax_term );
    ?>
</div>

Hi Tom, thanks for your help, sadly it doesn't seem to work, but don't worry I don't want to waste your time, I will use a plugin to do it and it will be fine.

When it comes to related posts, a related posts plugin is definitely the better option :)

This archived topic is closed to new replies.