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 adicionar um link “Leia mais” ao texto copiado no 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.

Você deve ter notado que alguns sites populares (como o eHow etc.) anexam um link “leia mais” a qualquer texto copiado do site deles. Essa é uma ótima maneira de conseguir novos usuários. Muitas vezes, as pessoas copiam e colam textos de sites em e-mails. Alguns usam isso para salvar as informações para o futuro, enquanto outros estão apenas compartilhando-as com seus amigos, familiares e colegas. Neste artigo, mostraremos como você pode adicionar facilmente um link “leia mais” a qualquer texto copiado do seu blog do WordPress, para que você possa obter tráfego adicional.

Observação: Para ver isso em ação, copie qualquer coisa desta postagem e cole-a em seu e-mail ou bloco de notas.

A primeira coisa que você precisa fazer é copiar o seguinte código no arquivo functions.php do seu tema ou em um plug-in específico do site:


function add_copyright_text() {
	if (is_single()) { ?>

<script type='text/javascript'>
function addLink() {
	if (
window.getSelection().containsNode(
document.getElementsByClassName('entry-content')[0], true)) {
    var body_element = document.getElementsByTagName('body')[0];
    var selection;
    selection = window.getSelection();
	var oldselection = selection
    var pagelink = "<br /><br /> Read more at WPBeginner: <?php the_title(); ?> <a href='<?php echo wp_get_shortlink(get_the_ID()); ?>'><?php echo wp_get_shortlink(get_the_ID()); ?></a>"; //Change this if you like
    var copy_text = selection + pagelink;
    var new_div = document.createElement('div');
	new_div.style.left='-99999px';
	new_div.style.position='absolute';

    body_element.appendChild(new_div );
    new_div.innerHTML = copy_text ;
    selection.selectAllChildren(new_div );
    window.setTimeout(function() {
        body_element.removeChild(new_div );
    },0);
}
}


document.oncopy = addLink;
</script>

<?php
}
}

add_action( 'wp_head', 'add_copyright_text');

Agora, sempre que alguém acessar seu site e tentar copiar seu conteúdo, um link para ler mais será incluído junto com ele. Não se esqueça de alterar o texto de copyright e adicionar o título de seu próprio site.

Editar: Inicialmente, estávamos pegando o URL da janela, mas um de nossos usuários apontou que isso fazia com que os URLs parecessem desajeitados. Atualizamos o código para mostrá-lo somente em páginas de postagem única e usar wp_shortlink. Portanto, ele usaria algo assim: yoursite.com/?p=23. Se você estiver usando um shortlink personalizado, como nós: wpbeg.in, ele mostrará o shortlink da marca.

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

60 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. Bee says

    Hi,
    this code does not seem to work, neither on your website here nor on my website using your snippet (WP 6.2). Could you please check this? Thank you.

    • WPBeginner Support says

      The code is still working for us, we would recommend trying to disable any plugins and/or using an incognito browser to prevent addons to see if one may be causing a conflict.

      Administrador

  3. Junuk says

    Hi, Thank you for your good information!

    I applied the code you have told me with BItly plugin to my website, but it works sometimes and doesn’t work sometimes.

    Does this code have relation with Cache plug-in? Can you tell me where in my website I should take a look?

  4. Pierre says

    Hi,

    Thanks, it’s work fine on article on 2019, but it’s possible to make it work on custom post type?

    I have Eventon and WP News and Scrolling Widgets.

    • WPBeginner Support says

      You would need to modify the is_single to is_singular and add the name of your custom post type

      Administrador

  5. Will says

    Do you have any advice on how to add Google tracking parameters to the end of each URL? Considering you’re already using ?p= for the post name at the end.

  6. Jasmine says

    Thanks for this, it works great for posts but when text is copied from events it doesn’t pull the URL of the page through – any advice? Thanks.

    • Michele says

      This is awesome. Thanks. When it says class – entry content, that meant it didn’t work for about 90% of the text on my site because my text didn’t use that class name. So if anyone else encounters this problem, you can change “entry content” to “body”. That’s what I did.
      var body_element = document.getElementsByTagName(‘body’)[0]; (line 13)
      Now it works everywhere.

  7. Dave says

    Thank you very much, all the text formatting were changed and pasted as a single line. But I need the text formatting as it is. So please help me in getting this.

  8. Jens | Sir Apfelot says

    Just added the script into my wordpress blog, but I dont get an appendix at the clipbiards end…

    Any ideas? I am not sure, if its because I am working on a mac… but I guess the javascript should work on Firefox on a mac too… :-(

  9. Yash Jhade says

    While pasting it to blogger following error comes
    Error parsing XML, line 2237, column 96: The value of attribute “href” associated with an element type “a” must not contain the ‘<' character.
    Any Solutions ?
    Thanks.

  10. matt says

    this feature makes copying and pasting more frustrating. For instance, if I copy and paste a headline for editing Wikipedia it can mess up formatting if I’m not careful and requires extra work.

  11. Alyson says

    Unfortunately, the code does not work with WP 3.8

    I have tested it on a fresh install. Please feel free to confirm this. Do you have any plans to update the code to make it function?

    • Roselle says

      Hello,

      At first, I could not get this to work. But upon close examination, I figured out the culprit:

      On the 8th line of the code, you’ll see this:
      document.getElementsByClassName(‘entry-content’)[0], true))

      This is the line that tells the code, “hey, if anyone copies text from text with this class name, then put a read more link”

      All you need to do is use Firebug to figure out what class name your post content is under.

      I have a child theme that I’ve edited over and over again, so mine wasn’t the default, “entry-content”. I suspect your class name is different from that also.

      Good luck,
      Roselle

  12. Gabriel says

    Hello,

    Many thanks for this great article, but I have a problem. I would like to get the permalink and not the shorthen link. Anyone can tell me how can I do that?

    Cheers

    • Editorial Staff says

      Yes it is possible. Change the selector tag from body to a div ID or what not. I have put the request in. Our developers will let me know, so I can update the article.

      Administrador

      • Lorenzo Solís says

        Thanks. I’ve just tried with var div = document.getElementById(‘copyright’); in the line number 6 and adding de id=”copyright” to the div content, but I get the same result as with your code. Sorry, I am not a programmer.

  13. Lisa says

    Interesting and useful; however, I was surprised that the copy test did not work (for me at least) when composing an email in Gmail — nothing showed after pasting the copied text, and the body text area in the compose email window just froze. Testing a copied bit in Notepad worked just fine, so I don’t know what the issue might be with Gmail.

    Thanks for the tip!

  14. Albert Albs says

    That is good option Syed. Thanks for sharing. But if we can able to print short URL of the post means, that is even better for website owners.

    Currently it is printing long URL. If I came here by Feedburner newsletter subscription, the UTM tracking url also coming.

    Hope you understand. Is it possible?

      • Albert Albs says

        That is fast and smart.

        One Question: Why you removed Author URL in the comment form? Always, I’m seeing, many of the WordPress powered blogs will give credit to the comment author at URL field with NoFollow attribute.

        Is there any specific reason for removing Author URI field? Or are there any experiments for Penguin update?

        Between, I’m not getting any comment notification, even after selecting the “Notify me of followup comments via e-mail” option.

  15. Gabe Diaz says

    Wow, now this is a great tip! Makes it easy to quote and show attribution as well as drops a link for those who skim and steal content. Very cool!

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.