php - Change Attribute Some Links on Content

637

I'm building plugin wordpress for change attribute some links on content of post. I have function like this :

public static function encrypt_link_content( $content ){
    if ( strpos( $content, 'safelinkThis' ) !== false ) {
        // get dom from string of content
        $content = str_get_dom($content);

        // find link with attribute data-role=safelinkThis
        $all_links = $content('a[data-role=safelinkThis]');

        $count_links = count($all_links);
        $i = 0;
        $_links = self::get_links_post($count_links);
        foreach ($all_links as $a) {
            $href = $a->href;
            $encrypt = self::zi_encrypt($href);
            $a->href = $_links[$i]."?link=".$encrypt;
            $i += 1;
        }
        $content = (string) $content;
    }
    return $content;
}

That function is work, Attributehref of link have been changed.

example of content :

Find us on :
<a href="http://facebook.com" data-role="safelinkThis">Go to facebook</a>
<a href="http://google.com" data-role="safelinkThis">Go to google</a>
<a href="http://twitter.com">Go to Twitter</a>

Will be change to like this :

Find us on :
<a href="http://asite.com/page?link=url_encrypted" data-role="safelinkThis">Go to facebook</a>
<a href="http://asite.com/page?link=url_encrypted" data-role="safelinkThis">Go to google</a>
<a href="http://twitter.com">Go to Twitter</a>

I'm usehttp://code.google.com/p/ganon/ library to find dom in string.

Now

I have a custom table for store domain exception, The name iswp_sf_domain. I won't change a link if it have href attribute with domain exception fromwp_sf_domain.

I know, I can use this

global $wpdb;
$sf_table_name = $wpdb->prefix . 'sf_domain';
foreach ($all_links as $a) {
 $href = $a->href;
 $aDomain = parse_url($href)['host'];
 $record = $wpdb->get_results( "SELECT * FROM $sf_table_name WHERE domain='$aDomain'" );
  if(count($record) == 0){
    // change this link
  }
}

But I think this is a bad practice if I have many links on content, I should check one by one to database. How can I compare between host of link on content with list domain in database and change a link attribute href if host of link not include in database?

People are also looking for solutions to the problem: php - How can I go to an address when I click on the logout button

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.