#javascript #reactjs #wordpress #wordpress-gutenberg
#javascript #reactjs #wordpress #wordpress-gutenberg
Вопрос:
Я создал пользовательский компонент для редактора WordPress gutenberg. Мне нужен был способ выбрать одну категорию из списка уже выбранных категорий. Я смог добиться такой функциональности с помощью приведенного ниже кода. Единственная проблема с моим компонентом заключается в том, что он не обновляет свой список категорий, если пользователь добавляет совершенно новую категорию в самом редакторе, при добавлении подобной категории категория выбирается автоматически и поэтому должна присутствовать в пользовательском раскрывающемся списке.
Я просматривал документацию и не нахожу способа добиться этого эффекта, похоже, что select().getEntityRecords()
это кэширование первого полученного набора результатов и не будет запрашивать свежие данные без обновления страницы.
Примечание: существует дополнительная функциональность для ограничения количества обычных категорий, которые пользователь может проверять. В настоящее время мой код ограничивает его до 3 и не позволит пользователю сохранить сообщение, если они проверили более 3.
index.js
// WordPress dependencies.
import { createElement as el, Fragment } from '@wordpress/element';
import { __ } from '@wordpress/i18n';
// Internal dependencies.
import PostPrimaryCategory from './post-primary-category';
/**
* Add new field to category content block
* Also add a limit check for categories
*
* @param {*} OriginalComponent
*/
function wrapPostPrimaryCategory( OriginalComponent ) {
return function( props ) {
// create content block
let originalElement = el( OriginalComponent, props );
let errorMessage = null;
// if the content block is category
if ( 'category' === originalElement.props.slug ) {
// turn on update/publish button
jQuery( ".editor-post-publish-button" ).prop( "disabled", false );
if ( 3 < originalElement.props.terms.length ) {
// if number of categories is more then 3, show error and disable publish/edit button
errorMessage = el( 'p', { class: 'error-message' }, __( 'Too many categories have been selected', 'post-categories-error' ) );
jQuery( ".editor-post-publish-button" ).prop( "disabled", true );
}
}
// compile all elements of the content block together
let elements = 'category' !== originalElement.props.slug ? el(
Fragment, null,
originalElement
) : (
el(
Fragment, null,
el( 'h4', null, __( 'Categories', 'post-categories' ) ),
// show error message if there is one
errorMessage,
originalElement,
// Show a custom heading
el( 'h4', null, __( 'Primary Category', 'post-primary-category' ) ),
// add new field
<PostPrimaryCategory selectedTerms={ originalElement.props.terms } />
)
);
return elements;
};
}
// hook to get access to the category ( and post tags ) content blocks in the editor
wp.hooks.addFilter(
'editor.PostTaxonomyType',
'authentic-child/assets/js/post-primary-category',
wrapPostPrimaryCategory
);
post-primary-category.js
// WordPress dependencies.
import { SelectControl } from '@wordpress/components';
import { compose } from '@wordpress/compose';
import { withSelect, withDispatch } from '@wordpress/data';
// Whenever the post is edited, this would be called. And we use it to pass the
// updated metadata to the above function.
const applyWithSelect = withSelect( ( select ) => {
return {
primaryCategory: select( 'core/editor' ).getEditedPostAttribute( 'meta' ).primary_category,
categories: select( 'core' ).getEntityRecords( 'taxonomy', 'category', { per_page:-1, hide_empty:false } )
};
} );
// Whenever the post is edited, this would also be called. And we use it to update
// the metadata through the above function. But note that the changes would only
// be saved in the database when you click on the submit button, e.g. the "Update"
// button on the post editing screen. :)
const applyWithDispatch = withDispatch( ( dispatch ) => {
const { editPost } = dispatch( 'core/editor' );
return {
onSetPrimaryCategory( primaryCategory ) {
const meta = { primary_category: primaryCategory };
editPost( { meta } );
}
};
} );
// This basically simply renders the select drop down.
function PostPrimaryCategory( {
// passsed in from the wrap function in index.js
selectedTerms,
// These these props are passed by applyWithSelect().
primaryCategory,
categories,
// Whereas this is passed by applyWithDispatch().
onSetPrimaryCategory,
} ) {
return (
<>
<SelectControl
label="This category will be displayed on the post when it is on the home/search pages"
value={ primaryCategory }
onChange={ onSetPrimaryCategory }
options={ null === categories || undefined === categories ? [] :
categories
.filter( ( { id, name } ) => ( "Uncategorized" === name || -1 === selectedTerms.indexOf( id ) ? false : true ) )
.map( ( { id, name } ) => ( { label: name, value: name } ) ) }
/>
</>
);
}
// And finally, 'compose' the above functions.
export default compose( applyWithSelect, applyWithDispatch )( PostPrimaryCategory );
Комментарии:
1. я не понимаю. как пользователь добавляет новую категорию? у select-control нет такой опции. можно использовать общий доступ к некоторому коду из этой части? или изображение
2. @arminyahya Нет, это встроенная функциональность самого WordPress. WordPress позволяет пользователю добавлять новые категории и большинство других таксономий, связанных с сообщениями, «на лету» при редактировании / создании сообщения в редакторе. Поэтому у меня нет простого способа поделиться кодом, который управляет этим. Извините.
Ответ №1:
Вы можете использовать useSelect
пользовательский хук реакции в функциональном компоненте. useSelect
будет «подписываться» на изменения и автоматически повторно отображать компонент, если значения изменяются (т. Е. Пользователь выбирает другую категорию).
Компонент для создания <SelectControl>
, который позволяет пользователю выбирать «Основную категорию», может выглядеть примерно так:
/**
* WordPress dependencies
*/
import { __ } from '@wordpress/i18n';
import { SelectControl } from '@wordpress/components';
import { useSelect } from '@wordpress/data';
import { useEntityProp } from '@wordpress/core-data';
function PostPrimaryCategory() {
const categories = useSelect((select) => {
/**
* Get the currently selected categories for a post. Since we are using
* useSelect, this will get updated any time the user adds or removes a
* category from the post.
*/
const catIds = select('core/editor').getEditedPostAttribute('categories');
/**
* The line of code above just gets us an array of category IDs, so here
* we get the full category details (name, slug, id, etc) that we can
* use to populate the SelectControl.
*/
return !!catIds amp;amp; catIds.length > 0 ?
select('core').getEntityRecords('taxonomy', 'category', {
include: catIds.join(','),
per_page: -1,
}) : [];
});
// We need the post type for setting post meta
const postType = useSelect((select) => {
return select('core/editor').getCurrentPostType();
});
// Get and set the post meta
const [meta, setMeta] = useEntityProp('postType', postType, 'meta');
return (
<SelectControl
label={ __('Primary Category', 'text-domain') }
value={ meta.primary_category }
options={ categories.map(cat => {
return {
label: cat.name,
value: cat.id,
}
}) }
onChange={ (value) => setMeta({primary_category: value}) }
/>
);
};