========================
CODE SNIPPETS
========================
TITLE: Conditionally Render Fill for Specific Post Types
DESCRIPTION: An advanced example demonstrating how to render a SlotFill component only for specific post types. It combines the 'viewable' check with an explicit allow list of post type slugs, ensuring the fill appears only on designated edit screens like 'page'.
SOURCE: https://github.com/wordpress/gutenberg/blob/trunk/docs/reference-guides/slotfills/README.md#_snippet_2
LANGUAGE: js
CODE:
```
/**
* WordPress dependencies
*/
import { registerPlugin } from '@wordpress/plugins';
import {
PluginDocumentSettingPanel,
store as editorStore,
} from '@wordpress/editor';
import { store as coreStore } from '@wordpress/core-data';
import { useSelect } from '@wordpress/data';
import { __, sprintf } from '@wordpress/i18n';
/**
* The component to be rendered as part of the plugin.
*/
const RestrictPostTypes = () => {
// Retrieve information about the current post type.
const { isViewable, postTypeName } = useSelect( ( select ) => {
const postType = select( editorStore ).getCurrentPostType();
const postTypeObject = select( coreStore ).getPostType( postType );
return {
isViewable: postTypeObject?.viewable,
postTypeName: postType,
};
}, [] );
// The list of post types that are allowed to render the plugin.
const allowedPostTypes = [ 'page' ];
// If the post type is not viewable or not in the allowed list, do not render the plugin.
if ( ! isViewable || ! allowedPostTypes.includes( postTypeName ) ) {
return null;
}
return (
{ sprintf(
__(
'Only appears on Post Types that are in the allowed list. %s'
),
allowedPostTypes.join( ', ' )
) }
);
};
registerPlugin( 'example-restrict-post-types', { render: RestrictPostTypes } );
```
----------------------------------------
TITLE: Define PluginPostStatusInfo SlotFill with createSlotFill
DESCRIPTION: Demonstrates how to create a SlotFill component named `PluginPostStatusInfo` using the `createSlotFill` utility from `@wordpress/components`. This establishes an extensibility point for the Summary panel in the WordPress editor.
SOURCE: https://github.com/wordpress/gutenberg/blob/trunk/docs/reference-guides/slotfills/README.md#_snippet_5
LANGUAGE: javascript
CODE:
```
/**
* Defines as extensibility slot for the Summary panel.
*/
/**
* WordPress dependencies
*/
import { createSlotFill, PanelRow } from '@wordpress/components';
export const { Fill, Slot } = createSlotFill( 'PluginPostStatusInfo' );
const PluginPostStatusInfo = ( { children, className } ) => (
{ children }
);
PluginPostStatusInfo.Slot = Slot;
export default PluginPostStatusInfo;
```
----------------------------------------
TITLE: Conditionally Render Fill in Post Editor Only
DESCRIPTION: Shows how to restrict a SlotFill component's rendering exclusively to the Post Editor screen. This is achieved by checking the 'viewable' property of the current post type using the useSelect hook from '@wordpress/data'.
SOURCE: https://github.com/wordpress/gutenberg/blob/trunk/docs/reference-guides/slotfills/README.md#_snippet_1
LANGUAGE: js
CODE:
```
/**
* WordPress dependencies
*/
import { registerPlugin } from '@wordpress/plugins';
import {
PluginDocumentSettingPanel,
store as editorStore,
} from '@wordpress/editor';
import { store as coreStore } from '@wordpress/core-data';
import { useSelect } from '@wordpress/data';
import { __ } from '@wordpress/i18n';
/**
* The component to be rendered as part of the plugin.
*/
const EditPostDocumentSettingPanel = () => {
// Retrieve information about the current post type.
const isViewable = useSelect( ( select ) => {
const postTypeName = select( editorStore ).getCurrentPostType();
const postTypeObject = select( coreStore ).getPostType( postTypeName );
return postTypeObject?.viewable;
}, [] );
// If the post type is not viewable, then do not render my the fill.
if ( ! isViewable ) {
return null;
}
return (
{ __( 'Only appears in the Edit Post screen' ) }
);
};
registerPlugin( 'example-post-edit-only', { render: EditPostDocumentSettingPanel } );
```
----------------------------------------
TITLE: Register Plugin for Specific Site Editor Screens
DESCRIPTION: This example extends the previous one by adding an allow list for specific Site Editor screens. It checks if the current post type is in the `allowedSiteEditorScreens` array before rendering the plugin panel. Dependencies are similar to the first snippet.
SOURCE: https://github.com/wordpress/gutenberg/blob/trunk/docs/reference-guides/slotfills/README.md#_snippet_4
LANGUAGE: js
CODE:
```
/**
* WordPress dependencies
*/
import { registerPlugin } from '@wordpress/plugins';
import {
PluginDocumentSettingPanel,
store as editorStore,
} from '@wordpress/editor';
import { store as coreStore } from '@wordpress/core-data';
import { useSelect } from '@wordpress/data';
import { __, sprintf } from '@wordpress/i18n';
/**
* The component to be rendered as part of the plugin.
*/
const SiteEditorDocumentSettingPanel = () => {
// Allowed areas in the Site Editor.
const allowedSiteEditorScreens = [
'wp_template', // Templates
'wp_block', // Patterns
'wp_template_part', // Template Parts
];
const { isViewable, postType } = useSelect( ( select ) => {
const postTypeName = select( editorStore ).getCurrentPostType();
const postTypeObject = select( coreStore ).getPostType( postTypeName );
return {
// A viewable post type is one than can be viewed in the WordPress admin. Internal ones are not set to viewable.
isViewable: postTypeObject?.viewable,
postType: postTypeName,
};
}, [] );
// If the post type is viewable, do not render my plugin.
if ( isViewable || ! allowedSiteEditorScreens.includes( postType ) ) {
return null;
}
return (
{ sprintf(
__(
'Only appears on Editor Screens that are in the allowed list. %s'
),
allowedSiteEditorScreens.join( ', ' )
) }
);
};
registerPlugin( 'example-site-editor-only', {
render: SiteEditorDocumentSettingPanel,
} );
```
----------------------------------------
TITLE: Register Plugin with PluginPostStatusInfo SlotFill
DESCRIPTION: Demonstrates the basic usage of SlotFills by registering a plugin that injects content into the PluginPostStatusInfo slot. It requires importing registerPlugin from '@wordpress/plugins' and the target SlotFill component from '@wordpress/editor'.
SOURCE: https://github.com/wordpress/gutenberg/blob/trunk/docs/reference-guides/slotfills/README.md#_snippet_0
LANGUAGE: js
CODE:
```
import { registerPlugin } from '@wordpress/plugins';
import { PluginPostStatusInfo } from '@wordpress/editor';
const PluginPostStatusInfoTest = () => (
Post Status Info SlotFill
);
registerPlugin( 'post-status-info-test', { render: PluginPostStatusInfoTest } );
```
----------------------------------------
TITLE: Use PluginPostStatusInfo Slot in PostSummary Component
DESCRIPTION: Illustrates the usage of the `PluginPostStatusInfo.Slot` within the `PostSummary` component. It shows how to render child components and dynamically include fills provided by other plugins or extensions.
SOURCE: https://github.com/wordpress/gutenberg/blob/trunk/docs/reference-guides/slotfills/README.md#_snippet_6
LANGUAGE: javascript
CODE:
```
export default function PostSummary( { onActionPerformed } ) {
const { isRemovedPostStatusPanel } = useSelect( ( select ) => {
// We use isEditorPanelRemoved to hide the panel if it was programmatically removed. We do
// not use isEditorPanelEnabled since this panel should not be disabled through the UI.
const { isEditorPanelRemoved } = select( editorStore );
return {
isRemovedPostStatusPanel: isEditorPanelRemoved( PANEL_NAME ),
};
}, [] );
return (
{ ( fills ) => (
<>
{ ! isRemovedPostStatusPanel && (
{ fills }
) }
>
) }
);
}
```
----------------------------------------
TITLE: Register Plugin for Site Editor Restriction
DESCRIPTION: Registers a WordPress plugin to restrict content visibility within the Site Editor. It leverages `useSelect` to determine if the current post type is viewable, hiding the panel if it is. Dependencies include `@wordpress/plugins`, `@wordpress/editor`, and `@wordpress/core-data`.
SOURCE: https://github.com/wordpress/gutenberg/blob/trunk/docs/reference-guides/slotfills/README.md#_snippet_3
LANGUAGE: js
CODE:
```
/**
* WordPress dependencies
*/
import { registerPlugin } from '@wordpress/plugins';
import {
PluginDocumentSettingPanel,
store as editorStore,
} from '@wordpress/editor';
import { store as coreStore } from '@wordpress/core-data';
import { useSelect } from '@wordpress/data';
import { __ } from '@wordpress/i18n';
/**
* The component to be rendered as part of the plugin.
*/
const SiteEditorDocumentSettingPanel = () => {
// Retrieve information about the current post type.
const isViewable = useSelect( ( select ) => {
const postTypeName = select( editorStore ).getCurrentPostType();
const postTypeObject = select( coreStore ).getPostType( postTypeName );
// A viewable post type is one than can be viewed in the WordPress admin. Internal ones are not set to viewable.
return postTypeObject?.viewable;
}, [] );
// If the post type is viewable, do not render my fill
if ( isViewable ) {
return null;
}
return (
{ __( 'Only appears in the Site Editor' ) }
);
};
registerPlugin( 'example-site-editor', {
render: SiteEditorDocumentSettingPanel,
} );
```
----------------------------------------
TITLE: Using createSlotFill Helper
DESCRIPTION: Illustrates the use of the createSlotFill helper function to simplify the creation of paired Slot and Fill components, making it easier to manage component extensibility.
SOURCE: https://github.com/wordpress/gutenberg/blob/trunk/packages/components/src/slot-fill/README.md#_snippet_1
LANGUAGE: javascript
CODE:
```
const { Fill, Slot } = createSlotFill( 'Toolbar' );
const ToolbarItem = () => My item;
const Toolbar = () => (
);
```
----------------------------------------
TITLE: Basic Slot/Fill Usage with Custom Panel
DESCRIPTION: Demonstrates setting up SlotFillProvider and using Slot and Fill components to render UI in different parts of the application. Includes custom Panel components.
SOURCE: https://github.com/wordpress/gutenberg/blob/trunk/packages/components/src/slot-fill/README.md#_snippet_0
LANGUAGE: jsx
CODE:
```
import {
SlotFillProvider,
Slot,
Fill,
Panel,
PanelBody,
} from '@wordpress/components';
const MySlotFillProvider = () => {
const MyPanelSlot = () => (
);
MyPanelSlot.Content = () => Panel body;
return (
);
};
```
----------------------------------------
TITLE: SlotFillProvider Component API
DESCRIPTION: The root component required to enable the Slot/Fill pattern across the application.
SOURCE: https://github.com/wordpress/gutenberg/blob/trunk/packages/components/src/slot-fill/README.md#_snippet_4
LANGUAGE: APIDOC
CODE:
```
SlotFillProvider
children: ReactNode
Any React nodes that will utilize Slot and Fill components.
This component does not accept any other specific props besides children.
```
----------------------------------------
TITLE: Slot Component API
DESCRIPTION: Details the Slot component's props and behavior, including virtual bubbling, custom wrapper elements, and conditional rendering via children functions.
SOURCE: https://github.com/wordpress/gutenberg/blob/trunk/packages/components/src/slot-fill/README.md#_snippet_2
LANGUAGE: APIDOC
CODE:
```
Slot
name: string | symbol
The unique name identifying the slot.
bubblesVirtually: boolean (optional, default: false)
If true, uses React portals for rendering fills, affecting event bubbling and context propagation.
- When true: Events bubble to React parents, context is preserved from Fill's hierarchy, renders a wrapper DOM element.
- When false: Events bubble to DOM parents, context is inherited from Slot's hierarchy, renders fills directly within a Fragment.
as: string (optional, default: 'div')
When bubblesVirtually is true, specifies the DOM element type for the wrapper.
className: string (optional)
When bubblesVirtually is true, applies a CSS class to the wrapper element.
style: object (optional)
When bubblesVirtually is true, applies inline styles to the wrapper element.
fillProps: object (optional)
Props passed from the Slot to its Fills. Can be accessed by Fills via their children function.
children: function(fills: Array) => ReactNode (optional)
A render prop function that receives an array of fills. Allows custom rendering logic, such as placeholders or conditional wrappers.
Example with children prop:
Slot name="Toolbar" {
( fills ) => {
return isMobile && fills.length > 3 ? (
{ fills }
) : (
fills
);
}
}
Example with fillProps:
Slot name="Toolbar" fillProps={ { hideToolbar } } />
```
----------------------------------------
TITLE: Fill Component API
DESCRIPTION: Details the Fill component's props and how it renders content into a corresponding Slot.
SOURCE: https://github.com/wordpress/gutenberg/blob/trunk/packages/components/src/slot-fill/README.md#_snippet_3
LANGUAGE: APIDOC
CODE:
```
Fill
name: string | symbol
The unique name identifying the slot this fill belongs to.
children: ReactNode | function(fillProps: object) => ReactNode (optional)
The content to be rendered in the Slot. If a function, it receives props passed from the Slot's fillProps.
Example with children function:
Fill {
( { hideToolbar } ) => {
;
}
}
```
----------------------------------------
TITLE: ActionItem.Slot Component Props - React
DESCRIPTION: Defines the properties for the ActionItem.Slot component, which acts as a 'slot' in a slot & fill pattern. It manages the container for multiple possible actions.
SOURCE: https://github.com/wordpress/gutenberg/blob/trunk/packages/interface/src/components/action-item/README.md#_snippet_1
LANGUAGE: APIDOC
CODE:
```
ActionItem.Slot:
Props:
name: The name of the slot and fill pair passed to the Slot component.
Type: String
Required: Yes
bubblesVirtually: Property used to change the event bubbling behavior, passed to the Slot component.
Type: boolean
Required: no
as: The component used as the container of the fills. Defaults to the MenuGroup component.
Type: Component
Required: no
Default: MenuGroup
```
----------------------------------------
TITLE: PinnedItems.Slot Component API
DESCRIPTION: Defines the PinnedItems.Slot component, which serves as a rendering point for pinned items managed by the PinnedItems component.
SOURCE: https://github.com/wordpress/gutenberg/blob/trunk/packages/interface/src/components/pinned-items/README.md#_snippet_1
LANGUAGE: APIDOC
CODE:
```
PinnedItems.Slot:
description: A slot that renders the pinned items.
props:
scope:
type: String
description: The scope of the pinned items area (e.g., "core", "myplugin/custom-screen-a").
required: Yes
```
----------------------------------------
TITLE: Control Popover Rendering with Popover.Slot
DESCRIPTION: Illustrates using Popover.Slot with SlotFillProvider to control where Popover components render in the DOM. This is useful for precise placement by rendering popovers to a single location.
SOURCE: https://github.com/wordpress/gutenberg/blob/trunk/packages/components/README.md#_snippet_2
LANGUAGE: jsx
CODE:
```
/**
* External dependencies
*/
import { Popover, SlotFillProvider } from '@wordpress/components';
/**
* Internal dependencies
*/
import { MyComponentWithPopover } from './my-component';
const Example = () => {
;
};
```
----------------------------------------
TITLE: isValueSpacingPreset
DESCRIPTION: Checks if a given value is a spacing preset. Returns true if the value is a string in the format 'var:preset|spacing|'.
SOURCE: https://github.com/wordpress/gutenberg/blob/trunk/packages/block-editor/README.md#_snippet_29
LANGUAGE: APIDOC
CODE:
```
isValueSpacingPreset( value: string )
Parameters:
- value: string: Value to check
Returns:
boolean: Return true if value is string in format var:preset|spacing|.
```
----------------------------------------
TITLE: Update ActionItem Slot 'as' Prop Usage
DESCRIPTION: Passing a tuple of components with the `as` prop to the `ActionItem.Slot` component is no longer supported. Pass a single component instead.
SOURCE: https://github.com/wordpress/gutenberg/blob/trunk/docs/contributors/code/deprecations.md#_snippet_2
LANGUAGE: JavaScript
CODE:
```
```diff
```
```
----------------------------------------
TITLE: getSpacingPresetCssVar
DESCRIPTION: Converts a spacing preset into a custom CSS variable string. It takes a value string as input.
SOURCE: https://github.com/wordpress/gutenberg/blob/trunk/packages/block-editor/README.md#_snippet_21
LANGUAGE: APIDOC
CODE:
```
getSpacingPresetCssVar( value: string )
Parameters:
- value: string: Value to convert.
Returns:
string | undefined: CSS var string for given spacing preset value.
```
----------------------------------------
TITLE: getCustomValueFromPreset
DESCRIPTION: Converts a spacing preset into a custom value. It takes a value string and an array of spacing preset objects as input. Returns a string mapping the spacing preset to its equivalent custom value.
SOURCE: https://github.com/wordpress/gutenberg/blob/trunk/packages/block-editor/README.md#_snippet_14
LANGUAGE: APIDOC
CODE:
```
getCustomValueFromPreset( value: string, spacingSizes: Array )
Parameters:
- value: string: Value to convert
- spacingSizes: Array: Array of the current spacing preset objects
Returns:
string: Mapping of the spacing preset to its equivalent custom value.
```
----------------------------------------
TITLE: Render Block with Scoped Component Approach
DESCRIPTION: Shows how to render a block using the scoped component approach, which requires `SlotFillProvider` and `BottomSheetSettings`. The `isVisible` prop is used to ensure the bottom sheet is displayed.
SOURCE: https://github.com/wordpress/gutenberg/blob/trunk/docs/contributors/code/react-native/integration-test-guide.md#_snippet_12
LANGUAGE: js
CODE:
```
```
----------------------------------------
TITLE: ComplementaryArea.Slot Component Props
DESCRIPTION: Defines the properties for the ComplementaryArea.Slot component, which is responsible for rendering the currently active ComplementaryArea. It relies on the scope to determine which area to display.
SOURCE: https://github.com/wordpress/gutenberg/blob/trunk/packages/interface/src/components/complementary-area/README.md#_snippet_1
LANGUAGE: APIDOC
CODE:
```
ComplementaryArea.Slot:
Props:
scope: String
- The scope of the complementary area to render (e.g., "core", "myplugin/custom-screen-a").
- Required: Yes
```
----------------------------------------
TITLE: Register PluginPrePublishPanel Item (JavaScript)
DESCRIPTION: This example demonstrates how to register a custom plugin that injects content into the pre-publish panel. It uses the `registerPlugin` function from `@wordpress/plugins` and the `PluginPrePublishPanel` component from `@wordpress/editor`. The code defines a React component to render the content and registers it under a unique plugin slug.
SOURCE: https://github.com/wordpress/gutenberg/blob/trunk/docs/reference-guides/slotfills/plugin-pre-publish-panel.md#_snippet_0
LANGUAGE: javascript
CODE:
```
import { registerPlugin } from '@wordpress/plugins';
import { PluginPrePublishPanel } from '@wordpress/editor';
const PluginPrePublishPanelTest = () => (
Pre Publish Panel
);
registerPlugin( 'pre-publish-panel-test', {
render: PluginPrePublishPanelTest,
} );
```
----------------------------------------
TITLE: Register Inserter Media Category Example
DESCRIPTION: Example usage of registering a custom media category for the Openverse image source.
SOURCE: https://github.com/wordpress/gutenberg/blob/trunk/docs/reference-guides/data/data-core-block-editor.md#_snippet_56
LANGUAGE: javascript
CODE:
```
wp.data.dispatch( 'core/block-editor' ).registerInserterMediaCategory( {
name: 'openverse',
labels: {
name: 'Openverse',
search_items: 'Search Openverse',
},
mediaType: 'image',
async fetch( query = {} ) {
const defaultArgs = {
mature: false,
excluded_source: 'flickr,inaturalist,wikimedia',
license: 'pdm,cc0',
};
const finalQuery = { ...query, ...defaultArgs };
// Map InserterMediaRequest params to API params (e.g., 'search' to 'q')
const mapFromInserterMediaRequest = {
per_page: 'page_size',
search: 'q',
};
const url = new URL( 'https://api.openverse.org/v1/images/' );
Object.entries( finalQuery ).forEach( ( [ key, value ] ) => {
const queryKey = mapFromInserterMediaRequest[ key ] || key;
url.searchParams.set( queryKey, value );
} );
const response = await window.fetch( url, {
headers: {
'User-Agent': 'WordPress/inserter-media-fetch',
},
} );
const jsonResponse = await response.json();
const results = jsonResponse.results;
return results.map( ( result ) => ( {
...result,
sourceId: result.id, // Map external ID to sourceId
id: undefined, // Clear WordPress ID for external items
caption: result.caption,
previewUrl: result.thumbnail,
} ) );
},
getReportUrl: ( { sourceId } ) =>
`https://wordpress.org/openverse/image/${ sourceId }/report/`,
isExternalResource: true,
} );
```
----------------------------------------
TITLE: Register PluginPostStatusInfo Component
DESCRIPTION: Demonstrates how to register a WordPress plugin using the `PluginPostStatusInfo` component. This component allows developers to insert custom content into the document sidebar's Summary panel. It requires the `@wordpress/plugins` and `@wordpress/editor` packages.
SOURCE: https://github.com/wordpress/gutenberg/blob/trunk/docs/reference-guides/slotfills/plugin-post-status-info.md#_snippet_0
LANGUAGE: js
CODE:
```
import { registerPlugin } from '@wordpress/plugins';
import { PluginPostStatusInfo } from '@wordpress/editor';
const PluginPostStatusInfoTest = () => (
Post Status Info SlotFill
);
registerPlugin( 'post-status-info-test', { render: PluginPostStatusInfoTest } );
```
----------------------------------------
TITLE: Register PluginDocumentSettingPanel
DESCRIPTION: Demonstrates how to register a custom panel for document settings using the PluginDocumentSettingPanel component. It outlines the available props like name, title, and className, and shows the integration with the registerPlugin function.
SOURCE: https://github.com/wordpress/gutenberg/blob/trunk/docs/reference-guides/slotfills/plugin-document-setting-panel.md#_snippet_0
LANGUAGE: javascript
CODE:
```
import {
registerPlugin
} from '@wordpress/plugins';
import {
PluginDocumentSettingPanel
} from '@wordpress/editor';
const PluginDocumentSettingPanelDemo = () => (
Custom Panel Contents
);
registerPlugin( 'plugin-document-setting-panel-demo', {
render: PluginDocumentSettingPanelDemo,
icon: 'palmtree',
} );
```
----------------------------------------
TITLE: Inserter Media Categories Configuration
DESCRIPTION: Defines an array of media categories for the Gutenberg inserter. Each category includes a name, labels, a media type, and a fetch function to retrieve media items. The fetch function handles API requests, parameter mapping, and response transformation.
SOURCE: https://github.com/wordpress/gutenberg/blob/trunk/platform-docs/docs/basic-concepts/settings.md#_snippet_3
LANGUAGE: jsx
CODE:
```
const inserterMediaCategories = {
name: 'openverse',
labels: {
name: 'Openverse',
search_items: 'Search Openverse',
},
mediaType: 'image',
async fetch( query = {} ) {
const defaultArgs = {
mature: false,
excluded_source: 'flickr,inaturalist,wikimedia',
license: 'pdm,cc0',
};
const finalQuery = { ...query, ...defaultArgs };
// Sometimes you might need to map the supported request params according to the `InserterMediaRequest`
// interface. In this example the `search` query param is named `q`.
const mapFromInserterMediaRequest = {
per_page: 'page_size',
search: 'q',
};
const url = new URL( 'https://api.openverse.engineering/v1/images/' );
Object.entries( finalQuery ).forEach( ( [ key, value ] ) => {
const queryKey = mapFromInserterMediaRequest[ key ] || key;
url.searchParams.set( queryKey, value );
} );
const response = await window.fetch( url, {
headers: {
'User-Agent': 'WordPress/inserter-media-fetch',
},
} );
const jsonResponse = await response.json();
const results = jsonResponse.results;
return results.map( ( result ) => ( {
...result,
// If your response result includes an `id` prop that you want to access later, it should
// be mapped to `InserterMediaItem`'s `sourceId` prop. This can be useful if you provide
// a report URL getter.
// Additionally you should always clear the `id` value of your response results because
// it is used to identify WordPress media items.
sourceId: result.id,
id: undefined,
caption: result.caption,
previewUrl: result.thumbnail,
} ) );
},
getReportUrl: ( { sourceId } ) =>
`https://wordpress.org/openverse/image/${ sourceId }/report/`,
isExternalResource: true,
}
```
----------------------------------------
TITLE: Register PluginPostPublishPanel Content
DESCRIPTION: This JavaScript example demonstrates how to register a custom plugin that injects content into the post-publish panel using the `@wordpress/plugins` and `@wordpress/editor` packages. It defines a React component to be rendered within the panel, allowing custom UI elements to be displayed after a post is published.
SOURCE: https://github.com/wordpress/gutenberg/blob/trunk/docs/reference-guides/slotfills/plugin-post-publish-panel.md#_snippet_0
LANGUAGE: javascript
CODE:
```
import { registerPlugin } from '@wordpress/plugins';
import { PluginPostPublishPanel } from '@wordpress/editor';
const PluginPostPublishPanelTest = () => (
Post Publish Panel
);
registerPlugin( 'post-publish-panel-test', {
render: PluginPostPublishPanelTest,
} );
```
----------------------------------------
TITLE: Theme.json 'useRootPaddingAwareAlignments' Setting
DESCRIPTION: Enables root padding awareness for alignments, applying padding from 'styles.spacing.padding' to full-width block content instead of the root block. Requires 'styles.spacing.padding' to be an object with explicit top, right, bottom, left values.
SOURCE: https://github.com/wordpress/gutenberg/blob/trunk/docs/reference-guides/theme-json-reference/theme-json-living.md#_snippet_2
LANGUAGE: APIDOC
CODE:
```
useRootPaddingAwareAlignments:
Description: Enables root padding to be applied to the contents of full-width blocks instead of the root block.
Constraints: Requires 'styles.spacing.padding' to be an object with declared 'top', 'right', 'bottom', 'left' values.
Scope: Top-level only property; not available in blocks.
```
----------------------------------------
TITLE: ActionItem Component Props - React
DESCRIPTION: Defines the properties for the ActionItem component, which acts as a 'fill' in a slot & fill pattern. It specifies how an individual action item is rendered and its behavior.
SOURCE: https://github.com/wordpress/gutenberg/blob/trunk/packages/interface/src/components/action-item/README.md#_snippet_0
LANGUAGE: APIDOC
CODE:
```
ActionItem:
Props:
name: The name of the slot and fill pair passed to the Fill component.
Type: String
Required: Yes
onClick: Callback function executed when a click on the item happens.
Type: Function
Required: no
as: The component that is going to be used to render an action item. Defaults to the Button component.
Type: Component
Required: no
Default: Button
```
----------------------------------------
TITLE: Change Icon
DESCRIPTION: Replaces the default WordPress icon button in the post editor's header with a custom close icon. This snippet demonstrates how to use the `MainDashboardButton` component with a `FullscreenModeClose` component and a custom icon.
SOURCE: https://github.com/wordpress/gutenberg/blob/trunk/docs/reference-guides/slotfills/main-dashboard-button.md#_snippet_0
LANGUAGE: javascript
CODE:
```
import { registerPlugin } from '@wordpress/plugins';
import { __experimentalMainDashboardButton as MainDashboardButton } from '@wordpress/edit-post';
import { close } from '@wordpress/icons';
const MainDashboardButtonTest = () => (
);
registerPlugin( 'main-dashboard-button-test', {
render: MainDashboardButtonTest,
} );
```
----------------------------------------
TITLE: Define Private Store Namespace (Lock: String)
DESCRIPTION: Allows unlocking private store namespaces using a specific string value for the `lock` option. Only code possessing the correct lock string can access or modify the private store.
SOURCE: https://github.com/wordpress/gutenberg/blob/trunk/docs/reference-guides/interactivity-api/api-reference.md#_snippet_37
LANGUAGE: js
CODE:
```
const { store } = require( '@wordpress/interactivity' );
const PRIVATE_LOCK = 'my-secret-lock-string';
const { state } = store(
'myPlugin/private',
{ state: { messages: [ 'private message' ] } },
{ lock: PRIVATE_LOCK }
);
// The following call works as expected.
store(
'myPlugin/private',
{
/* store part */
},
{ lock: PRIVATE_LOCK }
);
```
----------------------------------------
TITLE: Theme.json Settings: useRootPaddingAwareAlignments
DESCRIPTION: Controls how root padding is applied to full-width blocks. When true, root padding values from `styles.spacing.padding` are applied to the content of full-width blocks instead of the root block itself. Requires `styles.spacing.padding` to be an object with explicit top, right, bottom, left values.
SOURCE: https://github.com/wordpress/gutenberg/blob/trunk/docs/reference-guides/theme-json-reference/theme-json-v2.md#_snippet_2
LANGUAGE: APIDOC
CODE:
```
Setting: useRootPaddingAwareAlignments
Description: Enables root padding (the values from `styles.spacing.padding`) to be applied to the contents of full-width blocks instead of the root block.
Note: When using this setting, `styles.spacing.padding` should always be set as an object with `top`, `right`, `bottom`, `left` values declared separately.
Type: boolean
Default: false
```
----------------------------------------
TITLE: Register PluginMoreMenuItem in WordPress
DESCRIPTION: Demonstrates how to register a new menu item in the WordPress 'More Tools & Options' section using the `PluginMoreMenuItem` component. It requires `@wordpress/plugins`, `@wordpress/editor`, and `@wordpress/icons`. The component accepts an `icon`, an `onClick` handler, and children for the menu item text.
SOURCE: https://github.com/wordpress/gutenberg/blob/trunk/docs/reference-guides/slotfills/plugin-more-menu-item.md#_snippet_0
LANGUAGE: javascript
CODE:
```
import { registerPlugin } from '@wordpress/plugins';
import { PluginMoreMenuItem } from '@wordpress/editor';
import { image } from '@wordpress/icons';
const MyButtonMoreMenuItemTest = () => (
{
alert( 'Button Clicked' );
} }
>
More Menu Item
);
registerPlugin( 'more-menu-item-test', { render: MyButtonMoreMenuItemTest } );
```
----------------------------------------
TITLE: Set Inserter Opened State (customize-widgets)
DESCRIPTION: Dispatches an action to control the visibility of the inserter. It can be toggled between open and closed states, or set to open at a specific insertion point.
SOURCE: https://github.com/wordpress/gutenberg/blob/trunk/docs/reference-guides/data/data-core-customize-widgets.md#_snippet_1
LANGUAGE: js
CODE:
```
import { useState } from 'react';
import { store as customizeWidgetsStore } from '@wordpress/customize-widgets';
import { __ } from '@wordpress/i18n';
import { useDispatch } from '@wordpress/data';
import { Button } from '@wordpress/components';
const ExampleComponent = () => {
const { setIsInserterOpened } = useDispatch( customizeWidgetsStore );
const [ isOpen, setIsOpen ] = useState( false );
return (
);
};
```
----------------------------------------
TITLE: Merge Server State Types with Client Inference (TypeScript)
DESCRIPTION: Illustrates merging manually typed server state with client-defined store types. This approach defines a `ServerState` type and combines it with the inferred type of the client store definition.
SOURCE: https://github.com/wordpress/gutenberg/blob/trunk/docs/reference-guides/interactivity-api/core-concepts/using-typescript.md#_snippet_4
LANGUAGE: ts
CODE:
```
// Types the server state.
type ServerState = {
state: {
counter: number;
};
};
// Defines the store in a variable to be able to extract its type later.
const storeDef = {
actions: {
increment() {
state.counter += 1;
},
},
callbacks: {
log() {
console.log( `counter: ${ state.counter }` );
},
},
};
// Merges the types of the server state and the client store definition.
type Store = ServerState & typeof storeDef;
// Injects the final types when calling the `store` function.
const { state } = store< Store >( 'myCounterPlugin', storeDef );
```
----------------------------------------
TITLE: Register PluginBlockSettingsMenuItem
DESCRIPTION: Demonstrates how to register a `PluginBlockSettingsMenuItem` component using the `@wordpress/plugins` and `@wordpress/editor` packages. This example shows how to define a menu item with specific allowed blocks, an icon, a label, and an `onClick` handler.
SOURCE: https://github.com/wordpress/gutenberg/blob/trunk/docs/reference-guides/slotfills/plugin-block-settings-menu-item.md#_snippet_0
LANGUAGE: javascript
CODE:
```
import { registerPlugin } from '@wordpress/plugins';
import { PluginBlockSettingsMenuItem } from '@wordpress/editor';
const PluginBlockSettingsMenuGroupTest = () => (
{
alert( 'clicked' );
} }
/>
);
registerPlugin( 'block-settings-menu-group-test', {
render: PluginBlockSettingsMenuGroupTest,
} );
```
----------------------------------------
TITLE: TypeScript: Type yielded values with TypeYield
DESCRIPTION: Demonstrates how to use the `TypeYield` helper in TypeScript to correctly type values resolved by `yield` expressions within asynchronous generators. This ensures type safety for results from asynchronous operations like `fetch`.
SOURCE: https://github.com/wordpress/gutenberg/blob/trunk/docs/reference-guides/interactivity-api/core-concepts/using-typescript.md#_snippet_21
LANGUAGE: ts
CODE:
```
import { store, type AsyncAction, type TypeYield } from '@wordpress/interactivity';
// Assume this function is defined elsewhere and fetches specific data.
const fetchCounterData = async ( counterValue: number ): Promise< { current: number, next: number } > => {
// internal logic...
};
const { state, actions } = store( 'myCounterPlugin', {
state: {
counter: 0,
},
actions: {
*loadCounterData(): AsyncAction< void > {
// Use TypeYield to correctly type the resolved value of the yield.
const data = ( yield fetchCounterData( state.counter ) ) as TypeYield< typeof fetchCounterData >;
// Now, `data` is correctly typed as { current: number, next: number }.
console.log( data.current, data.next );
// Update state based on the fetched data.
state.counter = data.next;
},
}
} );
```
----------------------------------------
TITLE: Get Inserter Opened State (customize-widgets)
DESCRIPTION: Retrieves the current state of the inserter, indicating whether it is open or closed. This selector is part of the core/customize-widgets data store.
SOURCE: https://github.com/wordpress/gutenberg/blob/trunk/docs/reference-guides/data/data-core-customize-widgets.md#_snippet_0
LANGUAGE: js
CODE:
```
import { store as customizeWidgetsStore } from '@wordpress/customize-widgets';
import { __ } from '@wordpress/i18n';
import { useSelect } from '@wordpress/data';
const ExampleComponent = () => {
const { isInserterOpened } = useSelect(
( select ) => select( customizeWidgetsStore ),
[]
);
return isInserterOpened()
? __( 'Inserter is open' )
: __( 'Inserter is closed.' );
};
```
----------------------------------------
TITLE: Complete MyFirstApp with Search Functionality
DESCRIPTION: Presents the complete `MyFirstApp` component, integrating the `SearchControl` for user input, `useState` for state management, and `useSelect` for fetching filtered pages from the WordPress API. The `searchTerm` state is correctly passed as a dependency to `useSelect` to ensure re-fetching when the search term changes.
SOURCE: https://github.com/wordpress/gutenberg/blob/trunk/docs/how-to-guides/data-basics/2-building-a-list-of-pages.md#_snippet_7
LANGUAGE: javascript
CODE:
```
import { useState } from 'react';
import { createRoot } from 'react-dom';
import { SearchControl } from '@wordpress/components';
import { useSelect } from '@wordpress/data';
import { store as coreDataStore } from '@wordpress/core-data';
function MyFirstApp() {
const [searchTerm, setSearchTerm] = useState( '' );
const pages = useSelect( select => {
const query = {};
if ( searchTerm ) {
query.search = searchTerm;
}
return select( coreDataStore ).getEntityRecords( 'postType', 'page', query );
}, [searchTerm] );
return (
)
}
```
----------------------------------------
TITLE: JSX: Empty Lock Node Structure
DESCRIPTION: Represents an empty node in the lock tree, containing an empty array for locks and an empty object for child nodes. This is the base structure for any part of the state tree.
SOURCE: https://github.com/wordpress/gutenberg/blob/trunk/packages/core-data/src/locks/README.md#_snippet_0
LANGUAGE: jsx
CODE:
```
{
"locks": [],
"children": {}
}
```
----------------------------------------
TITLE: Toggle Editor Panel Programmatically
DESCRIPTION: Shows how to programmatically toggle the open/closed state of editor panels, including custom panels. It utilizes the `useDispatch` hook from '@wordpress/data' and the `toggleEditorPanelOpened` function from the '@wordpress/editor' store, requiring the panel's unique name.
SOURCE: https://github.com/wordpress/gutenberg/blob/trunk/docs/reference-guides/slotfills/plugin-document-setting-panel.md#_snippet_1
LANGUAGE: javascript
CODE:
```
import {
useDispatch
} from '@wordpress/data';
import {
store as editorStore
} from '@wordpress/editor';
const Example = () => {
const { toggleEditorPanelOpened } = useDispatch( editorStore );
return (
);
};
```
----------------------------------------
TITLE: Add items to toolbar with PluginSidebar in WordPress (JSX)
DESCRIPTION: Demonstrates how to use the `PluginSidebar` component from `@wordpress/editor` to add custom content to the WordPress editor's toolbar. It includes registering a plugin with a sidebar containing various WordPress components like `PanelBody`, `TextControl`, `SelectControl`, and `Button`. Dependencies include `@wordpress/i18n`, `@wordpress/editor`, `@wordpress/components`, and `@wordpress/plugins`.
SOURCE: https://github.com/wordpress/gutenberg/blob/trunk/docs/reference-guides/slotfills/plugin-sidebar.md#_snippet_0
LANGUAGE: jsx
CODE:
```
import { __ } from '@wordpress/i18n';
import { PluginSidebar } from '@wordpress/editor';
import {
PanelBody,
Button,
TextControl,
SelectControl,
} from '@wordpress/components';
import { registerPlugin } from '@wordpress/plugins';
import { useState } from '@wordpress/element';
const PluginSidebarExample = () => {
const [ text, setText ] = useState( '' );
const [ select, setSelect ] = useState( 'a' );
return (
{ __( 'This is a heading for the PluginSidebar example.' ) }
{ __( 'This is some example text for the PluginSidebar example.' ) }
setText( newText ) }
/>
setSelect( newSelect ) }
/>
);
};
// Register the plugin.
registerPlugin( 'plugin-sidebar-example', { render: PluginSidebarExample } );
```
----------------------------------------
TITLE: Set Default Block and Enable Direct Insertion for InnerBlocks
DESCRIPTION: Illustrates using the `defaultBlock` prop to pre-fill InnerBlocks with a specific block and its attributes. The `directInsert` prop, when set to true, enables immediate insertion of this default block upon interaction.
SOURCE: https://github.com/wordpress/gutenberg/blob/trunk/platform-docs/docs/create-block/nested-blocks.md#_snippet_2
LANGUAGE: jsx
CODE:
```
;
```
----------------------------------------
TITLE: Replace PostFeaturedImage Panel Content with wp.hooks
DESCRIPTION: Demonstrates replacing the Post Featured Image selection tool's content using a `wp.hooks` filter. The provided function returns a new React element, effectively substituting the original component's output.
SOURCE: https://github.com/wordpress/gutenberg/blob/trunk/packages/editor/src/components/post-featured-image/README.md#_snippet_0
LANGUAGE: javascript
CODE:
```
function replacePostFeaturedImage() {
return function () {
return React.createElement(
'div',
{},
'The replacement contents or components.'
);
};
}
wp.hooks.addFilter(
'editor.PostFeaturedImage',
'my-plugin/replace-post-featured-image',
replacePostFeaturedImage
);
```
----------------------------------------
TITLE: PostPendingStatus API
DESCRIPTION: API documentation for the PostPendingStatus component, used for displaying and toggling the pending status of a post.
SOURCE: https://github.com/wordpress/gutenberg/blob/trunk/packages/editor/README.md#_snippet_59
LANGUAGE: APIDOC
CODE:
```
PostPendingStatus()
A component for displaying and toggling the pending status of a post.
Returns:
React.ReactNode: The rendered component.
```
----------------------------------------
TITLE: Render Scoped Cover Block with Testing Library
DESCRIPTION: Shows how to render a specific Gutenberg block (Cover block) in isolation using `react-native-testing-library`. It includes setting up mock attributes and using `SlotFillProvider` and `BlockEdit` for rendering within a test environment.
SOURCE: https://github.com/wordpress/gutenberg/blob/trunk/docs/contributors/code/react-native/integration-test-guide.md#_snippet_1
LANGUAGE: javascript
CODE:
```
// This import points to the index file of the block
import { metadata, settings, name } from '../index';
// ... other imports and setup
const setAttributes = jest.fn();
const attributes = {
backgroundType: IMAGE_BACKGROUND_TYPE,
focalPoint: { x: '0.25', y: '0.75' },
hasParallax: false,
overlayColor: { color: '#000000' },
url: 'mock-url',
};
// ... other setup
// Simplified tree to render Cover edit within slot
const CoverEdit = ( props ) => (
);
const { getByText, findByText } = render(
);
```
----------------------------------------
TITLE: isInserterOpened Selector
DESCRIPTION: Checks if the block inserter UI is currently open. Returns true if the inserter is open, false otherwise. Requires the global application state.
SOURCE: https://github.com/wordpress/gutenberg/blob/trunk/docs/reference-guides/data/data-core-editor.md#_snippet_20
LANGUAGE: APIDOC
CODE:
```
isInserterOpened( state )
- Returns: boolean
- Description: Returns true if the inserter is opened.
- Parameters:
- state (Object): Global application state.
```
----------------------------------------
TITLE: Toggle Global Block Inserter
DESCRIPTION: Opens or closes the global block inserter panel.
SOURCE: https://github.com/wordpress/gutenberg/blob/trunk/packages/e2e-test-utils/README.md#_snippet_64
LANGUAGE: APIDOC
CODE:
```
toggleGlobalBlockInserter()
- Toggles the global inserter.
```
----------------------------------------
TITLE: getInserterItems
DESCRIPTION: Generates and returns a list of items suitable for display in the block inserter UI. Items are ordered by utility and recency, including static and dynamic block types.
SOURCE: https://github.com/wordpress/gutenberg/blob/trunk/docs/reference-guides/data/data-core-block-editor.md#_snippet_28
LANGUAGE: APIDOC
CODE:
```
getInserterItems(state: Object, rootClientId?: string): WPEditorInserterItem[]
- Determines the items that appear in the inserter. Includes both static items (e.g. a regular block type) and dynamic items (e.g. a reusable block).
- Each item object contains what's necessary to display a button in the inserter and handle its selection.
- The 'frecency' property is a heuristic () that combines block usage frequency and recency.
- Items are returned ordered descendingly by their 'utility' and 'frecency'.
- Parameters:
- state: Object - Editor state.
- rootClientId: ?string - Optional root client ID of block list.
- Returns:
- WPEditorInserterItem[]: Items that appear in inserter.
- Type Definition:
- WPEditorInserterItem: Object
- id: string - Unique identifier for the item.
- name: string - The type of block to create.
- initialAttributes: Object - Attributes to pass to the newly created block.
- title: string - Title of the item, as it appears in the inserter.
- icon: string - Dashicon for the item, as it appears in the inserter.
- category: string - Block category that the item is associated with.
- keywords: string[] - Keywords that can be searched to find this item.
- isDisabled: boolean - Whether or not the user should be prevented from inserting this item.
- frecency: number - Heuristic that combines frequency and recency.
```