Skip to content

Commit

Permalink
Add new attributes and controls to limit the search result based on p…
Browse files Browse the repository at this point in the history
…ost types and categories
  • Loading branch information
amitraj2203 committed Jun 10, 2024
1 parent e58e4e5 commit 1b8eb4e
Show file tree
Hide file tree
Showing 4 changed files with 101 additions and 3 deletions.
2 changes: 1 addition & 1 deletion docs/reference-guides/core-blocks.md
Original file line number Diff line number Diff line change
Expand Up @@ -811,7 +811,7 @@ Help visitors find your content. ([Source](https://github.com/WordPress/gutenber
- **Name:** core/search
- **Category:** widgets
- **Supports:** align (center, left, right), color (background, gradients, text), interactivity, typography (fontSize, lineHeight), ~~html~~
- **Attributes:** buttonPosition, buttonText, buttonUseIcon, isSearchFieldHidden, label, placeholder, query, showLabel, width, widthUnit
- **Attributes:** buttonPosition, buttonText, buttonUseIcon, categories, isSearchFieldHidden, label, limitResults, placeholder, postType, query, showLabel, width, widthUnit

## Separator

Expand Down
12 changes: 12 additions & 0 deletions packages/block-library/src/search/block.json
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,18 @@
"isSearchFieldHidden": {
"type": "boolean",
"default": false
},
"limitResults": {
"type": "boolean",
"default": false
},
"postType": {
"type": "string",
"default": "post"
},
"categories": {
"type": "object",
"default": {}
}
},
"supports": {
Expand Down
57 changes: 57 additions & 0 deletions packages/block-library/src/search/edit.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@ import {
BaseControl,
__experimentalUseCustomUnits as useCustomUnits,
__experimentalUnitControl as UnitControl,
SelectControl,
ToggleControl,
} from '@wordpress/components';
import { useInstanceId } from '@wordpress/compose';
import { Icon, search } from '@wordpress/icons';
Expand All @@ -53,7 +55,10 @@ import {
PX_WIDTH_DEFAULT,
MIN_WIDTH,
isPercentageUnit,
usePostTypes,
useTaxonomies,
} from './utils.js';
import { TaxonomyControls } from './taxonomy-controls.js';

// Used to calculate border radius adjustment to avoid "fat" corners when
// button is placed inside wrapper.
Expand All @@ -79,8 +84,27 @@ export default function SearchEdit( {
buttonUseIcon,
isSearchFieldHidden,
style,
postType,
limitResults,
categories,
} = attributes;

const { postTypesTaxonomiesMap, postTypesSelectOptions } = usePostTypes();
const taxonomies = useTaxonomies( postType );
const onPostTypeChange = ( newValue ) => {
// We need to dynamically update the `taxQuery` property,
// by removing any not supported taxonomy from the query.
const supportedTaxonomies = postTypesTaxonomiesMap[ newValue ];

// Update the categories attribute
const updatedCategories = {};
supportedTaxonomies.forEach( ( taxonomy ) => {
updatedCategories[ taxonomy ] = [];
} );

setAttributes( { categories: updatedCategories, postType: newValue } );
};

const wasJustInsertedIntoNavigationBlock = useSelect(
( select ) => {
const { getBlockParentsByBlockName, wasBlockJustInserted } =
Expand Down Expand Up @@ -307,6 +331,10 @@ export default function SearchEdit( {
);
};

const handleTaxonomiesChange = ( newCategories ) => {
setAttributes( { categories: newCategories } );
};

const renderButton = () => {
// If the button is inside the wrapper, the wrapper gets the border color styles/classes, not the button.
const buttonClasses = clsx(
Expand Down Expand Up @@ -474,6 +502,35 @@ export default function SearchEdit( {
} ) }
</ButtonGroup>
</BaseControl>
<ToggleControl
__nextHasNoMarginBottom
label={ __( 'Limit Search Results' ) }
checked={ limitResults }
onChange={ () =>
setAttributes( {
limitResults: ! limitResults,
} )
}
/>
{ limitResults && (
<SelectControl
__nextHasNoMarginBottom
options={ postTypesSelectOptions }
value={ postType }
label={ __( 'Post type' ) }
onChange={ onPostTypeChange }
help={ __(
'WordPress contains different types of content and they are divided into collections called “Post types”. By default there are a few different ones such as blog posts and pages, but plugins could add more.'
) }
/>
) }
{ limitResults && taxonomies?.length && (
<TaxonomyControls
categories={ categories }
onChange={ handleTaxonomiesChange }
postType={ postType }
/>
) }
</PanelBody>
</InspectorControls>
</>
Expand Down
33 changes: 31 additions & 2 deletions packages/block-library/src/search/index.php
Original file line number Diff line number Diff line change
Expand Up @@ -196,12 +196,41 @@ function render_block_core_search( $attributes ) {
';
}

$post_type_input = '';
$taxonomy_inputs = '';

if ( $attributes['limitResults'] ) {
$post_type = ! empty( $attributes['postType'] ) ? $attributes['postType'] : '';
$taxonomies = ! empty( $attributes['categories'] ) ? $attributes['categories'] : array();

foreach ( $taxonomies as $taxonomy => $terms ) {
if ( ! empty( $terms ) ) {
$taxonomy_terms = array_map(
function ( $term_id ) use ( $taxonomy ) {
$term = get_term_by( 'id', $term_id, $taxonomy );
return $term ? $term->slug : '';
},
$terms
);

$input_name = ( 'category' === $taxonomy ) ? 'category_name' : ( ( 'post_tag' === $taxonomy ) ? 'tag' : $taxonomy );
$taxonomy_input = sprintf( '<input type="hidden" name="%s" value="%s" />', esc_attr( $input_name ), esc_attr( implode( ',', $taxonomy_terms ) ) );
$taxonomy_inputs .= $taxonomy_input;
}
}

if ( ! empty( $post_type ) ) {
$post_type_input = sprintf( '<input type="hidden" name="post_type" value="%s" />', esc_attr( $post_type ) );
}
}

return sprintf(
'<form role="search" method="get" action="%1s" %2s %3s>%4s</form>',
'<form role="search" method="get" action="%1s" %2s %3s>%4s %5$s</form>',
esc_url( home_url( '/' ) ),
$wrapper_attributes,
$form_directives,
$label . $field_markup
$label . $field_markup,
$post_type_input . $taxonomy_inputs
);
}

Expand Down

0 comments on commit 1b8eb4e

Please sign in to comment.