Skip to content

Instantly share code, notes, and snippets.

@nikitasinelnikov
Last active March 25, 2024 22:46
Show Gist options
  • Save nikitasinelnikov/233037df9e68c626a19ee5cdccac7c13 to your computer and use it in GitHub Desktop.
Save nikitasinelnikov/233037df9e68c626a19ee5cdccac7c13 to your computer and use it in GitHub Desktop.
Custom gender field and filter in member directory for it
function custom_um_query_args_c2n_gender__filter_meta( $skip, $query, $field, $value, $filter_type, $is_default ) {
if ( ! is_array( $value ) ) {
$value = array( $value );
}
// $join_alias is pre-escaped.
$query->joins[] = "LEFT JOIN {$wpdb->prefix}um_metadata {$join_alias} ON {$join_alias}.user_id = u.ID";
$values_array = array();
foreach ( $value as $single_val ) {
$single_val = trim( stripslashes( $single_val ) );
// phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- $join_alias and $compare variables are pre-escaped.
$values_array[] = $wpdb->prepare( "{$join_alias}.um_value LIKE %s", '%"' . $wpdb->esc_like( $single_val ) . '"%' );
$values_array[] = $wpdb->prepare( "{$join_alias}.um_value = %s", $single_val );
// phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- $join_alias is pre-escaped.
}
$values = implode( ' OR ', $values_array );
// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- $join_alias and $values variables are pre-escaped or $wpdb->prepare.
$query->where_clauses[] = $wpdb->prepare( "( {$join_alias}.um_key = %s AND ( {$values} ) )", $field );
if ( ! $is_default ) {
$query->custom_filters_in_query[ $field ] = $value;
}
return true;
}
add_filter( 'um_query_args_c2n_gender__filter_meta', 'custom_um_query_args_c2n_gender__filter_meta', 10, 6 );
function custom_um_query_args_c2n_gender__filter( $query, $field, $value, $filter_type ) {
if ( ! is_array( $value ) ) {
$value = array( $value );
}
if ( is_array( $value ) ) {
$field_query = array( 'relation' => 'OR' );
foreach ( $value as $single_val ) {
$single_val = trim( stripslashes( $single_val ) );
$arr_meta_query = array(
array(
'key' => $field,
'value' => $single_val,
'compare' => '=',
),
array(
'key' => $field,
'value' => '"' . $single_val . '"',
'compare' => 'LIKE',
),
);
$field_query = array_merge( $field_query, $arr_meta_query );
}
}
if ( ! empty( $field_query ) ) {
UM()->member_directory()->query_args['meta_query'] = array_merge( UM()->member_directory()->query_args['meta_query'], array( $field_query ) );
UM()->member_directory()->custom_filters_in_query[ $field ] = $value;
}
return true;
}
add_filter( 'um_query_args_c2n_gender__filter', 'custom_um_query_args_c2n_gender__filter', 10, 4 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment