skip to Main Content

I didn’t find similar questions like mine, so I hope someone can explain to me what I am doing wrong.

I would like to echo from the backend wordpress custom fields via a function. This is what I do:

screenshot backend page

Function

function add_meta_data() {
    if ( is_page() ) {
        echo'<meta property="og:title" content="' . get_post_meta( $post_id, 'og_title', true ) . '">';
    }
add_action('wp_head','add_meta_data',1);

The above returns in an empty meta data:

frontend page head result

Before you comment about “Why not using existing SEO plugins?”, that is the whole thing I’d like to eliminate plugins which come with too many unused function and try to use existing features from WP.

3

Answers


  1. Chosen as BEST ANSWER

    The mistake I made in the function is that $post_id is not defined, as this is not a global variable. What needs to be done is:

    function add_meta_data() {
        if ( is_page() ) {
            $post_id = get_the_id();
            echo'<meta property="og:title" content="' . get_post_meta( $post_id, 'og_title', true ) . '">';
        }
    add_action('wp_head','add_meta_data',1);
    

  2. use this function with post id/

    get_post_meta( $post->ID, 'your_meta_key', true );
    

    Thanks

    Login or Signup to reply.
  3. If you are saving the og_title through get_post_meta in db then you will definitely have the og_title. But seems you are not passing the post_id which is mandatory.

    Please go through the doc mentioned on WP

    https://developer.wordpress.org/reference/functions/get_post_meta/

    You need to put the post_id to get the meta data. See the code below

    function add_meta_data() {
        if ( is_page() ) {
            echo'<meta property="og:title" content="' . get_post_meta($post_id ,'og_title' ) . '">';
        }
    add_action('wp_head','add_meta_data',1);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search