Skip to content

Featured: Query Loop Block Support #98

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 18 commits into
base: feature/classic-editor-support
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
18 commits
Select commit Hold shift + click to select a range
f111a95
Merge branch 'feature/rest-api-endpoint' into feature/query-loop-support
s3rgiosan Feb 21, 2025
d86a2c8
Merge branch 'feature/rest-api-endpoint' into feature/query-loop-support
s3rgiosan Feb 21, 2025
d747367
Add QueryLoop integration scaffold
s3rgiosan Feb 21, 2025
3d55313
Merge branch 'feature/rest-api-endpoint' into feature/query-loop-support
s3rgiosan Feb 21, 2025
69149c8
Rename class for clarity
s3rgiosan Feb 21, 2025
278be0b
Merge branch 'feature/rest-api-endpoint' into feature/query-loop-support
s3rgiosan Feb 21, 2025
ff6658f
Merge branch 'feature/rest-api-endpoint' into feature/query-loop-support
s3rgiosan Mar 14, 2025
bdca82a
Merge branch 'feature/data-api-backbone' into feature/query-loop-support
s3rgiosan Mar 14, 2025
f593472
Merge branch 'feature/data-api-backbone' into feature/query-loop-support
s3rgiosan Mar 14, 2025
afeae34
Merge branch 'feature/classic-editor-support' into feature/query-loop…
s3rgiosan Mar 14, 2025
31d0285
Add query loop block extension
s3rgiosan Mar 14, 2025
860ac4e
Update help texts
s3rgiosan Mar 14, 2025
fad2d96
Update query block extension
s3rgiosan Mar 17, 2025
8c30bcc
Rename extended attributes and add initial support for the relationsh…
s3rgiosan Mar 17, 2025
150c31e
Updates for Query Loop editor and front-end queries
s3rgiosan Mar 18, 2025
89ef678
Merge branch 'feature/data-api-backbone' into feature/query-loop-support
s3rgiosan Mar 18, 2025
48977e9
Merge branch 'feature/data-api-backbone' into feature/query-loop-support
s3rgiosan Apr 4, 2025
e33921d
Merge branch 'feature/classic-editor-support' into feature/query-loop…
s3rgiosan Apr 4, 2025
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .eslintrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"extends": [
"@10up/eslint-config/wordpress"
]
}
234 changes: 234 additions & 0 deletions assets/js/block-extensions/core-query.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,234 @@
/* eslint-disable import/no-extraneous-dependencies */
/* eslint-disable import/extensions */
/**
* External dependencies
*/
import { v4 as uuidv4 } from 'uuid';
import { registerBlockExtension, ContentPicker } from '@10up/block-components';

/**
* WordPress dependencies
*/
import {
ToggleControl,
PanelBody,
Notice,
SelectControl,
BaseControl,
} from '@wordpress/components';
import { InspectorControls } from '@wordpress/block-editor';
import { useSelect } from '@wordpress/data';
import { __ } from '@wordpress/i18n';
import { store as coreStore } from '@wordpress/core-data';
import { store as editorStore } from '@wordpress/editor';
import { useMemo, useEffect, useRef } from '@wordpress/element';

/**
* Internal dependencies
*/
import { store } from '../store';

const BlockEdit = ({ setAttributes, attributes }) => {
const { query, showRelated, relationshipKey, sourcePost, orderByRelationship } = attributes;
const { postType: queriedPostType } = query;

const { postTypes, relationships, hasRelationships, currentPostId, currentPostType } =
useSelect(
(select) => {
const { getPostTypes } = select(coreStore);
const excludedPostTypes = ['attachment'];
const filteredPostTypes = getPostTypes({ per_page: -1 })?.filter(
({ viewable, slug }) => viewable && !excludedPostTypes.includes(slug),
);

const currentPostId = select(editorStore).getCurrentPostId();
const currentPostType = select(editorStore).getCurrentPostType();

const postRelationships = select(store).getRelationships(
sourcePost?.[0]?.id || currentPostId,
);
const filteredRelationships = Object.values(postRelationships).filter(
(relationship) =>
Array.isArray(relationship.post_type) &&
relationship.post_type.includes(queriedPostType),
);

return {
postTypes: filteredPostTypes,
relationships: filteredRelationships,
hasRelationships: filteredRelationships.length > 0,
currentPostId,
currentPostType,
};
},
[queriedPostType, sourcePost?.length],
);

const postTypesSlugs = useMemo(() => (postTypes || []).map(({ slug }) => slug), [postTypes]);

const relationshipsOptions = useMemo(
() =>
relationships.map((relationship) => ({
value: relationship.rel_key,
label: relationship.labels.name,
})),
[relationships],
);

const selectedRelationshipKey = useMemo(
() =>
relationshipKey && relationships.some((rel) => rel.rel_key === relationshipKey)
? relationshipKey
: relationships[0]?.rel_key,
[relationshipKey, relationships],
);

const selectedRelationship = useMemo(
() =>
relationships.find((relationship) => relationship.rel_key === selectedRelationshipKey),
[relationships, selectedRelationshipKey],
);

const lastQueryRef = useRef(query);

const updatedQuery = useMemo(() => {
if (!showRelated || !selectedRelationship) {
const { relationshipQuery, orderByRelationship, ...cleanQuery } = query;
return cleanQuery;
}

return {
...query,
orderByRelationship: orderByRelationship && selectedRelationship.sortable,
relationshipQuery: [
{
name: selectedRelationship.rel_name,
related_to_post: sourcePost?.[0]?.id || currentPostId,
},
],
};
}, [query, showRelated, orderByRelationship, selectedRelationship, sourcePost, currentPostId]);

useEffect(() => {
if (JSON.stringify(lastQueryRef.current) !== JSON.stringify(updatedQuery)) {
setAttributes({ query: updatedQuery });
lastQueryRef.current = updatedQuery;
}
}, [updatedQuery, setAttributes]);

const relationshipsControlLabel = __('Relationship', 'tenup-content-connect');
const relationshipsControlHelp = __(
'Select a relationship to determine how related items are retrieved.',
'tenup-content-connect',
);
const sourcePostControlHelp = __(
'Choose the post from which related items will be pulled. Defaults to the current post.',
'tenup-content-connect',
);

const onRelationshipChange = (value) => {
setAttributes({ relationshipKey: value });
};

const resetAll = () => {
setAttributes({
showRelated: false,
sourcePost: undefined,
relationshipKey: undefined,
orderByRelationship: true,
});
};

return (
<InspectorControls>
<PanelBody title={__('Related', 'tenup-content-connect')} initialOpen={!!showRelated}>
<ToggleControl
label={__('Only show related items', 'tenup-content-connect')}
checked={showRelated}
onChange={(value) => {
if (!value) {
resetAll();
} else {
setAttributes({
showRelated: value,
sourcePost: [
{
id: currentPostId,
type: currentPostType,
uuid: uuidv4(),
},
],
});
}
}}
/>
{showRelated && (
<BaseControl help={sourcePostControlHelp}>
<ContentPicker
onPickChange={(ids) =>
setAttributes({ sourcePost: ids.length ? ids : undefined })
}
mode="post"
content={sourcePost}
contentTypes={postTypesSlugs}
singlePickedLabel={__('Selected post:', 'tenup-content-connect')}
multiPickedLabel={__('Selected posts:', 'tenup-content-connect')}
/>
</BaseControl>
)}
{showRelated && relationshipsOptions.length > 1 && (
<SelectControl
options={relationshipsOptions}
value={relationshipKey}
label={relationshipsControlLabel}
onChange={onRelationshipChange}
help={relationshipsControlHelp}
__nextHasNoMarginBottom
__next40pxDefaultSize
/>
)}
{showRelated && !hasRelationships && (
<Notice spokenMessage={null} status="warning" isDismissible={false}>
{__(
'No relationships exist for the selected post type or post. Try selecting a different post or post type.',
'tenup-content-connect',
)}
</Notice>
)}
{showRelated && selectedRelationship?.sortable && (
<ToggleControl
label={__('Order by relationship', 'tenup-content-connect')}
checked={orderByRelationship}
onChange={(value) => setAttributes({ orderByRelationship: value })}
help={__(
'If enabled, the order of the related items will be determined by the relationship.',
'tenup-content-connect',
)}
/>
)}
</PanelBody>
</InspectorControls>
);
};

registerBlockExtension('core/query', {
extensionName: 'content-connect',
attributes: {
showRelated: {
type: 'boolean',
default: false,
},
sourcePost: {
type: 'array',
},
relationshipKey: {
type: 'string',
},
orderByRelationship: {
type: 'boolean',
default: true,
},
},
classNameGenerator: () => '',
Edit: BlockEdit,
});
1 change: 1 addition & 0 deletions assets/js/block-extensions/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
import './core-query';
3 changes: 1 addition & 2 deletions assets/js/components/relationships-panel.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import React from 'react';
import { useSelect } from '@wordpress/data';
import { store as editorStore } from '@wordpress/editor';
import { PluginDocumentSettingPanel } from '@wordpress/edit-post';
import { store as editorStore, PluginDocumentSettingPanel } from '@wordpress/editor';
import { store } from '../store';
import { RelationshipManager } from './relationship-manager';

Expand Down
3 changes: 2 additions & 1 deletion assets/js/index.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import './store';
import './hooks';
import './block-extensions';

import { registerPlugin } from '@wordpress/plugins';
import { RelationshipsPanel } from './components/relationships-panel';

registerPlugin('wp-content-connect', {
registerPlugin('content-connect', {
render: RelationshipsPanel,
});
4 changes: 4 additions & 0 deletions includes/API/V2/Post/Field/Relationships.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,10 @@ public function register_fields() {

foreach ( $post_types as $post_type ) {

if ( 'attachment' === $post_type ) {
continue;
}

register_rest_field(
$post_type,
'relationships',
Expand Down
Loading