Search code examples
phpsmarty

How to dynamically modify the content of the meta property="og:image" in PHP?


I am using PHP and the Smarty template engine.

I would need to create a function or find some way that every time I share a video (i.e. a social network post that contains a video), I would take the value of the thumbnail of that video (the location of the thumbnail is stored in the database) and insert it into the content of the meta property="og:image", so that when I share it (for example, by Whatsapp), it shows the thumbnail of that video and not a default image.

Any ideas? Thanks in advance.


Solution

  • If you have only one video per page this is quite easy.

    1. get the data from the database

    2.) echo the retrieved data in the respective HTML fields

    e.g.

    for vanilla PHP

    <meta property="og:title" content="<?=  $title ?>" >
    <meta property="og:description" content="<?= $decription  ?>">
    <meta property="og:type" content="website" />
    <meta property="og:url" content="<?= $_SERVER['PHP_SELF']; ?>" >
    <meta property="og:image" content="<?= $thumbnail_url ?>" >
    <meta property="og:site_name" content="your site name" >
    <meta property="og:locale" content="es_ES" >
    <meta property="og:locale:alternate" content="en_US" >
    <meta property="fb:app_id" content="xxxxxxxxxxxxxxxxx" >
    <meta property="fb:admins" content="yyyyyyyyyyyyyyyyyyy" >
    

    in SMARTY you just replace the in the template with {$var}

    <meta property="og:title" content="{$title}" >
        <meta property="og:description" content="{$decription}">
        <meta property="og:type" content="website" />
        <meta property="og:url" content="{$_SERVER['PHP_SELF']}" >
        <meta property="og:image" content="{$thumbnail_url}" >
    

    3.) Test it with the fb Share Debugger https://developers.facebook.com/tools/debug/