简体   繁体   中英

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.

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. There must be a problem with that variable.

Any ideas?

Thank you so much

the_field() echoes the field value. You should use get_field() instead (which returns, not echoes the field value):

$redirect_value = get_field('desktop_cat');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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