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

Como personalizar completamente seus RSS Feeds do WordPress

Nota editorial: Ganhamos uma comissão de links de parceiros no WPBeginner. As comissões não afetam as opiniões ou avaliações de nossos editores. Saiba mais sobre Processo editorial.

Deseja adicionar conteúdo aos feeds RSS do WordPress?

RSS significa “Really Simple Syndication”, e os feeds RSS do WordPress mostram seu conteúdo mais recente. No entanto, por padrão, não há opção para personalizar esse conteúdo para os usuários do seu feed RSS.

Neste artigo, mostraremos como adicionar conteúdo facilmente e manipular completamente os feeds RSS do WordPress.

Adding custom content to your WordPress RSS feeds

Aqui está uma rápida visão geral dos assuntos que abordaremos neste artigo:

Adicionar conteúdo personalizado aos feeds RSS do WordPress (maneira fácil)

A maneira mais fácil de adicionar conteúdo personalizado do site aos feeds RSS do WordPress é usar o plug-in All in One SEO. Ele é o melhor plugin de SEO para WordPress do mercado e permite otimizar facilmente o SEO do seu site.

A primeira coisa que você precisa fazer é instalar e ativar o plug-in All in One SEO. Para obter mais detalhes, consulte nosso guia passo a passo sobre como instalar um plug-in do WordPress.

Após a ativação, você será solicitado a configurar o plug-in. Basta seguir as instruções na tela ou conferir nosso guia sobre como configurar o All in One SEO.

Depois disso, você precisa visitar a página All in One SEO ” General Settings (Configurações gerais do All in One SEO ) e mudar para a guia “RSS Content” (Conteúdo RSS).

Adding custom content to your WordPress RSS feed using All in One SEO

A partir daí, você pode adicionar o conteúdo que deseja exibir antes e depois de cada item do feed RSS.

Você pode usar tags inteligentes para adicionar links e outros metadados ao conteúdo personalizado.

Adding before and after content for each post in your RSS feed

Você também pode usar HTML básico para formatar seu conteúdo personalizado da maneira que desejar.

Quando estiver satisfeito com as alterações, não se esqueça de clicar no botão Save Changes (Salvar alterações).

O All in One SEO agora adicionará seu conteúdo personalizado a cada item de feed RSS.

Adição de conteúdo ao feed RSS do WordPress usando código

O primeiro método mencionado acima é a maneira mais fácil de adicionar conteúdo personalizado aos feeds RSS do WordPress. Entretanto, ele adiciona conteúdo a todos os itens em seu feed do WordPress.

E se você quisesse adicionar conteúdo a posts específicos, posts em categorias selecionadas ou exibir metadados personalizados em seu feed RSS?

As próximas etapas o ajudarão a adicionar conteúdo de forma flexível ao seu feed RSS usando trechos de código personalizados. Isso não é recomendado para iniciantes.

Você pode adicionar esses trechos de código diretamente ao arquivo functions.php do seu tema. No entanto, recomendamos o uso do plug-in WPCode, pois é a maneira mais fácil de adicionar códigos personalizados ao WordPress sem quebrar seu site.

Ele ainda inclui vários snippets de RSS em sua biblioteca que podem ser ativados com alguns cliques.

Basta instalar e ativar o plug-in gratuito WPCode usando as instruções em nosso guia sobre como instalar um plug-in do WordPress.

Vamos experimentar alguns exemplos de adição manual de conteúdo personalizado nos feeds RSS do WordPress.

1. Adicionar dados de um campo personalizado ao seu feed RSS do WordPress

Os campos personalizados permitem que você adicione metadados extras aos seus posts e páginas do WordPress. No entanto, esses metadados não são incluídos nos feeds RSS por padrão.

Adding custom fields in WordPress

Aqui está um snippet que você pode usar para recuperar e exibir dados de campos personalizados em seu feed RSS do WordPress:

function wpb_rsstutorial_customfield($content) {
global $wp_query;
$postid = $wp_query->post->ID;
$custom_metadata = get_post_meta($postid, 'my_custom_field', true);
if(is_feed()) {
if($custom_metadata !== '') {
// Display custom field data below content
$content = $content."<br /><br /><div>".$custom_metadata."</div>
";
}
else {
$content = $content;
}
}
return $content;
}
add_filter('the_excerpt_rss', 'wpb_rsstutorial_customfield');
add_filter('the_content', 'wpb_rsstutorial_customfield');

Esse código primeiro verifica se o campo personalizado tem dados em seu interior e se o feed RSS personalizado é exibido. Depois disso, ele simplesmente anexa a variável global content e adiciona os dados do campo personalizado abaixo do conteúdo.

2. Adição de texto adicional aos títulos de posts no RSS

Deseja exibir texto adicional ao título de algumas postagens em seu feed RSS? Talvez você queira distinguir entre artigos regulares e posts de convidados ou patrocinados.

Veja como você pode adicionar conteúdo personalizado aos títulos das postagens em seu feed RSS.

Exemplo 1: Como adicionar dados de campos personalizados ao título do post do RSS Feed

Primeiro, você deve salvar o conteúdo que deseja exibir como um campo personalizado. Por exemplo, você pode adicionar os campos personalizados guest_post ou sponsored_post.

Depois disso, você pode adicionar o seguinte código ao seu site:

function wpb_rsstutorial_addtitle($content) {
global $wp_query;
$postid = $wp_query->post->ID;
$gpost = get_post_meta($postid, 'guest_post', true);
$spost = get_post_meta($postid, 'sponsored_post', true);
 
if($gpost !== '') {
$content = 'Guest Post: '.$content;
}
elseif ($spost !== ''){
$content = 'Sponsored Post: '.$content;
}
else {
$content = $content;
}
return $content;
}
add_filter('the_title_rss', 'wpb_rsstutorial_addtitle');

Esse código simplesmente procura os campos personalizados. Se eles não estiverem vazios, ele anexa o valor do campo personalizado ao título do post em seu feed RSS.

Exemplo 2: Como adicionar o nome da categoria ao título da postagem no RSS Feed

Para este exemplo, exibiremos o nome da categoria no título da postagem.

Basta adicionar o seguinte código ao seu site:

function wpb_rsstutorial_titlecat($content) {
$postcat = "";
foreach((get_the_category()) as $cat) {
$postcat .= ' ('.$cat->cat_name . ')';
}
$content = $content.$postcat;
return $content;
}
add_filter('the_title_rss', 'wpb_rsstutorial_titlecat');

Agora, ele mostrará as categorias junto com os títulos das postagens no feed RSS. Por exemplo, “Top New Restaurants in Bay Area (News) (Travel)”, em que News e Travel são categorias.

3. Adicionar conteúdo personalizado a posts com tags ou categorias específicas

Agora, vamos supor que você queira adicionar conteúdo personalizado, mas somente para posts arquivados em tags ou categorias específicas.

O código a seguir o ajudará a adicionar facilmente conteúdo a posts arquivados em categorias e tags específicas:

function wpb_rsstutorial_taxonomies($content) {
 
if( is_feed() ){
 
// Check for posts filed under these categories
if ( has_term( array( 'travel', 'news' ), 'category' ) ) {
 
$content = $content."<br /><br />For special offers please visit our website"; 
 
}
}
return $content;
}
add_filter('the_excerpt_rss', 'wpb_rsstutorial_taxonomies');
add_filter('the_content', 'wpb_rsstutorial_taxonomies');

Você pode modificar esse código para direcionar as tags, bem como quaisquer taxonomias personalizadas.

Aqui está um exemplo de direcionamento de tags específicas:

function wpb_rsstutorial_taxonomies($content) {
 
if( is_feed() ){
 
// Check for posts filed under these categories
if ( has_term( array( 'holidays', 'blackfriday' ), 'post_tag' ) ) {
 
$content = $content."<br /><br />For special offers please visit our website"; 
 
}
}
return $content;
}
add_filter('the_excerpt_rss', 'wpb_rsstutorial_taxonomies');
add_filter('the_content', 'wpb_rsstutorial_taxonomies');

Por padrão, seu feed RSS do WordPress não mostra imagens em destaque para publicações. Você pode adicioná-las facilmente usando um trecho de código que está incluído na biblioteca do WPCode.

Basta navegar até Code Snippets ” + Add Snippet e, em seguida, pesquisar “rss” na biblioteca.

Em seguida, passe o mouse sobre o snippet denominado “Add Featured Images to RSS Feeds” e clique no botão “Use Snippet”.

WPCode Includes a Snippet to Add Featured Images to Your RSS Feed

Agora, tudo o que você precisa fazer é alternar a opção “Active” (Ativo) para a posição “On” (Ligado) e clicar no botão “Update” (Atualizar).

As imagens em destaque agora foram adicionadas aos seus feeds RSS.

Toggle the Active Switch On

Você também pode adicionar manualmente imagens em destaque ao seu feed RSS.

Este é o código que você pode usar:

function wpb_rsstutorial_featuredimage($content) {
global $post;
if(has_post_thumbnail($post->ID)) {
$content = '<p>' . get_the_post_thumbnail($post->ID) .
'</p>' . get_the_content();
}
return $content;
}
add_filter('the_excerpt_rss', 'wpb_rsstutorial_featuredimage');
add_filter('the_content_feed', 'wpb_rsstutorial_featuredimage');

Esse código simplesmente verifica se uma postagem tem uma miniatura (imagem em destaque) e a exibe junto com o restante do conteúdo da postagem

Recursos de bônus sobre a personalização de RSS Feeds do WordPress

Os feeds RSS podem ser uma ferramenta útil para atrair mais usuários e manter o engajamento dos assinantes existentes. Aqui estão alguns recursos que o ajudarão a otimizar ainda mais seus feeds do WordPress:

Esperamos que este artigo tenha ajudado você a aprender como adicionar conteúdo aos seus feeds RSS do WordPress. Talvez você também queira ver nosso guia sobre como adicionar assinaturas de e-mail ao seu blog do WordPress ou nossa seleção de especialistas sobre os melhores plug-ins de diretório comercial do WordPress.

Se você gostou deste artigo, inscreva-se em nosso canal do YouTube para receber tutoriais em vídeo sobre o WordPress. Você também pode nos encontrar no Twitter e no Facebook.

Divulgação: Nosso conteúdo é apoiado pelo leitor. Isso significa que, se você clicar em alguns de nossos links, poderemos receber uma comissão. Veja como o WPBeginner é financiado, por que isso é importante e como você pode nos apoiar. Aqui está nosso processo 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.

O kit de ferramentas definitivo WordPress

Obtenha acesso GRATUITO ao nosso kit de ferramentas - uma coleção de produtos e recursos relacionados ao WordPress que todo profissional deve ter!

Reader Interactions

39 ComentáriosDeixe uma resposta

  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. Roberto Diaz says

    Hi guys, I am trying to add the featured image by default to RSS posts and I have 2 questions:

    1. Where exactly do you add the code you mention?
    2. In your code I see “function wpb_rsstutorial” are we supposed to replace this or any other part of the code with our own parameters?

    Thank you for your help!

    • WPBeginner Support says

      If you check under our ‘Adding Content to WordPress RSS Feed using Code’ section we cover the different methods for adding the code from our guide.

      For the function names, those are not required to be changed unless you want to and if you change it you would want to ensure you change every instance of it with the original name to your new name.

      Administrador

    • WPBeginner Support says

      We do not recommend adding content after every paragraph in your RSS feed at this time.

      Administrador

  3. Macca Sherifi says

    On your RSS feed you’ve got a real simple “To leave a comment please visit [Post Title] on WPBeginner.”

    How do I replicate this? In your code that you’ve supplied, presumably I have to change “coolcustom”, but which one do I edit specifically?

  4. Gretchen Louise says

    I’m trying to use the third option to add the Digg Digg plugin’s buttons to the bottom of my RSS feeds. Any suggestions on editing the content to incorporate PHP rather than just text?

  5. brandy says

    I am trying to use this to implement CSS disclosure buttons in my feed, but I *cannot* figure out how to get it into the description. I have code of what I tried (2 different functions for the excerpt & the post). i hate how the buttons show up in the excerpt and i don’t think it’s necessary. help? :)

  6. Matt says

    I really appreciate you sharing this information with us. I have implemented this on my site now…I always really liked how it looks in your “weekly” emails that I receive.

    I think that it looks very professional and of course it is gonna help fight back against those content scrapers (thieves).

    Again, well written code, and very useful advice. Thank you!

  7. Adam says

    Great info! One question…  on #1 Add a Custom Field to your WordPress RSS Footer, for some reason the content/custom field is displayed twice. Any idea why?

  8. rahul says

    I have problem that in my site if someone fills a contact us form then his all personal info is displayed in rss feed and any user can see it
    plz help !!!!!
     

  9. thehifly says

    I actually got it now. Just edited the “$content = $content.”<br /><br /><div>”.$coolcustom.”</div>n”;” line. Perfect!

  10. thehifly says

    Adding the additional text works great but I’m trying to have the RSS to show only that custom field (for example the “coolcustom”) as the post’s description. Get rid of the actual text of the post. Is that possible?

  11. scot says

    Hi, I’m looking to add two fields to my ‘full’ rss feed. One which displays the author of the post and the other which displays a list of the taxomonies, if any, that the post is in. So let’s say the author is JohnR and the post is in the NFL, Raiders and Jets taxonomies, the RSS would have two additional fields:

    JohnR
    NFL, Raiders, Jets

    Can someone point me in the right direction to get this done?

    – Scot

  12. Agilworld says

    Thanks for sharing…

    Your tutorial is useful to me for verify the Technorati claim token! It worked nicely. I was looking for an effective way to verify it and found articles that discuss about that. But most of it, is not effective. And in the end, thought in my mind how add extra text in each footer post RSS feeds, Great! I found a smart way through your article, Thanks!!

  13. Juri says

    Hi,
    your code to add Custom Fields to RSS works great!!!! Thanks!
    I’m wondering if there is a way to edit the position and not to show the custom fields in the footer but above the title, or under the title, or etc… Is there a chance to add the tag “style” and so use some css?
    Thank you very much

  14. Juri says

    Add a Custom Field to your WordPress RSS Footer:
    THANKS Your code works perfectly. I have a question: How can I edit the position to show custom field up before the title or just after the title?
    I tried to edit the code here:
    $content = $content.””.$coolcustom.”
    “;
    I can remove the br tags and it works but where can I add style and css?

    Thanks for your great help

    • Editorial Staff says

      You would have to use inline styling for the RSS to work on all different readers. To add it before, you will add it like $coolcustom.$content and then add div tags using quotation where you like…

      Administrador

  15. Robert Simpson says

    Hi,

    I’m trying to find a way to use a custom field to EXCLUDE a post from the RSS feed.

    Any ideas?

    Cheers,
    Robert

  16. Zach says

    Hey, thanks for the tutorial. It worked perfectly. Had a quick question though – after I get the extra content to load into the RSS Feed (for example if I’m viewing it in Safari), when I actually embed the RSS Feed on a website, that extra info goes away. Do you have any idea why that would happen? It’s been about 4 days as well – and I’ve tried clearing my cache several times. Thanks!

  17. kiki says

    Thanks for this so far! I haven’t been able to find much on adding custom fields to the RSS feed until now.

    Would it be difficult to add multiple custom fields with the code from section 1? I have an event listing website with custom fields for each post I want to display in the RSS, i.e. “Venue,” “Event Date,” “Address,” et al.

      • Kiki says

        Sorry, I’m a bit of a novice, but what would the code look like to get the multiple custom fields. I’ve tried playing with a few configurations of the code so far but it keeps resulting in errors. One field is working great though!

    • Editorial Staff says

      Ajay but does your plugin allows one to add custom fields in the RSS Text? Because it just seems like that it has the exact same functionality that Joost’s RSS Footer Plugin has which is not what this article is showing. What if you need to display different FTC texts for each post, then plugins like yours and RSS Footer would fail because they show the same text on each post. With this, one can set different ways: For example, if custom field this: Display that otherwise display the default copyright or something like that.

      Administrador

  18. Oscar says

    This is great, it should help out a lot when trying to do quick little customizations. Little bite-sized tips like this are very helpful. I’ve seen people put some of the social media icons at the bottom too, to add to digg, and su and stuff.

Deixe uma resposta

Obrigado por deixar um comentário. Lembre-se de que todos os comentários são moderados de acordo com nossos política de comentários, e seu endereço de e-mail NÃO será publicado. NÃO use palavras-chave no campo do nome. Vamos ter uma conversa pessoal e significativa.