Search¶

Extending Front End Forms¶

Plugin includes two widgets for filtering the properties. In the sample we will be extending fields for “Filter” widget. So we need to create templates/widgets/filter-fields/custom.php in our child theme.

<?php if ( empty( $instance['hide_custom'] ) ) : ?>
    <div class="form-group">
        <?php if ( $input_titles == 'labels' ) : ?>
            <label for="<?php echo esc_attr( $args['widget_id'] ); ?>_custom"><?php echo __( 'Custom', 'realia' ); ?></label>
        <?php endif; ?>

        <input type="text" name="filter-custom" class="form-control"
               <?php if( $input_titles == 'placeholders' ) : ?>placeholder="<?php echo __( 'Custom', 'realia' ); ?>"<?php endif; ?>
               value="<?php echo ! empty( $_GET['filter-custom']) ? $_GET['filter-custom'] : ''; ?>"
               id="<?php echo esc_attr( $args['widget_id'] ); ?>_custom>
    </div><!-- /.form-group -->
<?php endif; ?>

After creating field teplate we need to tell widgets to include it. We can do that by applying following filters

add_filter( 'realia_filter_fields', 'custom_function_fields' );

function custom_function_fields( $fields ) {
    // Key must be same as field template name without .php
    $fields['custom'] = 'Custom Title';
    return $fields;
}
add_filter( 'realia_filter_field_names', 'custom_function_field_names' );

function custom_function_field_names( $fields ) {
    $fields[] = 'filter-custom';
    return $fields;
}

Adding Filter Logic¶

For property filtering is used pre_get_posts action which has $query argument. In custom filter function we will make sure that we are going to extend only query for properties and then we add custom query attributes.

add_action( 'pre_get_posts', 'custom_filter' );

function custom_filter( $query ) {
    $suppress_filters = ! empty( $query->query_vars['suppress_filters'] )
        ? $query->query_vars['suppress_filters'] : '';

    if ( ! is_post_type_archive( 'property' ) ||
         ! $query->is_main_query() || is_admin() ||
         $query->query_vars['post_type'] != 'property' ||
         $suppress_filters ) {
        return;
    }

    if ( ! empty( $_GET['filter-custom'] ) ) {
        $meta[] = array(
            'key'       => REALIA_PROPERTY_PREFIX . 'custom',
            'value'     => $_GET['filter-custom'],
            'compare'   => '=='
        );
    }

    $query->set( 'meta_query', $meta );

    return $query;
}

NOTE:: All query attributes are stored in Realia_Filter::filter_query( $query ) function which is already used for REST API filtering.

Table Of Contents

  • Search
    • Extending Front End Forms
    • Adding Filter Logic

Related Topics

  • Documentation overview
    • Previous: Fields
    • Next: Post Types

This Page

  • Show Source

Quick search

Enter search terms or a module, class or function name.