'post__not_in'不适用于分类法(wordpress)的相关帖子

时间:2015-06-12 07:05:31

标签: php wordpress

我正按分类标准创建相关帖子。 我有代码: (在functions.php中)

    // Create a query for the custom taxonomy
function related_posts_by_taxonomy( $post_id, $taxonomy, $args=array() ) {
    $terms = wp_get_object_terms( $post_id, $taxonomy );
// Make sure we have terms from the current post
    if ( count( $terms ) ) {
        $post_ids = get_objects_in_term( $terms[0]->term_id, $taxonomy );
        $post = get_post( $post_id );
        $post_type = get_post_type( $post );

    // Only search for the custom taxonomy on whichever post_type
    // we AREN'T currently on
    // This refers to the custom post_types you created so
    // make sure they are spelled/capitalized correctly
    if ( strcasecmp($post_type, 'colors') == 0 ) {
        $type = 'colors';
    } else {
        $type = 'colors';
    }

    $args = wp_parse_args( $args, array(
            'post_type' => $type,
            'post__not_in' => array($post_id),
            'post__in' => $post_ids,
            'taxonomy' => $taxonomy,
            'term' => $terms[1]->slug,
            'posts_per_page' => 5,
            'orderby' => 'rand'
        ) );
    $query = new WP_Query( $args );
}
print_r($post_id);
// Return our results in query form
return $query;
}

在我的模板single-colors.php

<?php $related =  related_posts_by_taxonomy( $post->ID, 'colors_tax' );
while ( $related->have_posts() ): $related->the_post(); ?>
<strong class="center block fz">
<?php echo $ncolors; ?>
</strong>
<h1 class="no-m"><?php the_title();?></h1>
<?php endwhile; ?>

代码有效。但是这个代码也显示我的帖子重复(在分类的相关帖子中)。如何消除它? 'post__not_in' => array($post_id)不起作用。

1 个答案:

答案 0 :(得分:4)

正如我已经说过的,你的代码是完全错误的,不起作用。我不会详细介绍您的代码,因为我只是废弃您的代码并从头开始

以下是我最近在WPSE上发布的帖子的副本。这基本上是一个复制和粘贴解决方案,这里唯一的事情是帖子没有粗略排序,所以你需要在查询参数中添加随机排序。

这是帖子:

我只是废弃上面的函数,因为代码中有几个错误,也不是很有效。实际上,我真的很高兴它真的适合你。

这里最好的解决方案是编写一个完整的新功能。这是我们想要做的以及我们将如何完成这个

  • 在单个帖子页面上获取当前帖子对象。 $post不可靠,因此我们将在此处使用主查询对象,我们将使用get_queried_object()返回该对象。从这里我们可以使用帖子ID和帖子类型来获取其他相关信息

  • 使用wp_get_post_term()获取当前帖子的条款。我们将fields参数设置为仅获取术语ID。然后可以在我们的tax_query

  • 中使用这些返回的术语ID
  • 添加一些验证以验证用户输入并清理输入

让我们把它全部放在代码中( CAVEAT:这都是未经测试的,至少需要PHP 5.4 +

function get_related_posts( $taxonomy = '', $args = [] )
{
    /*
     * Before we do anything and waste unnecessary time and resources, first check if we are on a single post page
     * If not, bail early and return false
     */
    if ( !is_single() )
        return false;

    /*
     * Check if we have a valid taxonomy and also if the taxonomy exists to avoid bugs further down.
     * Return false if taxonomy is invalid or does not exist
     */
    if ( !$taxonomy ) 
        return false;

    $taxonomy = filter_var( $taxonomy, FILTER_SANITIZE_STRING );
    if ( !taxonomy_exists( $taxonomy ) )
        return false;

    /*
     * We have made it to here, so we should start getting our stuff togther. 
     * Get the current post object to start of
     */
    $current_post = get_queried_object();

    /*
     * Get the post terms, just the ids
     */
    $terms = wp_get_post_terms( $current_post->ID, $taxonomy, ['fields' => 'ids'] );

    /*
     * Lets only continue if we actually have post terms and if we don't have an WP_Error object. If not, return false
     */
    if ( !$terms || is_wp_error( $terms ) )
        return false;

    /*
     * Set the default query arguments
     */
    $defaults = [
        'post_type' => $current_post->post_type,
        'post__not_in' => [$current_post->ID],
        'tax_query' => [
            [
                'taxonomy' => $taxonomy,
                'terms' => $terms,
                'include_children' => false
            ],
        ],
    ];

    /*
     * Validate and merge the defaults with the user passed arguments
     */
    if ( is_array( $args ) ) {
        $args = wp_parse_args( $args, $defaults );
    } else {
        $args = $defaults;
    }

    /*
     * Now we can query our related posts and return them
     */
    $q = get_posts( $args );

    return $q;
}

现在我们已经有了更好的功能,我们可以在单个帖子页面或内容模板部分中使用它,具体取决于您的确切用例。您可能已经注意到,我们的新函数get_related_posts()有两个参数,第一个接受单个分类值,第二个接受参数数组。这个参数将传递给我们的查询的参数,因此您可以传递任何可在此处WP_Queryget_posts加入的有效参数数组。

示例:

您需要返回一个帖子,因此您可以尝试以下操作:(请注意,请勿在此处使用post type参数或任何分类法类型参数,否则可能会出现意外输出

if ( function_exists( 'get_related_posts' ) ) {
    $related_posts = get_related_posts( 'my_taxonomy_name', ['posts_per_page' => 1] );
    if ( $related_posts ) {
        foreach ( $related_posts as $post ) {
            setup_postdata( $post ); 
            // Use your template tags and html mark up as normal like
            the_title();
            the_content();
            // etc etc
        }
        wp_reset_postdata();
    }
}

修改

从评论看来,你的PHP版本似乎早于5.4,它不支持新的短数组语法([]),因此你得到了可怕的WSOD。为此,您需要将新数组语法更改为旧语法(array())。

您可以尝试以下操作:

function get_related_posts( $taxonomy = '', $args = array() )
{
    /*
     * Before we do anything and waste unnecessary time and resources, first check if we are on a single post page
     * If not, bail early and return false
     */
    if ( !is_single() )
        return false;

    /*
     * Check if we have a valid taxonomy and also if the taxonomy exists to avoid bugs further down.
     * Return false if taxonomy is invalid or does not exist
     */
    if ( !$taxonomy ) 
        return false;

    $taxonomy = filter_var( $taxonomy, FILTER_SANITIZE_STRING );
    if ( !taxonomy_exists( $taxonomy ) )
        return false;

    /*
     * We have made it to here, so we should start getting our stuff togther. 
     * Get the current post object to start of
     */
    $current_post = get_queried_object();

    /*
     * Get the post terms, just the ids
     */
    $terms = wp_get_post_terms( $current_post->ID, $taxonomy, array( 'fields' => 'ids') );

    /*
     * Lets only continue if we actually have post terms and if we don't have an WP_Error object. If not, return false
     */
    if ( !$terms || is_wp_error( $terms ) )
        return false;

    /*
     * Set the default query arguments
     */
    $defaults = array(
        'post_type' => $current_post->post_type,
        'post__not_in' => array( $current_post->ID),
        'tax_query' => array(
            array(
                'taxonomy' => $taxonomy,
                'terms' => $terms,
                'include_children' => false
            ),
        ),
    );

    /*
     * Validate and merge the defaults with the user passed arguments
     */
    if ( is_array( $args ) ) {
        $args = wp_parse_args( $args, $defaults );
    } else {
        $args = $defaults;
    }

    /*
     * Now we can query our related posts and return them
     */
    $q = get_posts( $args );

    return $q;
}

然后使用模板中的代码,转到

if ( function_exists( 'get_related_posts' ) ) {
    $related_posts = get_related_posts( 'my_taxonomy_name', array( 'posts_per_page' => 1) );
    if ( $related_posts ) {
        foreach ( $related_posts as $post ) {
            setup_postdata( $post ); 
            // Use your template tags and html mark up as normal like
            the_title();
            the_content();
            // etc etc
        }
        wp_reset_postdata();
    }
}
相关问题