mustardBees / cmb-field-select2

Select2 field type for Custom Metaboxes and Fields for WordPress
93 stars 46 forks source link

Get all the custom content by the value of cmb-field-select2 #55

Closed rpiscopo-easyweb closed 1 year ago

rpiscopo-easyweb commented 1 year ago

Hello everyone, I'm using a theme for a project that has two custom types, "person" and "assignment". Each person can have none, one or more assignments (selected by cmb-field-select2). Assignement is a custom content type that has "type" as custom field. I need to create a template where I show all the people that have the same type of assignment.

Is there a way to know the type of assignment using cmb-field-select2?

Thanks for your help!

mustardBees commented 1 year ago

Hi @rpiscopo-easyweb,

Based on this approach, you could try something like:

$assignment = 'your_assignment_value';

$args = array(
    'post_type'  => 'person',
    'meta_query' => array(
        array(
            'key'     => '_cmb_assignments',
            'value'   => '"' . $assignment . '"',
            'compare' => 'LIKE',
        ),
    ),
);

$people = new WP_Query( $args );

When working with the multiselect field, the values are stored in the database as a serialized array. For example:

a:6:{i:0;s:2:"32";i:1;s:2:"30";i:2;s:2:"34";i:3;s:2:"33";i:4;s:2:"35";i:5;s:2:"38";}

The double quotes around the $assignment variable within the query ensure that we are searching for an exact match, including the quotes.

rpiscopo-easyweb commented 1 year ago

Thank you so much, it works!