简体   繁体   English

WP_Query中的自定义字段值

[英]Custom field value inside WP_Query

I want a WP_Query, that displays all the posts, that have the same custom field value as the display post. 我想要一个WP_Query,它显示所有与显示帖子具有相同自定义字段值的帖子。

This is my Code: 这是我的代码:

    function show_other_posts() {
        //Get the current custom field value
        if( get_field('desktop_cat') ){
            $redirect_value = the_field('desktop_cat');

            //Echo the current custom field value for debugging
            echo $redirect_value;

            //Query Posts with same value
            $redirect_args = array(
                    'posts_per_page' => -1,
                    'post_type'     => 'post',
                    'meta_query' => array(
                        array(
                          'key' => 'desktop_cat',
                          'value' => $redirect_value,
                          'compare' => '='
                        )
                    )
            );

            //Display the Post Titles
            $the_query = new WP_Query ( $redirect_args );
            if( $the_query->have_posts() ): while( $the_query->have_posts() ) : $the_query->the_post();
            the_title();
            endwhile;endif;
            wp_reset_query();
        };
    };

The Problem must be 'value' => $redirect_value, because when i enter a value manually it works well. 问题必须是'value' => $redirect_value,因为当我手动输入一个值时,它会很好地工作。 There must be a problem with that variable. 该变量一定有问题。

Any ideas? 有任何想法吗?

Thank you so much 非常感谢

the_field() echoes the field value. the_field()回显字段值。 You should use get_field() instead (which returns, not echoes the field value): 您应该改用get_field() (它返回而不是回显字段值):

$redirect_value = get_field('desktop_cat');

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

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