phpwordpressserializationmetadatameta-query

How to use WordPress metaquery when meta_value is saved as serialized key/value


I am Working on WordPress project , which required me to manipulate the existing plugin's WP_Query

On the front-end side , I have 3 Dropdown , in which 2 of them I have customizes with tax_query and using plugin's filter , I don't know how to customize with meta_query ( check screenshot )

enter image description here

<?php 
add_filter( 'learndash_ld_course_list_query_args', 'filter__learndash_ld_course_list_query_args', 10, 2 );
function filter__learndash_ld_course_list_query_args( $filter, $atts ) {

    if ( ! isset( $filter['tax_query'] ) ) {
        $filter['tax_query'] = array();
    }
    if ( ! isset( $filter['meta_query'] ) ) {
        $filter['meta_query'] = array();
    }
    if ( isset( $_GET['catid'] ) && ! empty( $_GET['catid'] ) ) { 
        $filter['tax_query'][] = array(
            'taxonomy' => 'ld_course_category',
            'field'    => 'term_id',
            'terms'    => intval( $_GET['catid'] ),
        );
    }
    if ( isset( $_GET['taxid'] ) && ! empty( $_GET['taxid'] ) ) { 
        $filter['tax_query'][] = array(
            'taxonomy' => $atts['course_taxonomy'],
            'field'    => 'term_id',
            'terms'    => intval( $_GET['taxid'] ),
        );
    }
    if ( isset( $_GET['priceid'] ) && ! empty( $_GET['priceid'] ) ) { 
        $filter['meta_query'][] = array(
            'key'       => '_sfwd-courses',
            'value'     => '',
            'compare'   => 'LIKE',
        );
    }
    if ( count( $filter['tax_query'] ) > 1 ) {
        $filter['tax_query']['relation'] = 'AND';
    }

    //echo "<pre>"; print_r($filter);
    return $filter;
}

But I am stuck in meta_query , because it stores data in serialize array ( Check screenshots )

enter image description here

What should I write here to compare 'value' => '', ??


Solution

  • You’re gonna have to use the LIKE operator and %…% around the value (actually, with WP_Query you don’t need to insert that yourself, with the operator set to LIKE, WP will automatically put the %…% around the value itself), to find a partial match. As for what to match - just %free% or %"free"% might not be a good idea, because then you would get false positives, if any of the other properties in that serialized array could ever contain free as well.

    So you should probably include the key here as well - but then you will have to include the part in between as well, and that means the s:4 part needs to be made dynamic as well. What the number needs to be, can easily be determined by strlen($_GET['priceid'])