Use production URL when in development or staging

You can modify what URL is used to find share counts, and what URL is shared when a share button is clicked.

This is useful when you’re building a website locally or in a staging environment and want to see the actual counts for the production (live) version of a post.

This code snippet goes in a core functionality plugin or Code Snippets.

/**
 * Production URL 
 * @author Bill Erickson
 * @link https://sharedcountsplugin.com/2019/03/27/use-production-url-when-in-development-or-staging/
 * 
 * @param string $url (optional), URL to convert to production.
 * @return string $url, converted to production. Uses home_url() if no url provided 
 *
 */
function ea_production_url( $url = false ) {
	// Make it protocol-agnostic, for preserving http requests
	$production = '://www.billerickson.net';

	$url = $url ? esc_url( $url ) : home_url();
	$home = str_replace( array( 'http://', 'https://' ), '://', home_url() );
	$url = str_replace( $home, $production, $url );
	
	return esc_url( $url );	
}

/**
 * Use Production URL for Share Count API
 * @author Bill Erickson
 * @link http://www.billerickson.net/code/use-production-url-in-shared-counts/
 * 
 * @param array $params, API parameters used when fetching share counts
 * @return array
 */
function ea_production_url_share_count_api( $params ) {
	$params['url'] = ea_production_url( $params['url'] );
	return $params;
}
add_filter( 'shared_counts_api_params', 'ea_production_url_share_count_api' );

/**
 * Use Production URL for Share Count link
 * @author Bill Erickson
 * @link http://www.billerickson.net/code/use-production-url-in-shared-counts/
 *
 * @param array $link, elements of the link
 * @return array
 */
function ea_production_url_share_count_link( $link ) {
	$exclude = array( 'print', 'email' );
	if( ! in_array( $link['type'], $exclude ) )
		$link['link'] = ea_production_url( $link['link'] );
	return $link;
}
add_filter( 'shared_counts_link', 'ea_production_url_share_count_link' );

Filters used:

Published by Bill Erickson

Bill Erickson is a freelance WordPress developer and a contributor to the Genesis framework. For the past 14 years he has worked with attorneys, publishers, corporations, and non-profits, building custom websites tailored to their needs and goals.