Support

Account

Home Forums General Issues Change canonical tag with custom field

Solving

Change canonical tag with custom field

  • I would like to change the canonical tag for some posts using an ACF custom field.

    I’ve created the field in ACF but having trouble figuring out how to insert it into the <head/> without using a plugin such as Yoast. I have found the following code to put in my functions.php but it is 7 years old. Can anyone confirm that this code would be safe to use?

    /* Begin Rel-canonical by custom fields */
    // A copy of rel_canonical but to allow an override on a custom tag
    function rel_canonical_with_custom_tag_override()
    {
     if( !is_singular() )
     return;
    
     global $wp_the_query;
     if( !$id = $wp_the_query->get_queried_object_id() )
     return;
    
     // check whether the current post has content in the "canonical_url" custom field
     $canonical_url = get_post_meta( $id, 'canonical_url', true );
     if( '' != $canonical_url )
     {
     // trailing slash functions copied from http://core.trac.wordpress.org/attachment/ticket/18660/canonical.6.patch
     $link = user_trailingslashit( trailingslashit( $canonical_url ) );
     }
     else
     {
     $link = get_permalink( $id );
     }
     echo "<link rel='canonical' href='" . esc_url( $link ) . "' />\n";
    }
    
    // remove the default WordPress canonical URL function
    if( function_exists( 'rel_canonical' ) )
    {
     remove_action( 'wp_head', 'rel_canonical' );
    }
    // replace the default WordPress canonical URL function with your own
    add_action( 'wp_head', 'rel_canonical_with_custom_tag_override' );
    /* End Rel-canonical by custom fields */
    
  • I would not use that code.

    The function rel_canonical() calls wp_get_canonical_url(). The value returned from this function is filterable. I would use this hook and create a filter to replace what WP is using. This is how the plugins you’ve mentioned to this.

  • Thanks! There seems to be an ACF-related function on that hook page that looks like it might work so I will test that out.

    function wpdocs_edit_canonical_urls( $original_url, $post ) {
        $override_url = get_post_meta( $post->ID, 'canonical_url', true );
     
        if ( empty( $override_url ) ) {
            return $original_url;
        }
     
        return $override_url;
     
    }
     
    add_filter( 'get_canonical_url', 'wpdocs_edit_canonical_urls', 10, 2 );
    
Viewing 3 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic.