Function and usage of get_post_meta_by_id() in wordpress


Answers ( 1 )


    get_post_meta_by_id() is a function in WordPress, a popular content management system, used to retrieve metadata associated with a post. Metadata in WordPress can include additional information about a post, such as custom fields. Here’s a detailed explanation of this function and an example of how to use it:

    Function Definition

    • Function Name: get_post_meta_by_id
    • Parameter:
      • $mid (int, required): The meta ID for which the post metadata is to be fetched.
    • Return Type:
      • Returns an object or bool. The function will return an object if metadata with the specified meta ID is found. It will return false if no metadata is found for the given meta ID.

    Function Usage:

    The get_post_meta_by_id() function is specifically designed to retrieve metadata based on its unique meta ID. This is different from the more commonly used get_post_meta() function, which retrieves metadata based on the post ID and meta key.

    Sample Usage:

    // Assume $mid is the meta ID you have
    $mid = 123; // example meta ID
    // Retrieve the metadata object
    $meta_data = get_post_meta_by_id($mid);
    // Check if metadata was found
    if ($meta_data) {
        // Metadata found, process it
        echo 'Meta Value: ' . $meta_data->meta_value;
    } else {
        // Metadata not found
        echo 'No metadata found for meta ID: ' . $mid;

    In this example:

    1. We have a meta ID stored in the $mid variable.
    2. We use get_post_meta_by_id($mid) to attempt to retrieve the metadata associated with this ID.
    3. If metadata is found, it is processed and its value is displayed. If no metadata is found for the given ID, a message is displayed indicating that no metadata was found.

    This function is useful in scenarios where you are dealing with meta IDs directly and need to fetch metadata without knowing the associated post ID or meta key. However, it's less commonly used in typical WordPress development compared to get_post_meta().

Leave an answer