如何链接到同期限的最新定制帖子

时间:2020-07-27 作者:ZackAkai

标题说明了一切。我正在尝试链接到自定义帖子类型的最新帖子,但只在同一期限内。目前,我的代码成功地回显了正确的术语ID,但没有在屏幕上显示链接。

<?php

    // Get the ID of the current posts\'s term
    $terms = get_the_terms( get_the_ID(), \'comic-series\' );

    // Only get the parent term and ignore child terms
    foreach ( $terms as $term ){
        if ( $term->parent == 0 ) {
            
            // Echo the term (this is only for debugging purposes)
            echo $term->term_id;
            
            // Take only the most recent post of same term
            $args = array( \'numberposts\' => \'1\', \'category\' => $term->term_id );
            $recent_posts = wp_get_recent_posts( $args );
            
            // Link to most recent post of same term
            foreach( $recent_posts as $recent ){ ?> 
                <a href="<?php get_the_permalink( $recent->ID ); ?>">
                    >>  
                </a> <?php
            }
        }
    } 
    
?>

2 个回复
SO网友:ZackAkai

我最终改用wp\\u query,因为无论我怎么做,我都无法让wp\\u get\\u recent\\u posts工作。对于将来需要此功能的任何人,以下是我使用的代码:

// Get the ID of the current posts\'s term
    $terms = get_the_terms( $post->ID, \'comic-series\' );

    // Only get the parent term and ignore child terms
    foreach ( $terms as $term ){
        if ( $term->parent == 0 ) {

            // Query Options
            $query_options = array(
                \'posts_per_page\' => 1,
                \'orderby\' => \'title\', // I\'ve ordered all my posts by title but change this for your needs 
                \'order\' => \'DESC\',
                \'tax_query\' => array(
                    array(
                        \'taxonomy\' => \'comic-series\',
                        \'field\'    => \'term_id\',
                        \'terms\'    => $term->term_id,
                    ),
                ),
             );
             
            //Query
            $the_query = new WP_Query( $query_options ); 

            while ($the_query -> have_posts()) : $the_query -> the_post();
             
                // Link to the latest page
                ?> <a href="<?php the_permalink(); ?>">LINK TEXT</a> <?php
             
            endwhile;
            wp_reset_postdata();    
            
        }
    } 

SO网友:mozboz

不确定这是否是唯一的错误,但请注意get_ 在前面,当他们返回PHP中的值时,不会将其回显到屏幕上。没有的人会回应它。

因此,您可能想要:

            foreach( $recent_posts as $recent ){ ?> 
                <a href="<?php the_permalink( $recent->ID ); ?>">
                    >>  
                </a> <?php
            }
注释删除get_ 从函数