如何在我的自定义模板页面中获得类别明智的帖子

时间:2019-09-13 10:07:41

标签: wordpress

这是我的代码。我想在自定义页面模板中显示相关的帖子。现在,它将仅在管理员端正常工作。但是,当我没有登录我的帐户以及当时以订户身份登录时,它也无法正常运行。这是我的代码,请帮助我。

$args = array('post_type' => 'psdupload',
                    'posts_per_page' => 4,
                    'category__in' => wp_get_post_categories(get_the_ID()),
                    'post__not_in' => array (get_the_ID()),
                    'post_status' => 'publish',                    
                );               
                $loop = new WP_Query($args);

                //FOR CHECK IF POST ARRAY NULL OR NOT
                if($loop->have_posts())
                {
                    $loop = new WP_Query($args);                    
                }
                else
                {
                    $recent_args = array(
                        'post_type' => 'psdupload',
                        'posts_per_page' => 4,
                        'orderby'        => 'date',
                        'order'          => 'DESC',
                        'post__not_in' => array (get_the_ID()),
                        'post_status' => 'publish',                       
                    );
                    $loop = new WP_Query( $recent_args );                    
                }

此外,我将根据需要使用“ $ loop”变量。

1 个答案:

答案 0 :(得分:0)

您可以添加以下代码段-

global $post;
    $args = array( 
        'post_type'     => 'psdupload', 
        'posts_per_page'=> 4,
        'category__in'  => wp_get_post_categories($post->ID), 
        'post__not_in'  => array($post->ID),
        'post_status'   => 'publish',  
    );
    $loop = new WP_Query($args); 
    if( !$loop->have_posts() ) {
        $args = array( 
            'post_type'     => 'psdupload', 
            'posts_per_page'   => 4,
            'orderby'       => 'date',
            'order'         => 'DESC',
            'post__not_in'  => array($post->ID),
            'post_status'   => 'publish',  
        );
        $loop = new WP_Query($args); 
    }

    if( $loop->have_posts() ) {
        ?>
        <ul>
        <?php while ( $loop->have_posts() ) : $loop->the_post(); ?>
            <li>
                <a href="<?php the_permalink() ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a>
            </li>
        <?php endwhile;
        wp_reset_postdata(); ?>
        </ul>
        <?php
    }