• Resolved carlosrms

    (@carlosrms)


    I have WordPress and I would like that all visitors who access my site by searching in google (traffic source), go directly to a specific part of the page (focus).

    To focus on this part, I need to include the anchor at the end of the url: #welcome-source-google https://example.com/category/page-or-post/#welcome-source-google

    I think I need to insert this code, probably in functions.php:

    function organic_source_anchor() {
      if (preg_match('/(www\\.)?google\\./', $_SERVER['HTTP_REFERER'])) {
        wp_redirect( get_permalink( $postID ) . '#welcome-source-google' );
        exit;
      }
    add_action( 'template_redirect', 'organic_source_anchor' );

    I got this code by researching, but since I am not a programmer, I believe there are several errors or maybe I need to put the code out of functions. A problem that happens is that I didn’t want to disable the cache, as this frame appears to all visitors, but if the source is from google, I wanted the focus on the part this page.

Viewing 4 replies - 1 through 4 (of 4 total)
  • Moderator bcworkz

    (@bcworkz)

    Appending to the permalink like that is fine. The problem is $postID is out of scope and will not have a valid value. You can use get_queried_object_id() in its place, but this introduces a different problem. Not all requests will result in an ID for the queried object. Like requesting the blog listing page. Also, maybe some pages would not have a welcome-source-google ID value. I suspect you will need more conditional checks beyond whether the referrer is from Google or not.

    Thread Starter carlosrms

    (@carlosrms)

    Thank you so much for your answer @bcworkz
    and is it not possible to just get the URL of the current page and if the source is from google add the anchor?
    example: wordpress link: site.com/category/post-name-date#anchor

    Only add #anchor in all links.

    Thank you!

    Moderator bcworkz

    (@bcworkz)

    Sure, good idea! You can get it from $_SERVER['REQUEST_URI'].

    Would every page always have an element with welcome-source-google ID attribute? I suppose it’s not a big deal if a few didn’t. The added parameter is then ignored.

    Thread Starter carlosrms

    (@carlosrms)

    Perfect @bcworkz !!!
    It worked
    Thank you very much

Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘How to add #anchor at the end of the WordPress URL’ is closed to new replies.