Trusted WordPress tutorials, when you need them most.
Beginner’s Guide to WordPress
Copa WPB
25 Million+
Websites using our plugins
16+
Years of WordPress experience
3000+
WordPress tutorials
by experts

Cómo crear feeds RSS personalizados en WordPress

Nota editorial: Ganamos una comisión de los enlaces de socios en WPBeginner. Las comisiones no afectan a las opiniones o evaluaciones de nuestros editores. Más información sobre Proceso editorial.

¿Quieres crear un feed RSS personalizado en WordPress?

WordPress viene con un feed RSS por defecto que muestra el contenido de su sitio web. Sin embargo, si usted tiene un tipo específico de contenido, entonces es posible que desee crear un feed RSS personalizado para ello.

En este artículo, le mostraremos cómo crear fácilmente un feed RSS personalizado en WordPress.

Create custom RSS feed in WordPress

¿Por qué crear un feed RSS personalizado en WordPress?

WordPress incorpora un feed RSS, al que puede añadir fácilmente contenido personalizado o miniaturas.

Sin embargo, si usted tiene un tipo específico de contenido o tipo de entrada en su sitio web de WordPress, entonces es posible que desee crear un feed RSS personalizado para ello.

Por ejemplo, si ofrece a sus suscriptores contenidos exclusivos de autores específicos, puede crear un feed RSS personalizado para mantener a sus suscriptores informados acerca de los contenidos.

Además, los feeds personalizados también le dan más libertad al permitirle añadir el nombre del autor, las fechas de publicación o cualquier otra información relevante, proporcionando más detalles a sus usuarios.

Dicho esto, veamos cómo crear fácilmente feeds RSS personalizados en WordPress, paso a paso.

Nota: Debe crear una copia de seguridad completa de su sitio web WordPress antes de realizar cambios importantes en un sitio web activo.

Cómo crear un feed RSS personalizado en WordPress

Puede crear fácilmente un feed RSS personalizado en WordPress añadiendo código personalizado al archivo functions. php de su tema.

Este feed mostrará el título, enlace, fecha de publicación, autor y extractos de las entradas de su sitio WordPress.

Sin embargo, tenga en cuenta que el más mínimo error al escribir este código puede romper su sitio web y hacerlo inaccesible.

Por eso recomendamos usar WPCode. Es el mejor plugin de fragmentos de código de WordPress del mercado que hace que sea seguro y fácil añadir código personalizado a su sitio web.

Primero, necesitas instalar y activar el plugin WPCode. Para obtener instrucciones detalladas, consulte nuestra guía para principiantes sobre cómo instalar un plugin de WordPress.

Nota: Puedes utilizar el plugin gratuito WPCode para este tutorial. Sin embargo, la actualización al plan de pago desbloqueará más características como el modo de prueba, la opción de fragmentos de código CSS, la biblioteca en la nube, la lógica condicional y mucho más.

Una vez activado, visite la página Fragmentos de código ” + Añadir fragmento desde el escritorio de WordPress. Aquí, haga clic en el botón “Usar fragmento de código” debajo de la opción “Añadir su código personalizado (nuevo fragmento de código)”,

Add new snippet

Esto le llevará a la página “Crear fragmento de código personalizado”, donde puede empezar escribiendo un nombre para el fragmento de código.

A continuación, elija la opción “Fragmento de código PHP” en el menú desplegable Tipo de código de la derecha.

Choose the PHP Snippet option to create a custom RSS feed

Una vez hecho esto, añada el siguiente código personalizado en el cuadro “Vista previa del código”:

add_action('init', 'customRSS');
function customRSS(){
        add_feed('Feed', 'customRSSFunc');
}function customRSSFunc(){
        get_template_part('rss', 'feedname');
}<?php
/**
 * Template Name: Custom RSS Template - Feedname
 */
$postCount = 5; // The number of posts to show in the feed
$posts = query_posts('showposts=' . $postCount);
header('Content-Type: '.feed_content_type('rss-http').'; charset='.get_option('blog_charset'), true);
echo '<?xml version="1.0" encoding="'.get_option('blog_charset').'"?'.'>';
?>
<rss version="2.0"
        xmlns:content="http://purl.org/rss/1.0/modules/content/"
        xmlns:wfw="http://wellformedweb.org/CommentAPI/"
        xmlns:dc="http://purl.org/dc/elements/1.1/"
        xmlns:atom="http://www.w3.org/2005/Atom"
        xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
        xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
        <?php do_action('rss2_ns'); ?>>
<channel>
        <title><?php bloginfo_rss('name'); ?> - Feed</title>
        <atom:link href="<?php self_link(); ?>" rel="self" type="application/rss+xml" />
        <link><?php bloginfo_rss('url') ?></link>
        <description><?php bloginfo_rss('description') ?></description>
        <lastBuildDate><?php echo mysql2date('D, d M Y H:i:s +0000', get_lastpostmodified('GMT'), false); ?></lastBuildDate>
        <language><?php echo get_option('rss_language'); ?></language>
        <sy:updatePeriod><?php echo apply_filters( 'rss_update_period', 'hourly' ); ?></sy:updatePeriod>
        <sy:updateFrequency><?php echo apply_filters( 'rss_update_frequency', '1' ); ?></sy:updateFrequency>
        <?php do_action('rss2_head'); ?>
        <?php while(have_posts()) : the_post(); ?>
                <item>
                        <title><?php the_title_rss(); ?></title>
                        <link><?php the_permalink_rss(); ?></link>
                        <pubDate><?php echo mysql2date('D, d M Y H:i:s +0000', get_post_time('Y-m-d H:i:s', true), false); ?></pubDate>
                        <dc:creator><?php the_author(); ?></dc:creator>
                        <guid isPermaLink="false"><?php the_guid(); ?></guid>
                        <description><![CDATA[<?php the_excerpt_rss() ?>]]></description>
                        <content:encoded><![CDATA[<?php the_excerpt_rss() ?>]]></content:encoded>
                        <?php rss_enclosure(); ?>
                        <?php do_action('rss2_item'); ?>
                </item>
        <?php endwhile; ?>
</channel>
</rss>

Ahora puede cambiar el nombre de su feed RSS personalizado por el que desee sustituyendo el texto Feed después de la línea add_feed del código.

Una vez que haya creado este feed, podrá verlo accediendo a la URL sudominio.com/feed/nombredelfeed.

Type custom feed name in the code

A continuación, desplácese hasta la sección de inserción y elija el modo “Inserción automática”.

El feed RSS personalizado se creará automáticamente al activar el código.

Choose an insertion method

Por último, desplázate hasta la parte superior y activa el conmutador “Inactivo”.

A continuación, haz clic en el botón “Guardar fragmento de código” para establecer los ajustes.

Save the custom RSS feed custom snippet

Una vez hecho esto, visite la página Ajustes ” Enlaces permanentes desde el escritorio de WordPress.

Aquí, basta con hacer clic en el botón “Guardar cambios” para borrar las reglas de reescritura y generar nuevos enlaces permanentes para su sitio web.

Check Permalinks

Ahora podrá ver su feed RSS personalizado visitando la URL yourdomain.com/feed/feedname.

He aquí un ejemplo de feed RSS personalizado en nuestro sitio web WordPress de demostración:

Custom RSS feed preview

Bonificación: diagnosticar problemas de feed RSS personalizado

A continuación se enumeran algunos errores que pueden producirse al intentar crear un feed RSS personalizado y cómo puede solucionarlos.

Recibo un error 404 al intentar ver mi feed.

Si obtiene el error 404 al intentar ver su feed personalizado, compruebe si está utilizando el nombre de feed correcto en su URL.

Tiene que ser el que proporcionó en la función add_feed. Si tienes el feedname correcto, puede que tus reglas de reescritura no se hayan cargado correctamente. Puede hacerlo fácilmente guardando de nuevo sus enlaces permanentes.

Si ha guardado de nuevo sus enlaces permanentes y el problema persiste, entonces puede forzar una descarga de reescritura añadiendo este código en su fragmento de código WPCode junto a la función add_feed:

global $wp_rewrite;
$wp_rewrite->flush_rules();

¡Mi feed no se valida!

El W3C ofrece un servicio de validación de feeds que permite validar el feed resultante y proporciona detalles específicos sobre los puntos en los que el feed no se valida.

A continuación, puede editar fácilmente el fragmento de código para resolver estos problemas / conflictos / incidencias.

Recibo un error de validación de <idioma>.

Esto es común cuando el idioma RSS no ha sido configurado en su instalación de WordPress.

Para ello, puede añadir el siguiente código a WPCode para actualizar la opción de idioma:

function rssLanguage(){
        update_option('rss_language', 'en');
}
add_action('admin_init', 'rssLanguage');

Una vez hecho esto, edite el segundo argumento de la función update_option para cambiar el idioma por el obligatorio / requerido / necesario. Marque / compruebe la lista completa de códigos de idioma RSS.

Una vez que guarde el fragmento de código, se eliminará el error y podrá ver su feed RSS personalizado.

Esperamos que este artículo te haya ayudado a aprender cómo crear un feed RSS personalizado en WordPress. Puede que también quieras ver nuestro tutorial sobre cómo hacer feeds RSS separados para cada categoría y nuestros consejos de experto para optimizar tus feeds RSS en WordPress.

If you liked this article, then please subscribe to our YouTube Channel for WordPress video tutorials. You can also find us on Twitter and Facebook.

Descargo: Nuestro contenido está apoyado por los lectores. Esto significa que si hace clic en algunos de nuestros enlaces, podemos ganar una comisión. Vea cómo se financia WPBeginner , por qué es importante, y cómo puede apoyarnos. Aquí está nuestro proceso editorial .

Avatar

Editorial Staff at WPBeginner is a team of WordPress experts led by Syed Balkhi with over 16 years of experience in WordPress, Web Hosting, eCommerce, SEO, and Marketing. Started in 2009, WPBeginner is now the largest free WordPress resource site in the industry and is often referred to as the Wikipedia for WordPress.

El último kit de herramientas de WordPress

Obtenga acceso GRATUITO a nuestro kit de herramientas - una colección de productos y recursos relacionados con WordPress que todo profesional debería tener!

Reader Interactions

69 comentariosDeja una respuesta

  1. Syed Balkhi says

    Hey WPBeginner readers,
    Did you know you can win exciting prizes by commenting on WPBeginner?
    Every month, our top blog commenters will win HUGE rewards, including premium WordPress plugin licenses and cash prizes.
    You can get more details about the contest from here.
    Start sharing your thoughts below to stand a chance to win!

  2. Jonathan says

    Following this tutorial, for some reason changing the $postCount does not work.

    Eg,
    $postCount = 20; // The number of posts to show in the feed

    Only by changing the default number inside of WordPress Reading settings does it work. Very weird. How do we overwrite the wordpress settings, or stop the wordpress settings from overriding our code?

    • WPBeginner Support says

      Your specific theme may be overriding the number of posts to show, we would first recommend checking with the support for your specific theme and they should be able to assist.

      Administrador

  3. Dexter Nelson says

    Is there any way to make this permanent? I keep having to repeat this step every few weeks when the theme is updated.

  4. John Snyder says

    I need to create an XML feed for a specific page on my WordPress website. Here is the page will I have to edit my functions.php file or is there an easier way?

  5. Alok Shrestha says

    Hello,

    This article is very helpful but I got some issue.

    I did exactly like in your code. But it gives me an error as
    This page contains the following errors:

    error on line 1 at column 7: XML declaration allowed only at the start of the document
    Below is a rendering of the page up to the first error.

    Could you please help me out what could possibly go wrong here?
    This is very important for me.

    Thank you.

  6. Guillermo says

    Hi, is it possible to change de order of the posts in my feeds without creating a new custom feed? I want to use the current feed files but just want to change the displayed order of theme. Using PHP queries as an example, changing order from DESC to RAND()

    I will appreciate you help. Thanks.

  7. Jeremy says

    Great post! I definitely fall under the rookie status. Many feed readers/aggregators don’t seems to like the /feed/ URL structure, even through the xml returned validates. Is there a way to append the url to end with rss.xml?

  8. JDURAN says

    Sorry to say, however, implementing the codes for custom rss has effectively wiped out my entire blog. Having to do a restore and it is taking a long time to get my blog back up. Any advise?

    • Mark says

      You need to connect to your site via FTP or your hosting’s file browser in cPanel, and simply remove what you added. If you added the code as a custom plugin, then just rename the plugin folder. If you added the code in functions.php, edit the file and remove the code. Don’t forget to backup the file before editing. Hope this helps for the next time.

  9. DrLightman says

    Never mind, it does. I had a bug with YOAST SEO that with the /category/ prefix removal. I have warned them of it I hope they will fix it.

  10. DrLightman says

    Hello, thank you for the article, but it seems this will only work for the main site feed, not for the specific catgories feeds:

    mysite.com/category/mycat/feed/feedname/

  11. Manuel says

    Doesn’t work anymore.
    I got a 404 error, so I activated debug mode. Debug mode says “Notice: The Called Constructor Method For WP_Widget Is Deprecated Since Version 4.3.0! Use __construct()”

  12. git says

    unfortunately this is restricted in its usefulness. inserting screenshots and sample pages would be very helpful, particularly for amateurs/rookies like me.

  13. CT says

    Please see below screenshots – what determines the “…” or “[…]” or “Read More ->” etc etc in feeds?

    I’m using the default /feed in 2 different WP sites & these 2 screenshots obviously are showing something different at the end of their excerpts. Thanks!

  14. CT says

    Apologizes but that code did not come through clear lol. Lets try that again. Go here to see the exact, raw code I’m looking to remove:

  15. Neha says

    Hello,

    When I try to view the feed I got 404 Page not found error. I am trying to add code:

    global $wp_rewrite;
    $wp_rewrite->flush_rules();

    then I also got same error. Could this be why?

    • Jon Harvey says

      Got it to work neatly thanks to birgire at Stack exchange:

      add_action( ‘init’, ‘custom_feeds’ );

      function custom_feeds()
      {
      foreach( array( ‘feedname1’, ‘feedname2’ ) as $name )
      {
      add_feed( $name,
      function() use ( $name )
      {
      get_template_part( ‘rss’, $name );
      }
      );
      }
      }

  16. Neal Pope says

    The “follow” button shows up at the bottom right corner when viewing posts on a personal computer, but does not appear when viewing on a mobile devise (smartphone) (unless I’m just missing it.

  17. Jeff says

    Sorry, but everything about this is misleading. this is not “beginner” work. and it is not worded for beginners. This is totally irresponsible and can cause major issues to people’s websites.

  18. Christine says

    I got this working (kind of). The feed page exists, but will not validate and says there is an error on line 1.

    I copied the code exactly from this page and haven’t changed anything. What could be going wrong here?

    • Flávia says

      W3 will not validate mine as well and says there is an error on line 17.

      And I am getting the 404 page!

      What should I do?

  19. Eugene Asiamah says

    Hello,

    Please i need help in configuring my rss to show all my post content on not just an excerpt of it.

    Thank you.

  20. Georgi says

    Hello,
    I need to show only date without time for pubDate. When I use

    It’s doesn’t work for firefox,IE.
    Can you help me?

    Thank you in advance!

  21. Jan-Philipp says

    Hi.

    I would like to change the update pattern of the feed with

    sy:updatePeriod
    echo apply_filters( ‘rss_update_period’, ‘weekly’ );
    /sy:updatePeriod

    sy:updateFrequency
    echo apply_filters( ‘rss_update_frequency’, ‘1’ );
    /sy:updateFrequency>

    sy:updateBase
    2015-03-29T01:00:00+09:00
    /sy:updateBase

    But whatever I tried, it automatically adds a new post when I publish it and does not wait till Sunday ( as defined in the code above) to add it to the RSS.

    Do you have any suggestions? Do I maybe need to find a solution within the WP Query?

    Your help would be much appriciated.

  22. Jan-Philipp says

    Hi.

    I would like to change the update pattern of the feed with

    2015-03-29T01:00:00+09:00

    But whatever I tried, it automatically adds a new post when I publish it and does not wait till Sunday ( as defined in the code above) to add it to the RSS.

    Do you have any suggestions? Do I maybe need to find a solution within the WP Query?

    Your help would be much appriciated.

  23. Issabellla says

    Hi.I try to do as your mention but I’ve seen my site cannot access to the feed page.This is My site I try to use /feed and a lot of word which is mention in wordpress.com or wordpress.org even in the google.Please help me.

  24. xuamox says

    What determines that the feed will be displayed at feed/feedname? I have tried to follow the tutorial, but not luck at all. The feed is not publishing at feed/feedname.php

  25. Wouter Bertels says

    Following these exact steps I got this error:

    Fatal error: Cannot redeclare get_bloginfo_rss() (previously
    declared in
    /home/public_html/wp-includes/feed.php:25)
    in /home/public_html/wp-content/themes/xxx/rss-name.php on line 39

  26. George says

    Hi,

    My feed is OK when this code is added:

    global $wp_rewrite;
    $wp_rewrite->flush_rules();

    and returns a 404 when it is removed.
    I only remove it as per your instructions, which is to remove it after reloading wordpress.

    At this moment I am testing it on my local server. Could this be why?

  27. ybmgryzzz says

    Hi there. Thanks for this post! Really appreciated. Worked well at first go! :)

    I would also like some assistance as Brian below. For the full text in the RSS instead of the post excerpt.

    Thanks in advance.

  28. Brian says

    I am trying to add a second RSS feed that is full text (my first RSS feed is summary). If I wanted this custom RSS feed to be full text instead of summary excerpt, what would I change?

    Thanks so much!

  29. Steve Marks says

    Thanks for this. Just what I was looking for!

    I had an issue when I used add_feed(). I could view the RSS feed in the browser absolutely fine, but it would return a 404 when I entered the URL into a third party application (ie. MailChimp, W3C feed validator etc). I had tried flushing the permalinks etc.

    The only way I could get round the issue was to create a new blank page and select the template as the one you’ve outlined in this article.

    Not sure why it didn’t work, but hopefully this offers a viable solution for others in this situation.

    Thanks again!

  30. Josh McClanahan says

    Your article is right on the path of what I was looking for. One question I have (as a noob to RSS), how can I add a link to an RSS feed?
    The site that I need this for is a church and would like to have a custom feed that would make it easier for our members to be alerted to newly posted sermon posts (that have mp3 download links).
    Currently, the feed shows the text for the links that I have created on the posts for the sermons. But it only acts as text. Any help would be appreciated.

    • Josh McClanahan says

      Just noticed that I didn’t ask my question correctly.
      What I was trying to ask was, how can I display a link in the RSS Feed? The links that are in the content of my posts are broken in the feed.
      Thanks for your help and this article.

    • Josh McClanahan says

      Still curious, if anyone knows why my links would be broken and only show as plain text in a feed?
      To see what I mean checkout: http://amfmchurch.com/feed
      You will see “Download” in plain text. I would like to make it so that people can click the anchor link and download the mp3. This works find on the actual site.

      Thanks for any help.

  31. Neil says

    Hi, I have the default rss feed.. but I would like to be able to either reduce the size of the images from what is displayed in the post…. (to a maximujm width of 265px) OR to just use the post thumbnail in the rss.

    Is either of the above possible?

    The reason I am looking to do this is that my RSS feeds an APP and the APP will only display images up to 265px in width (before horizontal scrolling) and 265px is very limiting for online/pc blog posts…

  32. Cathy Finn-Derecki says

    Thank you for this! I am making a custom RSS location part of a plugin I’m developing. As a result, I have included the text for the custom RSS in the function, not in a theme template. It’s working. However, it does not seem to work when I want to restrict the feed to a category. It gives all posts regardless. Any thoughts?

  33. Alexis says

    Hello,

    Thank you, these explanations are really useful. I just used it to customize my feed so I could put an image in mailchimp’s “RSS to email” feature.

    Thank you very much !

  34. the Off says

    Hello,

    Till yesterday afternoon, my WordPress (version 3.6.1) blog http://theoff.info/wordpress/ had no problem. And I successfully added new plugins.

    In the night, problems started: (1) I could not login. (2) the RSS feed http://theoff.info/wordpress/?feed=rss2 got corrupted. The feed failed validation.

    I searched the Web and WordPress Support Forum for solutions. I tried the following:
    (i) successfully reset the password
    (ii) deleted new plugins from ftp
    (iii) renamed Theme folder by adding “-old” and plugin folder by adding “-hold” from ftp

    Then I could login and up grade to 3.7.1 version and make changes to the blog.

    However, login is still an issue. Every time I am following method mentioned in step (iii) to login.

    RSS still does not validate.

    Could you help in resolving both login and RSS feed problems?

    Note: My webhost does not offer technical help. I am not an IT professional i.e. I have very little technical knowledge.

    Thanks

    • WPBeginner Support says

      It is difficult to figure out. Here is one thing you can try.

      1. Using FTP download your plugins to your computer for backup and then delete your plugins directory.
      2. Create a new plugins directory.
      3. Install and all your plugins one by one by downloading fresh copy of the plugin from the source. After you activate each plugin log out and and log back in to see if the problem occurs again. You will probably find a plugin that may be causing the problem or you wont. This could mean that a plugin file on your site may have been compromised.

      If this process does not help you, repeat this process process with your themes as well. If you have made a lot of changes to your existing themes then you might want to back it up on your computer by downloading theme folder through FTP. Then delete themes folder from your webserver and create a new themes directory in wp-content folder on your server. From WordPress admin area download and install a fresh copy of default twenty thirteen theme.

      Let us know what happens when you do all that. Make Sure to Backup your Site first.

      Administrador

  35. Bertrand says

    Hello,

    When I try to open the new feed, I get an error message:

    Fatal error: Call to undefined function query_posts() in /xxxx/wp-content/themes/xxx/rss-feedname.php on line 6

    I tried on localhost and web hosting, it is the same…

    How can I fix it?

    Thanks

Deja tu comentario

Gracias por elegir dejar un comentario. Tenga en cuenta que todos los comentarios son moderados de acuerdo con nuestros política de comentarios, y su dirección de correo electrónico NO será publicada. Por favor, NO utilice palabras clave en el campo de nombre. Tengamos una conversación personal y significativa.