Skip to content

Instantly share code, notes, and snippets.

@coreyworrell
Last active March 13, 2022 18:25
Show Gist options
  • Save coreyworrell/6312e13737eecec8a18d61fa8551881d to your computer and use it in GitHub Desktop.
Save coreyworrell/6312e13737eecec8a18d61fa8551881d to your computer and use it in GitHub Desktop.
Exclude current post from latest posts block
const { addFilter } = wp.hooks
const { createHigherOrderComponent } = wp.compose
const { InspectorControls } = wp.blockEditor
const { PanelBody, ToggleControl } = wp.components
function LatestPostsPlugin(settings, name) {
if (name !== 'core/latest-posts') {
return settings
}
settings.attributes = {
...settings.attributes,
excludeCurrentPost: {
type: 'boolean',
default: false,
},
}
return settings
}
const withInspectorControls = createHigherOrderComponent((BlockEdit) => {
return (props) => {
const { attributes, setAttributes } = props
const { excludeCurrentPost } = attributes
return (props.name === 'core/latest-posts') ? (
<>
<BlockEdit { ...props } />
<InspectorControls>
<PanelBody title="Exclude">
<ToggleControl
label="Exclude current"
help="Excludes the current post from list of latest posts"
checked={ excludeCurrentPost }
onChange={ () => setAttributes({ excludeCurrentPost: !excludeCurrentPost }) }/>
</PanelBody>
</InspectorControls>
</>
) : <BlockEdit { ...props }/>;
};
}, 'withInspectorControl');
function extraProps(props, blockType, attributes) {
const { excludeCurrentPost = false } = attributes
if (blockType.name !== 'core/latest-posts') {
return props
}
return { ...props, excludeCurrentPost }
}
addFilter(
'blocks.registerBlockType',
'site/latest-posts/exclude-current-post/plugin',
LatestPostsPlugin
);
addFilter(
'editor.BlockEdit',
'site/latest-posts/exclude-current-post/controls',
withInspectorControls
);
addFilter(
'blocks.getSaveContent.extraProps',
'site/latest-posts/exclude-current-post/save',
extraProps
);
<?php
declare(strict_types=1);
namespace Site\Post;
use WP_Query;
class Post
{
public function register(): void
{
add_filter('register_block_type_args', [$this, 'latestPostsBlockArgs'], 10, 2);
}
public function latestPostsBlockArgs(array $args, string $name): array
{
if ($name === 'core/latest-posts') {
$args['render_callback'] = [$this, 'latestPostsBlockRender'];
}
return $args;
}
public function latestPostsBlockRender(array $attributes): string
{
$filter = isset($attributes['excludeCurrentPost']) && $attributes['excludeCurrentPost'];
if ($filter) {
add_action('parse_query', [$this, 'parseQuery']);
}
$result = render_block_core_latest_posts($attributes);
if ($filter) {
remove_action('parse_query', [$this, 'parseQuery']);
}
return $result;
}
public function parseQuery(WP_Query $query): void
{
if (is_singular()) {
$query->query_vars['post__not_in'] = [get_queried_object()->ID];
}
}
}
(new Post())->register();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment