I would turn this into a function to account for all conditions. Take the following:
function generate_facebook_sharer_link( $label = 'Share this on Facebook', $classes = '', $return = false ){
if( is_singular() ){
// If is a Single CPT, Post, Page, etc.
$url = get_permalink();
$title = get_the_title();
} else if( is_front_page() ){
// If this is the "Main Page"
$url = home_url();
$title = get_bloginfo( 'title' );
} else {
// All other Accounts (Archives, Blog Page, etc.)
$url = ( is_ssl() ? 'https://' : 'http://') . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
$title = get_bloginfo( 'title' );
}
$output = sprintf( '<a class="%s" href="http://www.facebook.com/sharer.php?u=%s&t=%s" target="_blank" rel="noopener noreferrer">%s</a>', $classes, urlencode( $url ), urlencode( $title ), $label );
// Allow returning, default to echoing
if( $return == true )
return $output;
echo $output;
}
This will output a link wherever generate_facebook_sharer_link();
is called. The is_singular()
should catch all Custom Post Types, Posts, Pages, etc. is_front_page()
will catch if it's the "main page", regardless of what the Reading Settings/Blog Page are, and then it falls back to building the current URI with appropriate protocol and setting the blog title.
This could also very simply be turned into a shortcode:
add_shortcode( 'facebook_share_link', function( $atts ){
// Extract and Define Defaults
extract( shortcode_atts( array(
'label' => 'Share this on Facebook',
'classes' => '',
), $atts ) );
if( is_singular() ){
// If is a Single CPT, Post, Page, etc.
$url = get_permalink();
$title = get_the_title();
} else if( is_front_page() ){
// If this is the "Main Page"
$url = home_url();
$title = get_bloginfo( 'title' );
} else {
// All other Accounts (Archives, Blog Page, etc.)
$url = ( is_ssl() ? 'https://' : 'http://') . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
$title = get_bloginfo( 'title' );
}
$output = sprintf( '<a class="%s" href="http://www.facebook.com/sharer.php?u=%s&t=%s" target="_blank" rel="noopener noreferrer">%s</a>', $classes, urlencode( $url ), urlencode( $title ), $label );
return $output;
} );
Which would allow you to plop [facebook_share_link]
wherever you'd like it to show up.