Site logo

[Support request] Using Custom Fields in HTML Block

Home Forums Support [Support request] Using Custom Fields in HTML Block

Home Forums Support Using Custom Fields in HTML Block

Viewing 2 posts - 1 through 2 (of 2 total)
  • Author
    Posts
  • #2425151
    Jon

    Hi

    I’m trying to figure out the best way to use custom field data inside an HTML block.

    Or, it’s something I can use on various sites as it loads so much faster than the standard YouTube embed blocks that I’ve tried.

    It may well be worth me creating my own custom Gutenberg block, so if you could tell me how I can use GP Custom Fields in a child theme’s functions file, then that would also be useful.

    The use case is that I want to embed YouTube videos in a global header widget that gets its YouTube video ID from a custom field created using GP’s custom fields.

    The YouTube Embed Lite Script can be found here:
    https://github.com/paulirish/lite-youtube-embed

    This is the code for the Lite YouTube Embed script uses:

    <lite-youtube videoid=”I_NEED_THIS_DATA_TO_COME_FROM_A_CUSTOM_FIELD”></lite-youtube>

    #2425233
    David
    Staff
    Customer Support

    Hi there,

    so WordPress allows you to save Custom Fields on any post:

    https://wordpress.org/support/article/custom-fields/

    Lets say you:

    1. Edit a post and add a New custom field, titled youtubeid and give it a value.

    2. You can retrieve that value using PHP and the WordPress get_post_meta function. Which can then be output where you require.

    3. However PHP cannot be added to a HTML block inside the post editor. So to do that would require a Shortcode or a custom block.

    To create a shortcode add this PHP Snippet to your site:

    
    function custom_youtube_embed() {
    
        // Setup our HTML output
        $html = '';
        // Get the custom field titled: youtubeid
        $id = get_post_meta(get_the_id(), 'youtubeid', true);
        if( !empty($id) ){
            // if the youtubeid has a value update our html
            $html = sprintf('<lite-youtube videoid="%1$s"></lite-youtube>', $id );
        }
    
        return $html;
    }
    add_shortcode( 'show_yt_lite', 'custom_youtube_embed' );

    You can then add your [show_yt_lite] shortcode wherever you require it.

    You’re alternative to this is to use the core embed block, and use this plugin:
    https://wordpress.org/plugins/wp-youtube-lyte/

    It will make it so just the video poster is displayed, the scripts and the player won’t load until their is user interaction with it.

Viewing 2 posts - 1 through 2 (of 2 total)
  • You must be logged in to reply to this topic.