Function and usage of get_post_custom_keys() in wordpress


Answers ( 1 )


    The get_post_custom_keys() function in WordPress is used to retrieve the names of all custom meta fields for a specific post. Custom meta fields in WordPress are used to store additional information about posts, which is not included in the default post fields. This function is particularly useful when you want to know what extra data is associated with a post.

    Function Prototype:

    get_post_custom_keys( int $post_id ): array|void


    • This function returns the names (keys) of all custom meta fields for a given post.
    • If the specified post has no custom meta fields, the function returns null.


    • $post_id (int, optional): The ID of the post for which you want to retrieve custom field keys. If not specified, the function uses the ID of the global $post, which represents the current post in a WordPress loop.

    Return Value:

    • array|void: The function returns an array of strings, where each string is the key of a custom meta field. If no custom fields are found, or the post does not exist, the function returns null.

    Example Usage:

    Here's how you might use get_post_custom_keys() in a WordPress template or plugin:

    $post_id = get_the_ID(); // Get the current post's ID
    $custom_keys = get_post_custom_keys($post_id);
    if (!empty($custom_keys)) {
        echo '<ul>';
        foreach ($custom_keys as $key) {
            echo '<li>' . esc_html($key) . '</li>';
        echo '</ul>';
    } else {
        echo 'No custom fields found for this post.';

    In this example, the function is used to get the custom meta field keys for the current post. It then checks if there are any keys. If keys are found, it lists them in an HTML unordered list. If no keys are found, it displays a message indicating that no custom fields are available for this post.

    Remember, this function only retrieves the keys (names) of the custom fields, not their values. To get the values, you would use another function like get_post_meta().

Leave an answer