$conf, $runtime; function_exists('chdir') AND chdir(APP_PATH); $r = 'mysql' == $conf['cache']['type'] ? website_set('runtime', $runtime) : cache_set('runtime', $runtime); } function runtime_truncate() { global $conf; 'mysql' == $conf['cache']['type'] ? website_set('runtime', '') : cache_delete('runtime'); } register_shutdown_function('runtime_save'); ?>functions - How to display the link (title) and thumbnail post?|Programmer puzzle solving
最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

functions - How to display the link (title) and thumbnail post?

matteradmin9PV0评论

I found this related post code here, but the code calling it is incomplete, it only shows the article title. How do I make the links and thumbnails appear?

I really hope someone helps, because this is very suitable for the scenario I want.

function get_max_related_posts( $taxonomy_1 = 'post_tag', $taxonomy_2 = 'category', $total_posts = 4 )
{
// First, make sure we are on a single page, if not, bail
if ( !is_single() )
    return false;

// Sanitize and vaidate our incoming data
if ( 'post_tag' !== $taxonomy_1 ) {
    $taxonomy_1 = filter_var( $taxonomy_1, FILTER_SANITIZE_STRING );
    if ( !taxonomy_exists( $taxonomy_1 ) )
        return false;
}

if ( 'category' !== $taxonomy_2 ) {
    $taxonomy_2 = filter_var( $taxonomy_2, FILTER_SANITIZE_STRING );
    if ( !taxonomy_exists( $taxonomy_2 ) )
        return false;
}

if ( 4 !== $total_posts ) {
    $total_posts = filter_var( $total_posts, FILTER_VALIDATE_INT );
        if ( !$total_posts )
            return false;
}

// Everything checks out and is sanitized, lets get the current post
$current_post = sanitize_post( $GLOBALS['wp_the_query']->get_queried_object() );

// Lets get the first taxonomy's terms belonging to the post
$terms_1 = get_the_terms( $current_post, $taxonomy_1 );

// Set a varaible to hold the post count from first query
$count = 0;
// Set a variable to hold the results from query 1
$q_1   = [];

// Make sure we have terms
if ( $terms_1 ) {
    // Lets get the term ID's
    $term_1_ids = wp_list_pluck( $terms_1, 'term_id' );

    // Lets build the query to get related posts
    $args_1 = [
        'post_type'      => $current_post->post_type,
        'post__not_in'   => [$current_post->ID],
        'posts_per_page' => $total_posts,
        'fields'         => 'ids',
        'tax_query'      => [
            [
                'taxonomy'         => $taxonomy_1,
                'terms'            => $term_1_ids,
                'include_children' => false
            ]
        ],
    ];
    $q_1 = get_posts( $args_1 );
    // Count the total amount of posts
    $q_1_count = count( $q_1 );

    // Update our counter
    $count = $q_1_count;
}

// We will now run the second query if $count is less than $total_posts
if ( $count < $total_posts ) {
    $terms_2 = get_the_terms( $current_post, $taxonomy_2 );
    // Make sure we have terms
    if ( $terms_2 ) {
        // Lets get the term ID's
        $term_2_ids = wp_list_pluck( $terms_2, 'term_id' );

        // Calculate the amount of post to get
        $diff = $total_posts - $count;

        // Create an array of post ID's to exclude
        if ( $q_1 ) {
            $exclude = array_merge( [$current_post->ID], $q_1 );
        } else {
            $exclude = [$current_post->ID];
        }

        $args_2 = [
            'post_type'      => $current_post->post_type,
            'post__not_in'   => $exclude,
            'posts_per_page' => $diff,
            'fields'         => 'ids',
            'tax_query'      => [
                [
                    'taxonomy'         => $taxonomy_2,
                    'terms'            => $term_2_ids,
                    'include_children' => false
                ]
            ],
        ];
        $q_2 = get_posts( $args_2 );

        if ( $q_2 ) {
            // Merge the two results into one array of ID's
            $q_1 = array_merge( $q_1, $q_2 );
        }
    }
}

// Make sure we have an array of ID's
if ( !$q_1 )
    return false;

// Run our last query, and output the results
$final_args = [
    'ignore_sticky_posts' => 1,
    'post_type'           => $current_post->post_type,
    'posts_per_page'      => count( $q_1 ),
    'post__in'            => $q_1,
    'order'               => 'ASC',
    'orderby'             => 'post__in',
    'suppress_filters'    => true,
    'no_found_rows'       => true
];
$final_query = new WP_Query( $final_args );

return $final_query;
}

this is the calling code:

$query = get_max_related_posts();
if ( $query ) {

    while ( $query->have_posts() ) {
        $query->the_post();

        echo get_the_title() . '</br>';

    }
    wp_reset_postdata();
}

I found this related post code here, but the code calling it is incomplete, it only shows the article title. How do I make the links and thumbnails appear?

I really hope someone helps, because this is very suitable for the scenario I want.

function get_max_related_posts( $taxonomy_1 = 'post_tag', $taxonomy_2 = 'category', $total_posts = 4 )
{
// First, make sure we are on a single page, if not, bail
if ( !is_single() )
    return false;

// Sanitize and vaidate our incoming data
if ( 'post_tag' !== $taxonomy_1 ) {
    $taxonomy_1 = filter_var( $taxonomy_1, FILTER_SANITIZE_STRING );
    if ( !taxonomy_exists( $taxonomy_1 ) )
        return false;
}

if ( 'category' !== $taxonomy_2 ) {
    $taxonomy_2 = filter_var( $taxonomy_2, FILTER_SANITIZE_STRING );
    if ( !taxonomy_exists( $taxonomy_2 ) )
        return false;
}

if ( 4 !== $total_posts ) {
    $total_posts = filter_var( $total_posts, FILTER_VALIDATE_INT );
        if ( !$total_posts )
            return false;
}

// Everything checks out and is sanitized, lets get the current post
$current_post = sanitize_post( $GLOBALS['wp_the_query']->get_queried_object() );

// Lets get the first taxonomy's terms belonging to the post
$terms_1 = get_the_terms( $current_post, $taxonomy_1 );

// Set a varaible to hold the post count from first query
$count = 0;
// Set a variable to hold the results from query 1
$q_1   = [];

// Make sure we have terms
if ( $terms_1 ) {
    // Lets get the term ID's
    $term_1_ids = wp_list_pluck( $terms_1, 'term_id' );

    // Lets build the query to get related posts
    $args_1 = [
        'post_type'      => $current_post->post_type,
        'post__not_in'   => [$current_post->ID],
        'posts_per_page' => $total_posts,
        'fields'         => 'ids',
        'tax_query'      => [
            [
                'taxonomy'         => $taxonomy_1,
                'terms'            => $term_1_ids,
                'include_children' => false
            ]
        ],
    ];
    $q_1 = get_posts( $args_1 );
    // Count the total amount of posts
    $q_1_count = count( $q_1 );

    // Update our counter
    $count = $q_1_count;
}

// We will now run the second query if $count is less than $total_posts
if ( $count < $total_posts ) {
    $terms_2 = get_the_terms( $current_post, $taxonomy_2 );
    // Make sure we have terms
    if ( $terms_2 ) {
        // Lets get the term ID's
        $term_2_ids = wp_list_pluck( $terms_2, 'term_id' );

        // Calculate the amount of post to get
        $diff = $total_posts - $count;

        // Create an array of post ID's to exclude
        if ( $q_1 ) {
            $exclude = array_merge( [$current_post->ID], $q_1 );
        } else {
            $exclude = [$current_post->ID];
        }

        $args_2 = [
            'post_type'      => $current_post->post_type,
            'post__not_in'   => $exclude,
            'posts_per_page' => $diff,
            'fields'         => 'ids',
            'tax_query'      => [
                [
                    'taxonomy'         => $taxonomy_2,
                    'terms'            => $term_2_ids,
                    'include_children' => false
                ]
            ],
        ];
        $q_2 = get_posts( $args_2 );

        if ( $q_2 ) {
            // Merge the two results into one array of ID's
            $q_1 = array_merge( $q_1, $q_2 );
        }
    }
}

// Make sure we have an array of ID's
if ( !$q_1 )
    return false;

// Run our last query, and output the results
$final_args = [
    'ignore_sticky_posts' => 1,
    'post_type'           => $current_post->post_type,
    'posts_per_page'      => count( $q_1 ),
    'post__in'            => $q_1,
    'order'               => 'ASC',
    'orderby'             => 'post__in',
    'suppress_filters'    => true,
    'no_found_rows'       => true
];
$final_query = new WP_Query( $final_args );

return $final_query;
}

this is the calling code:

$query = get_max_related_posts();
if ( $query ) {

    while ( $query->have_posts() ) {
        $query->the_post();

        echo get_the_title() . '</br>';

    }
    wp_reset_postdata();
}
Share Improve this question edited Feb 17, 2019 at 11:38 Krzysiek Dróżdż 25.6k9 gold badges53 silver badges74 bronze badges asked Feb 17, 2019 at 11:31 R.M. RezaR.M. Reza 1417 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 0

The first part of your code is responsible for building the query and getting the related posts. So if this part works OK, you don't have to change anything in it.

This is the part that is responsible for displaying them:

$query = get_max_related_posts();
if ( $query ) {  // PS. This condition doesn't make any sense it should be $query->have_posts()...

    while ( $query->have_posts() ) {
        $query->the_post();

        echo get_the_title() . '</br>';

    }
    wp_reset_postdata();
}

And as you can see, only titles are echoed in there.

So if you want to display anything more, you'll have to change this part according to your needs. Here's an example:

<?php 
    $query = get_max_related_posts();
    if ( $query->have_posts() ) :
?>
<ul>
    <?php while ( $query->have_posts() ) : $query->the_post(); ?>
    <li>
        <a href="<?php the_permalink(); // <- this shows the url to the post ?>">
            <?php the_post_thumbnail( 'post-thumbnail' ); // <- this shows the thumbnail ?>
            <?php the_title(); // <- this shows the title ?>
        </a>
    </li>
    <?php endwhile; wp_reset_postdata(); ?>
</ul>
<?php endif; ?>
Post a comment

comment list (0)

  1. No comments so far