Agregar OpenGraph y Twitter Cards sin Plugins

Si quieres añadir una nueva funcionalidad a tu sitio de WordPress, probablemente encontrarás esa funcionalidad en el repositorio de Plugins.

Si deseas agregar OpenGraph y Twitter Cards para que tu contenido luzca mejor cuando se comparte en las redes sociales, la solución probablemente esta en un plugin de SEO

Si eres como yo y evitas usar plugins a toda costa, quizás quieras usar un code snippets en vez de casarte con un plugin de SEO.

En esta publicación te enseñaré como agregar OpenGraph y Twitter Cards a tu contenido sin la necesidad de instalar un nuevo plugin.



Código para Agregar OpenGraph and Twitter Card de Forma Automatica

He estado tratando de deshacerme de SEOPress por algún tiempo y creo que esta mi ultima relación con ese y cualquier plugin de SEO.

Este Snippet ha sido creado tomando en cuenta lo que SEOPress hace en términos de OpenGraph y Twitter Cards.

<?php

/*
  Plugin Name: Open Graph
  Plugin URI: https://wpsurfer.com
  Description: Add Open Graph to Posts and Pages
  Version: 1.0
  Author: TicoLibre
  Author URI: https://wpsurfer.com
*/

function add_open_graph_tags() {
  if (is_single() || is_page()) {
    global $post;
    setup_postdata($post);

    function get_description() {
      global $post;

      // Check if the 'meta-description' custom field exists
      $meta_description = get_post_meta($post->ID, 'meta_description', true);
      if ($meta_description) {
        return $meta_description;
      }

      // If the 'meta-description' custom field does not exist, get the excerpt from the content
      $excerpt = get_the_content();
      $excerpt = preg_replace(" (\[.*?\])",'',$excerpt);
      $excerpt = strip_shortcodes($excerpt);
      $excerpt = strip_tags($excerpt);
      $excerpt = substr($excerpt, 0, 200);
      $excerpt = substr($excerpt, 0, strripos($excerpt, " "));
      $excerpt = trim(preg_replace( '/\s+/', ' ', $excerpt));
      return $excerpt;
    }

    // Get the post categories
    $categories = get_the_category();
    $category_name = '';

    if (!empty($categories)) {
      // Assuming you want the name of the first category
      $category_name = $categories[0]->name;
    }

    // Open Graph tags
    echo '<meta property="og:url" content="' . get_the_permalink() . '">' . "\n";
    echo '<meta property="og:site_name" content="' . get_bloginfo('name') . '">' . "\n";
    echo '<meta property="og:locale" content="en_US">' . "\n";
    echo '<meta property="og:type" content="article">' . "\n";

    echo '<meta property="article:author" content="Manuel Campos">' . "\n";
    echo '<meta property="article:publisher" content="TicoLibre">' . "\n";
    echo '<meta property="article:section" content="' . esc_attr($category_name) . '">' . "\n"; // Include the category name

    echo '<meta property="og:title" content="' . get_the_title() . '">' . "\n";
    echo '<meta property="og:description" content="' . get_description() . '">' . "\n";

    if (has_post_thumbnail()) {
      $thumbnail_id = get_post_thumbnail_id($post->ID);
      $thumbnail_src = wp_get_attachment_image_src($thumbnail_id, 'medium');
      $thumbnail_alt = get_post_meta($thumbnail_id, '_wp_attachment_image_alt', true); // Get the alt tag

      if ($thumbnail_src) {
        $width = $thumbnail_src[1];
        $height = $thumbnail_src[2];

        echo '<meta property="og:image" content="' . esc_attr($thumbnail_src[0]) . '">' . "\n";
        echo '<meta property="og:image:secure_url" content="' . esc_attr($thumbnail_src[0]) . '">' . "\n";
        echo '<meta property="og:image:width" content="' . esc_attr($width) . '">'. "\n";
        echo '<meta property="og:image:height" content="' . esc_attr($height) . '">'. "\n";

        // Include the alt tag
        echo '<meta property="og:image:alt" content="' . esc_attr($thumbnail_alt) . '"/>'. "\n";
      }
    }

    // Twitter Card tags
    echo '<meta name="twitter:card" content="summary">' . "\n";
    echo '<meta name="twitter:site" content="Tico Libre">' . "\n";
    echo '<meta name="twitter:creator" content="Manuel Campos">' . "\n";
    echo '<meta name="twitter:title" content="' . get_the_title() . '">' . "\n";
    echo '<meta name="twitter:description" content="' . get_description() . '">' . "\n";
    if (has_post_thumbnail()) {
      $thumbnail_src = wp_get_attachment_image_src(get_post_thumbnail_id($post->ID), 'medium');
      echo '<meta name="twitter:image" content="' . esc_attr($thumbnail_src[0]) . '">' . "\n";
    }
  }
}
add_action('wp_head', 'add_open_graph_tags', 3);

Lo único que debes hacer para implementar el código es crear el folder mu-plugin en tu la carpeta wp-content.

Una vez que has creado el folder, debes crear un archivo y nombrarlo como quieras.

Luego copias y pegas mi code snippet y cambias los detalles del autor y el sitio:

   echo '<meta property="article:author" content="Manuel Campos">' . "\n";
   echo '<meta property="article:publisher" content="TicoLibre">' . "\n";
    echo '<meta name="twitter:site" content="Tico Libre">' . "\n";
    echo '<meta name="twitter:creator" content="Manuel Campos">' . "\n";

Una vez realizados los cambios, puedes guardar el archivo y verificar que el código ha sido agregado a la parte posterior del código fuente de tu sitio.


Precaución

Si has jugado con Code Snippets sabrás que estos pueden romper tu sitio, si te equivocas al implementarlo.

Si ese fuese el caso, lo que debes hacer es usar FileZilla e ir a la instalación de tu sitio y borrar el archivo php que agregaste a la carpeta mu-plugin


Manuel Campos, English Professor

Manuel Campos

I am José Manuel. I am writing about things I know and things that I am learning about WordPress. I hope you find the content of this blog useful.

WP SURFER

home

about

privacy

contact

© 2024 WP SURFER • Made with Love in Costa Rica