Mastering select(‘core’) in WordPress Gutenberg (With Simple Examples)


When working with Gutenberg blocks, accessing WordPress data efficiently is essential. One of the most commonly used tools for this is select('core').

In this guide, we’ll break it down in a simple and practical way, with examples you can use immediately.


📌 What is select('core')?

In Gutenberg:

  • select() is used to read data from a data store
  • 'core' refers to the WordPress core data store
  • It allows you to fetch:
    • Posts
    • Pages
    • Users
    • Taxonomies
    • Media

👉 In simple terms:

select('core') lets you fetch data from WordPress (via REST API) inside your block.


⚠️ Basic Example (Not Recommended for UI)

import { select } from '@wordpress/data';

const posts = select('core').getEntityRecords('postType', 'post');




❗ Why this is not ideal?

  • It is not reactive
  • UI will not update automatically
  • Should not be used inside React render logic

✅ Correct Way: Using useSelect

The recommended approach in Gutenberg is using the useSelect hook.


🎯 Example: Fetch Posts

import { useSelect } from '@wordpress/data';

const posts = useSelect((select) => {
    return select('core').getEntityRecords('postType', 'post');
}, []);

💾 Storing Data in a Variable & Using It

Here’s a simple working example:

import { useSelect } from '@wordpress/data';

export default function MyComponent() {

    const posts = useSelect((select) => {
        return select('core').getEntityRecords('postType', 'post');
    }, []);

    if (!posts) {
        return 'Loading...';
    }

    return (
        <ul>
            {posts.map((post) => (
                <li key={post.id}>
                    {post.title.rendered}
                </li>
            ))}
        </ul>
    );
}

🔍 What’s Happening Here?

  • useSelect() subscribes to the data store
  • posts variable stores fetched data
  • Initially, it returns null → then updates with real data
  • Component re-renders automatically when data is available

⚡ Using Query Parameters (Best Practice)

To improve performance, always limit the data you fetch:

const posts = useSelect((select) => {
    return select('core').getEntityRecords('postType', 'post', {
        per_page: 5,
        _fields: ['id', 'title'],
    });
}, []);

✅ Benefits:

  • Faster API response
  • Less memory usage
  • Cleaner data

🚀 Advanced Pattern (Loading State Handling)

const { posts, isLoading } = useSelect((select) => {
    const query = { per_page: 5 };

    return {
        posts: select('core').getEntityRecords('postType', 'post', query),
        isLoading: !select('core').hasFinishedResolution(
            'getEntityRecords',
            ['postType', 'post', query]
        ),
    };
}, []);

🧠 Why this is important?

  • Helps handle loading state properly
  • Prevents UI flickering
  • Useful for production-grade blocks
, , ,

Leave a Reply

Your email address will not be published. Required fields are marked *