php – Obfuscate links (for SEO purpose)

Question

I ended up making my own system that allows me to obfuscate any link easily.

Add the following code to your child theme’s functions.php file, then just add the class “obfuscate” to any element to obfuscate its link by replacing it with a element with no readable link.

Also be sure to edit styles above, or delet them and style the “akn-obf-link” class in your own CSS file, so that it looks like a link to the visitor.

/*************************************************************************************\
|* Links obuscation - add class "obfuscate" to any <a> element to obfuscate its link *|
\*************************************************************************************/

add_action('wp_loaded', 'buffer_start');
function buffer_start() {
    ob_start('akn_ofbuscate_buffer');
}
add_action('shutdown', 'buffer_end');
function buffer_end() {
    ob_end_flush();
}
function akn_ofbuscate_buffer($buffer) {
    $result = preg_replace_callback('#<a[^>]+(href=(\"|\')([^\"\']*)(\'|\")[^>]+class=(\"|\')[^\'\"]*obfuscate[^\'\"]*(\"|\')|class=(\"|\')[^\'\"]*obfuscate[^\'\"]*(\"|\')[^>]+href=(\"|\')([^\"\']*)(\'|\"))[^>]*>([^<]+)<\/a>#im', function($matches) {
        return '<span class="akn-obf-link" data-o="'.base64_encode($matches[3]?:$matches[10]).'" data-b="'.((strpos(strtolower($matches[0]),'_blank')!==false)?'1':'0').'">'.$matches[12].'</span>';
    }, $buffer);
    return $result;
}
add_action('wp_footer', 'akn_ofbuscate_footer_js');
function akn_ofbuscate_footer_js() {
    ?>
        <script>
            jQuery(document).ready(function($){
                $(document).on('click','.akn-obf-link',function(){
                    var $t = $(this);
                    var link = atob($t.data('o'));
                    var _blank = $t.data('b');
                    if (_blank)
                        window.open(link);
                    else
                        location.href = link;
                });
            });
        </script>
        <style>
            .akn-obf-link {
                color: blue;
                cursor: pointer;
            }
            .akn-obf-link:hover {
                text-decoration: underline;
            }
        </style>
    <?php
}

I’m also sharing the code on this Pastebin: https://pastebin.com/cXEBSVFn

Consider checking the link just in case I updated the code on it and forgot to update it here

0
rAthus 3 months 2022-04-01T10:52:24-05:00 0 Answers 0 views 0

Leave an answer

Browse
Browse