繁体   English   中英

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

[英]'post__not_in' doesn't work for related posts by taxonomy (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)不起作用。

如前所述,您的代码完全错误,无法正常工作。 我将不讨论有关您的代码的详细信息,因为我只会废弃您的代码并从头开始

这是我最近在WPSE上发表的帖子的副本。 这基本上是一个复制粘贴解决方案,这里唯一的问题是帖子不是随机排列的,因此您需要在查询参数中添加随机顺序。

这是帖子:

我只是简单地废弃上面的函数,因为代码中存在多个错误,而且效率也不高。 实际上,我认为它确实对您有用。

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

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

  • 使用wp_get_post_term()获取当前正在查看的帖子的条款。 我们将fields参数设置为仅获取术语ID。 返回的术语ID数组可在我们的tax_query

  • 添加一些验证以验证用户输入并清理输入

让我们将其全部放入代码中( 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 WP_Query任何有效参数数组。

例:

您需要返回一个帖子,因此可以尝试以下操作:( 请注意,此处不要使用post类型参数或任何分类类型参数,您可能会得到意外的输出

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();
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM