WordPress.org

Support

Support » Plugins and Hacks » [Resolved] og:url does not point to canonical URL

[Resolved] og:url does not point to canonical URL

  • When a post URL contains query string parameters (for example, Analytics campaign tracking utm_source, etc), the URL that is set in og:url is the same exact URL that was requested (lines 649-650):

    $og['og:url'] = empty( $_SERVER['HTTPS'] ) ? 'http://' : 'https://';
    $og['og:url'] .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];

    If we set the canonical URL instead, we will not lose Facebook likes when users access the page with different GET parameters:

    $og['og:url'] = get_permalink( $post->ID );

    Could it be merged to trunk?
    Best regards!

Viewing 3 replies - 1 through 3 (of 3 total)
  • Plugin Author JS Morisset

    @jsmoriss

    Ah, hadn’t thought of that. 😉 The problem is that section is used for a variety of pages, including indexes, categories, etc. So here’s what I went with:

    if ( is_singular() ) $og['og:url'] = get_permalink( $post->ID );
    else $og['og:url'] = $this->get_current_url();
    
    function get_current_url() {
        $url = empty( $_SERVER['HTTPS'] ) ? 'http://' : 'https://';
        $url .= $_SERVER["SERVER_NAME"] .  $_SERVER["REQUEST_URI"];
        // remove the query string
        if ( strpos( $url, "?") !== false )
            $url = reset( explode( '?', $url ) );
        return $url;
    }

    Try out the latest DEV version and let me know if things work better. 😉

    js.

    Great! But removing the entire query string could be dangerous if friendly URL are not set, right? Something like /?p=123 would be converted to /

    This removes only Google tracking parameters. It could be interesting to remove other parameters like pk_campaign and pk_kwd (Piwik campaign tracking), other advertising systems, etc.

    $og['og:url'] = preg_replace('/[\?&](utm_source|utm_medium|utm_campaign|utm_term|gclid)=([^&]+)/i', '', $og['og:url']);
    Plugin Author JS Morisset

    @jsmoriss

    I think /?p=123 would also mean that is_singular() === true

    But just in case, I made the function a little more flexible, as you suggested…

    function get_current_url( $strip_query = 'notrack' ) {
    
          $url = empty( $_SERVER['HTTPS'] ) ? 'http://' : 'https://';
          $url .= $_SERVER["SERVER_NAME"] .  $_SERVER["REQUEST_URI"];
    
          switch ( $strip_query ) {
            case 'noquery' :
              if ( strpos( $url, '?' ) !== false )
                $url = reset( explode( '?', $url ) );
              break;
            case 'notrack' :
              $url = preg_replace( '/([\?&])(utm_source|utm_medium|utm_campaign|utm_term|gclid|pk_campaign|pk_kwd)=[^&]*&?/i', '$1', $url );
              break;
          }

    Thanks,

    js.

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘[Resolved] og:url does not point to canonical URL’ is closed to new replies.