Почему я не могу использовать WP_QUERY для своего пользовательского типа записи? - PullRequest
0 голосов
/ 11 мая 2019

Я создал связанную функцию записи и добавил ее в wordpress functions.php.

function related_posts($args = array()) {
    global $post;

    // default args
    $args = wp_parse_args($args, array(
        'post_id' => !empty($post) ? $post->ID : '',
        'taxonomy' => 'category',
        'limit' => 4,
        'post_type' => !empty($post) ? $post->post_type : 'post',
        'orderby' => 'date',
        'order' => 'DESC'
    ));

    // check taxonomy
    if (!taxonomy_exists($args['taxonomy'])) {
        return;
    }

    // post taxonomies
    $taxonomies = wp_get_post_terms($args['post_id'], $args['taxonomy'], array('fields' => 'ids'));
    if (empty($taxonomies)) {
        return;
    }

    // query
    //  $related_posts = get_posts(array(
    $related_posts = new WP_Query(array(
        'post__not_in' => (array) $args['post_id'],
        'post_type' => $args['post_type'],
                'tax_query' => array(
                array(
                   'taxonomy' => $args['taxonomy'],
                   'field' => 'term_id',
                   'terms' => $taxonomies
                ),
            ),
            'posts_per_page' => $args['limit'],
            'orderby' => $args['orderby'],
            'order' => $args['order']
        ));

        if  $related_posts ) {
            echo 'ok';
        } else {
            echo 'not ok';
        }
    ?>
    <?php if (!empty($related_posts)) { ?>
        <h3 class="widget-title"><?php _e('<h5 class="title is-6">You Might Also Like</h5>', 'http://localhost/wordpress_john/wordpress1/'); ?></h3>

        <div class="columns  ">
        <?php
           include( locate_template('related-posts-template.php', false, false) );
        ?>
        </div>
        <?php
        }
        ?>
        <?php
             wp_reset_postdata();
        }

        // related posts
        add_action( 'comment_form_before', 'related_posts', 10, 0 ) ;

Я создал собственный пост (post_type => 'custom'), его шаблон и т. Д., Который работает нормально. Но этот код не показывает связанные сообщения, когда зритель просматривает пользовательские сообщения, которые обслуживаются из single-custom.php Первоначально этот код был с get_posts, и я преобразовал его в WP_QUERY, так как код возвращался пустым из get_posts, почему? Сообщения Single.php отображали похожие сообщения, как и должны, но не single-custom.php. Затем я преобразовал в WP_QUERY, так как get_posts немного ограничен, чем WP_QUERY, и все же пользовательский пост (single-custom.php) не показывает связанных постов, но здесь заполняется переменная $ related_posts. Помогите!

1 Ответ

0 голосов
/ 24 мая 2019
**Try this working code:**

 <?php $customTaxonomyTerms = wp_get_object_terms( $post->ID, 'category', array('fields' => 'ids') );

        $args = array(
            'post_type' => 'events',
            'post_status' => 'publish',
            'posts_per_page' => 5,
            'orderby' => 'rand',
            'tax_query' => array(
                array(
                    'taxonomy' => 'category',
                    'field' => 'id',
                    'terms' => $customTaxonomyTerms
                )
            ),
            'post__not_in' => array ($post->ID),
        );

        //the query
        $relatedPosts = new WP_Query( $args );

        //loop through query
        if($relatedPosts->have_posts()){
            echo '<ul>';
            while($relatedPosts->have_posts()){ 
               $relatedPosts->the_post(); ?>
               <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
               <?php } echo '</ul>';
             }else{
            //no posts found
            }
          wp_reset_postdata();
        ?>
...