Search code examples
phpwordpressadvanced-custom-fields

Get ACF post meta value in query


I would like to add the value of an ACF custom field into a plugin in order to narrow the query with it.

Here the function I've create in order to retrieve the value :

function vayvo_elements_post_difficulty(){
$post_meta = the_field( array( 
    'meta_key'=> 'difficulty',
    'hide_empty' => false,
));

if ( ! empty( $post_meta ) && ! is_wp_error( $post_meta ) ){
    foreach ( $post_meta as $meta_value ) {
        $options[ $meta_value->string ] = $post->meta_value;
    }
    return $options;
}

And here the code to display it :

enter       $this->add_control(
        'progression_post_difficulty',
        [
            'label' => esc_html__( 'Narrow by difficulty', 'progression-elements-vayvo' ),
            'description' => esc_html__( 'Choose a difficulty to display posts', 'progression-elements-vayvo' ),
            'label_block' => true,
            'multiple' => true,
            'type' => Controls_Manager::SELECT2,
            'options' => vayvo_elements_post_difficulty(),
        ]
    );

Unfortunetly, I can see the new args into the query but is totally empty even if I have posts with this meta_key fielded.

Someone have an idea?

best regards, Clément


Solution

  • I'm not entirely sure if I follow. But from my understanding, you are using the function the_field incorrectly, see the documentation here.

    You should be able to simply get the field value from get_field and disabling value formatting.

    $this->add_control( 'progression_post_difficulty', [
        'label' => esc_html__( 'Narrow by difficulty', 'progression-elements-vayvo' ),
        'description' => esc_html__( 'Choose a difficulty to display posts', 'progression-elements-vayvo' ),
        'label_block' => true,
        'multiple' => true,
        'type' => Controls_Manager::SELECT2,
        'options' => get_field( 'difficulty', false, false ) ?: [],
    ] );