• I’m just starting out with WordPress plugins and I need some advice on my first plugin.

    My WordPress blog has to respond on two different site aliases, e.g. http://www.sitename1.com and http://www.sitename2.com

    It seems all I need to do to make this work is to change the hostname in all internal links, so they link to the host specified in the request headers, instead of using the ‘siteurl’ option from the database.

    I looked for a way to override the siteurl setting, but I couldn’t find one. Then I looked for a way to do a search-and-replace on the entire rendered output, but I couldn’t find that either.

    What I ended up doing was listing every hook that looks like it will have a URL in it, and filtering each one invidividually. It works, but it seems fragile – I might have missed a filter or a new one might get added to WordPress in future.

    Here’s the entire plugin. If anyone can suggest a better way of doing this, I would appreciate it.

    $old_url = get_option('siteurl');
    preg_match('@^http://([^/]+)/@', $old_url, $matches);
    $old_hostname = $matches[1];
    $new_hostname = $_SERVER['SERVER_NAME'];
    
    function fix_site_url($filter_text) {
    	global $old_hostname, $new_hostname;
    	return str_replace($old_hostname, $new_hostname, $filter_text);
    }
    
    if ($old_hostname != $new_hostname) {
    
    	$link_filters = array('admin_user_info_link','attachment_link','author_feed_link','author_link','category_feed_link','category_link','comment_author_email_link','comment_author_link','comment_reply_link','day_link','feed_link','get_attachment_link','get_author_rss_link','get_category_feed_link','get_category_link','get_comment_author_link','get_comment_author_url_link','get_comment_reply_link','get_day_link','get_feed_link','get_link','get_month_link','get_page_link','get_tag_link','get_year_link','manage_link','month_link','next_post_link','page_link','post_comments_feed_link','post_link','post_type_link','pre_link','preview_page_link','preview_post_link','previous_post_link','tag_link','the_author_posts_link','widget_link','year_link','bloginfo_url','comment_author_url','comment_url','get_author_posts_url','get_comment_author_url','get_locale_stylesheet_uri','get_stylesheet_directory_uri','get_stylesheet_uri','get_template_directory_uri','get_theme_root_uri','icon_dir_uri','locale_stylesheet_uri','pre_comment_author_url','pre_link_url','pre_user_url','redirect_url','requested_url','stylesheet_directory_uri','stylesheet_uri','template_directory_uri','theme_root_uri','wp_get_attachment_thumb_url','wp_get_attachment_url');
    
    	foreach ($link_filters as $filter) {
    		add_filter($filter, 'fix_site_url', 100, 1);
    	}
    }

    Thanks

  • The topic ‘Changing hostname in all internal links’ is closed to new replies.