WordPress内容被复制后自动添加文章来源链接

WordPress站点内容被别人复制是常有的事,你可以给你的WordPress站点添加一个功能:内容被复制后,粘贴的时候自动在后面添加文章链接。

来自wp大学的方法:

将下面的代码添加到主题的 functions.php 文件中:

function add_copyright_text() {
  if (is_single()) { ?>
 
<script type='text/javascript'>
  function addLink() {
    if (
  window.getSelection().containsNode(
  document.getElementsByClassName('entry-content')[0], true)) {
          //把entry-content修改为你文章内容的class,如我的是entry
    var body_element = document.getElementsByTagName('body')[0];
    var selection;
    selection = window.getSelection();
    var oldselection = selection
    var pagelink = "<br /><br /> 阅读更多: <?php the_title(); ?> <a href='<?php echo get_permalink(get_the_ID()); ?>'><?php echo get_permalink(get_the_ID()); ?></a>"; //根据你的需要修改这行代码
    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');

你也可以使用纯js的方法:

把下面js代码引用到你的主题中(摘自devework

function addLink() {
    var body_element = document.getElementsByTagName('body')[0];
    var selection;
    selection = window.getSelection();
    var pagelink = "<br /><br /> 转载请注明来源: <a href='"+document.location.href+"'>"+document.location.href+"</a>"; 
    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;