Плавная прокрутка до якоря в WordPress

jQuery(function($) { 

$('a[href^="#"]').on('click',function(event){
    event.preventDefault();
    var target_offset = $(this.hash).offset() ? $(this.hash).offset().top : 0;
    //change this number to create the additional off set        
    var customoffset = 85;
    $('html, body').animate({scrollTop:target_offset - customoffset}, 500);
});

}(jQuery));

Этот пример смещает прокрутку на 85 пикселей посредством customoffset = 85
Для учета по умолчанию наложенного / липкого заголовка. Если ваш заголовок выше, вы должны увеличить это значение (в пикселах).

Вариант:

$(function() {
  $("a[href^='#']").click(function() {
    var _href = $(this).attr("href");
    $("html, body").animate({ scrollTop: $(_href).offset().top + "px" });
    return false;
  });
});

С обновлением хэша в URL-адресе:

jQuery(function($) {
  $('a[href*="#"]').on('click.smoothscroll', function(e) {
    var hash = this.hash,
      _hash = hash.replace(/#/, ''),
      theHref = $(this).attr('href').replace(/#.*/, '');
    if (theHref && location.href.replace(/#.*/, '') != theHref) return;
    var $target = _hash === '' ? $('body') : $(hash + ', a[name="' + _hash + '"]').first();
    if (!$target.length) return;
    e.preventDefault();
    $('html, body').stop().animate({ scrollTop: $target.offset().top - 0 }, 400, 'swing', function() {
      window.location.hash = hash;
    });
  });
});

Eщё варианты:

$(function() {
    $(document).on('click', 'a[href^="#"]', function(event) {
      event.preventDefault();
      $('html, body').animate({
        scrollTop: $($.attr(this, 'href')).offset().top
      }, 500);
    });
  });
jQuery(document).ready(function() {
    var scrollWin = function(selector) {
      jQuery('html, body').animate({
        scrollTop: jQuery(selector).offset().top
      }, 800);
    }
    jQuery("[href^=#]").click(function(e) {
      scrollWin(jQuery(this).attr("href"));
      return false;
    });
  });

С id

$(document).ready(function() {
  $("#div").on("click", "a", function(event) {
    event.preventDefault();
    var id = $(this).attr('href'),
      top = $(id).offset().top;
    $('body,html').animate({ scrollTop: top }, 800);
  });
});

С обновлением хэша в URL-адресе:

$(function() {
    $(window).load(function() {
      var jump = function(e) {
        //prevent the "normal" behaviour which would be a "hard" jump
        e.preventDefault();
        //Get the target
        var target = $(this).attr("href");
        //perform animated scrolling
        $('html,body').animate({
          //get top-position of target-element and set it as scroll target
          scrollTop: $(target).offset().top
          //scrolldelay: 2 seconds
        }, 2000, function() {
          //attach the hash (#jumptarget) to the pageurl
          location.hash = target;
        });
      }
      $(document).ready(function() {
        $('a[href*=#]').bind("click", jump);
        return false;
      });
    });
  });

С обновлением хэша в URL-адресе:

jQuery(function() {
    $('a[href*=#]:not([href=#])').click(function() {
      if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') || location.hostname == this.hostname) {
        var hashStr = this.hash.slice(1);
        var target = $(this.hash);
        target = target.length ? target : $('[name=' + hashStr + ']');
        if (target.length) {
          $('html,body').animate({ scrollTop: target.offset().top }, 1000);
          window.location.hash = hashStr;
          return false;
        }
      }
    });
  });
$(function() {
    /* ADDED: make targets focusable */
    $('target[id]').attr('tabindex', '-1');
    $('a[href*=#]:not([href=#])').click(function() {
      var $linkElem = $(this);
      if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) {
        var target = $(this.hash);
        target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
        if (target.length) {
          $('html,body').animate({
            scrollTop: target.offset().top
          }, 1000, function() {
            /* ADDED: focus the target */
            target.focus();
            /* end ADDED */
            /* ADDED: update the URL */
            window.location.hash = $linkElem.attr('href').substring(1);
            // window.location.hash = $(this).attr('href').substring(1, $(this).attr('href').length);
            /* end ADDED */
          });
          return false;
        }
      }
    });
  });

С обновлением хэша в URL-адресе:

jQuery(function($) {
    jQuery('a[href*=#]:not([href=#])').on('click', function() {
      if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) {
        var target = jQuery(this.hash);
        target = target.length ? target : jQuery('[name=' + this.hash.slice(1) + ']');
        if (target.length) {
          jQuery('html,body').stop().animate({
            scrollTop: target.offset().top
          }, 1000, undefined, function() {
            location.hash = target.selector.substr(1);
          });
          return false;
        }
      }
    });
  });

С обновлением хэша в URL-адресе: и классом:

jQuery(function() {
    $('.scrollto').click(function() {
      if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') || location.hostname == this.hostname) {
        var hashStr = this.hash.slice(1);
        var target = $(this.hash);
        target = target.length ? target : $('[name=' + hashStr + ']');
        if (target.length) {
          $('html,body').animate({ scrollTop: target.offset().top - 20 }, 500);
          window.location.hash = hashStr;
          return false;
        }
      }
    });
  });

С обновлением хэша в URL-адресе:

$(document).ready(function() {
    $('a[href*=#]').bind('click', function(e) {
      e.preventDefault(); //prevent the "normal" behaviour which would be a "hard" jump
      var target = $(this).attr("href"); //Get the target
      // perform animated scrolling by getting top-position of target-element and set it as scroll target
      $('html, body').stop().animate({ scrollTop: $(target).offset().top }, 2000, function() {
        location.hash = target; //attach the hash (#jumptarget) to the pageurl
      });
      return false;
    });
  });

Ещё варианты:

$(document).on('click', 'a[href^="#"]', function (event) {
    event.preventDefault();

    $('html, body').animate({
        scrollTop: $($.attr(this, 'href')).offset().top
    }, 500);
});

Если ваш целевой элемент не имеет идентификатора, и вы связываетесь с ним его name, используйте это:

$('a[href^="#"]').click(function () {
    $('html, body').animate({
        scrollTop: $('[name="' + $.attr(this, 'href').substr(1) + '"]').offset().top
    }, 500);

    return false;
});

Для повышения производительности вам следует кэшировать селектор $('html, body'), чтобы он не запускался каждый раз, когда нажимается якорь:

var $root = $('html, body');

$('a[href^="#"]').click(function () {
    $root.animate({
        scrollTop: $( $.attr(this, 'href') ).offset().top
    }, 500);

    return false;
});

Если вы хотите, чтобы URL-адрес был обновлен, выполните его в обратном вызове animate:

var $root = $('html, body');

$('a[href^="#"]').click(function() {
    var href = $.attr(this, 'href');

    $root.animate({
        scrollTop: $(href).offset().top
    }, 500, function () {
        window.location.hash = href;
    });

    return false;
});

С обновлением хэша в URL-адресе:

$(document).ready(function(){
  // Add smooth scrolling to all links
  $("a").on('click', function(event) {

    // Make sure this.hash has a value before overriding default behavior
    if (this.hash !== "") {
      // Prevent default anchor click behavior
      event.preventDefault();

      // Store hash
      var hash = this.hash;

      // Using jQuery's animate() method to add smooth page scroll
      // The optional number (800) specifies the number of milliseconds it takes to scroll to the specified area
      $('html, body').animate({
        scrollTop: $(hash).offset().top
      }, 1000, function(){
   
        // Add hash (#) to URL when done scrolling (default click behavior)
        window.location.hash = hash;
      });
    } // End if
  });
});

С обновлением хэша в URL-адресе:

// Select all links with hashes
$('a[href*="#"]')
  // Remove links that don't actually link to anything
  .not('[href="#"]')
  .not('[href="#0"]')
  .click(function(event) {
    // On-page links
    if (
      location.pathname.replace(/^\//, "") ==
        this.pathname.replace(/^\//, "") &&
      location.hostname == this.hostname
    ) {
      // Figure out element to scroll to
      var target = $(this.hash);
      target = target.length ? target : $("[name=" + this.hash.slice(1) + "]");
      // Does a scroll target exist?
      if (target.length) {
        // Only prevent default if animation is actually gonna happen
        event.preventDefault();
        $("html, body").animate(
          {
            scrollTop: target.offset().top
          },
          1000,
          function() {
            // Callback after animation
            // Must change focus!
            var $target = $(target);
            $target.focus();
            if ($target.is(":focus")) {
              // Checking if the target was focused
              return false;
            } else {
              $target.attr("tabindex", "-1"); // Adding tabindex for elements not focusable
              $target.focus(); // Set focus again
            }
          }
        );
      }
    }
  });

С обновлением хэша в URL-адресе и плавной прокруткой на новой странице:

/*
-------------------------------------------------
 Smooth Scroll jQuery Plugin 2.0 by Mark D. Adams
 http://www.bigdatamark.com/
-------------------------------------------------
*/
(function($) {
  // Add smooth scrolling to all same page links
  // bind to document for delegations
  $(document).on("click", "a[href*='#']", function(event) {
    function filterPath(string) {
      return string
        .replace(/^\//, "")
        .replace(/(index|default).[a-zA-Z]{3,4}$/, "")
        .replace(/\/$/, "");
    }

    // Make sure this.hash has a value before overriding default behavior
    if (
      this.hash !== "" &&
      filterPath(location.pathname) == filterPath(this.pathname) &&
      location.hostname == this.hostname
    ) {
      // Prevent default anchor click behavior
      event.preventDefault();

      // Store hash
      var hash = this.hash;

      // Using jQuery's animate() method to add smooth page scroll
      // The optional number (800) specifies the number of milliseconds it takes to scroll to the specified area
      $("html, body").animate(
        {
          scrollTop: $(hash).offset().top
        },
        800,
        function() {
          // Add hash (#) to URL when done scrolling (default click behavior)
          window.location.hash = hash;
        }
      );
    } // End if
  });

  // enter new page
  if (location.hash) {
    setTimeout(function() {
      window.scrollTo(0, 0);
    }, 1);

    $(window).on("load", function(event) {
      var hash = location.hash;
      $("html, body").animate(
        {
          scrollTop: $(hash).offset().top
        },
        800,
        function() {
          // Add hash (#) to URL when done scrolling (default click behavior)
          window.location.hash = hash;
        }
      );
    });
  }
})(jQuery);

Библиотека jQuery Address, позволяющая отображать хэш в URL-адресе.
Плагин jQuery.localScroll
Плагин Smooth Scroll

functions.php

/** Animated smooth scrolling for WP*/
add_action('wp_head','smoothscroll');

function smoothscroll() {
print("<script></script>");

}