• I am trying to write code that can add matadata in head of each web story without any plugin. I have written code that works for WordPress post but not for Web Story.

    Please look at the below code and provide your suggestion that can help to** add custom metadata in each Web Story** without any plugin.

    PHP Code Here:

    function header_metadata_add_to_header() {
    if (is_single() || is_page() || 'web-story' === get_post_type() || is_singular('web-story')) {
    
    $current_url = esc_url_raw(add_query_arg(array(), $_SERVER['REQUEST_URI']));
    
    // Check if the current URL matches the pattern
    if (preg_match('/^\/web-stories\/(\d+)\/$/', $current_url, $matches)) {
    $post_id = absint($matches[1]); // Extract the post ID from the URL
    } elseif (preg_match('/^\?p=(\d+)$/', parse_url($current_url, PHP_URL_QUERY), $matches)) {
    $post_id = absint($matches[1]); // Extract and sanitize the post ID<br>} else{<br>$post_id = get_the_ID();
    }
    $keywords = get_post_meta($post_id, '_header_metadata_keywords', true);<br><br>echo '<meta name="keywords" content="' . esc_attr($keywords) . '">';
    }
    add_action('wp_head', 'header_metadata_add_to_header');

    You can verify the post metadata here : [linked below] .

    • This topic was modified 1 year, 2 months ago by bcworkz. Reason: formatting fixed

    The page I need help with: [log in to see the link]

Viewing 1 replies (of 1 total)
  • I have 4 thoughts on this:

    1) What is a web story? This looks like a custom post type to me. What do you use to create it?

    2) You have a syntax error in your code, could also have happened by copying it here. This line is incorrect:

    $keywords = get_post_meta($post_id, '_header_metadata_keywords', true);<br><br>echo '<meta name="keywords" content="' . esc_attr($keywords) . '">';

    Correct would be:

    $keywords = get_post_meta($post_id, '_header_metadata_keywords', true);
    echo '';

    3) The variable $post_id is not always set. I would recommend adding this line before the comment “// Check if the current URL matches the pattern”:

    $post_id = 0;

    Also, before the output, check if $post_id is greater than 0. So:

    if( $post_id > 0 ) {
     $keywords = get_post_meta($post_id, '_header_metadata_keywords', true);
    echo '<meta name="keywords" content="' . esc_attr($keywords) . '">';
    }

    4) What you are doing here has no value for search engines. The meta keywords tag has not been considered by any search engine for more than 10 years.

Viewing 1 replies (of 1 total)
  • The topic ‘How to add metadata in each Web Story without plugin?’ is closed to new replies.