Forums

How to use the "get_{$meta_type}_metadata" filter ? (2 posts)

  1. jfache
    Member
    Posted 1 year ago #

    Hi there,

    I expect to filter my post meta prior to display and I thought that the new get_{$meta_type}_metadata filter could help but I don't get it.

    I'm basically trying to add a "TEST" string at the end of each post meta I want to display. Here's my code :

    function more_test($content) {
      return $content . "TEST";
    }
    
    add_filter('get_post_metadata', 'more_test');
    
    echo get_post_meta($post->ID, 'meta_test', true);

    It returns me "TEST" alone instead of the meta content + the "TEST" string. The meta content is stripped and if I try to echo it it's empty.

    What am I doing wrong? Is the get_post_metadata hook filter intended for another use?

    Thanks in advance for your help,
    Jeremy

  2. David Carroll
    Member
    Posted 4 months ago #

    Hi jfache,

    Although it's been 10 months since you asked this question, you and others may still be interested.

    The issue with your code is the get_post_meta filter accepts 4 arguments, which needs to be reflected in your code. The following code example should work if your theme supports Featured Images.

    /* Description: Custom function to prevent post thumbnails from loading on search, category, and archive pages.
         * @param string|array $metadata - Always null for post metadata.
         * @param int $object_id - Post ID for post metadata
         * @param string $meta_key - metadata key.
         * @param bool $single - Indicates if processing only a single $metadata value or array of values.
         * @return Original or Modified $metadata.
         */
        function remove_post_thumbnail($metadata, $object_id, $meta_key, $single){
    
            //Return false if the current filter is that of a post thumbnail. Otherwise, return the original $content value.
            return ( isset($meta_key) && '_thumbnail_id' === $meta_key ) ? false : $metadata;
    
        }
    
        //Specify 4 arguments for this filter in the last parameter.
        add_filter('get_post_metadata', 'remove_post_thumbnail', true, 4);

    A good way to review how this works is reviewing the get_metadata() function in the /wp-includes/meta.php file.

    Look for the apply_filters line:

    $check = apply_filters( "get_{$meta_type}_metadata", null, $object_id, $meta_key, $single );

    Notice the second parameter is null. This is the first parameter ($metadata) in the custom filter function: remove_post_thumbnail().

    If the filter function returns anything other than null, the get_metadata() function will exit early. This is reflected in the conditional block immediately following the apply_filter() line.

    Hope this helps.

    David Carroll

Topic Closed

This topic has been closed to new replies.

About this Topic