Seo

SEO best practices

[] SEO best practices – WordPress Tutorials for Beginners res.json() ); } function removeLink( selector, condition ) { document.querySelectorAll( selector ).forEach( element => { const parent = element.parentNode; const parentTagName = parent.tagName.toLowerCase(); if ( condition ) { (parentTagName === ‘li’ ? parent : element).remove(); } }); } /** * Checks if the given data pertains to the specified region or country * @param {string} key – The key to check in the data * @param {string} name – The region or country name to check for * @param {object} data – The geolocation data * @returns {boolean} – True if the data pertains to the specified region or country */ function pertainsTo( key, name, data ) { if ( data && data[ key ] && name ) { return data[ key ].toLowerCase() === name.toLowerCase(); } return false; } fetchGeoData().then(data => { const isFCCA = pertainsTo( ‘country_long’, ‘germany’, data ); removeLink( FCCA_LINK_SELECTOR, ! isFCCA ); }); }); ]]> WordPress.com, WooCommerce, Jetpack, Simplenote, Longreads, VaultPress, Akismet, Gravatar, Crowdsignal, Cloudup, and more. We believe in making the web a better place, and we believe in Open Source. The vast majority of our work is available under the GPL.”,”logo”:{“@type”:”ImageObject”,”@id”:”https://automattic.com/#logo”,”url”:”https://automattic.com/wp-content/themes/a8c/automattic-2011/images/automattic-logo-2x.png”,”width”:552,”height”:60,”caption”:”Automattic”},”image”:{“@id”:”https://automattic.com/#logo”},”address”:{“@type”:”PostalAddress”,”streetAddress”:”60 29th Street #343″,”addressLocality”:”San Francisco”,”addressRegion”:”CA”,”postalCode”:”94110″,”addressCountry”:”US”},”founder”:{“@type”:”Person”,”@id”:”https://wordpress.com/schema.org/author/5#person”,”name”:”Matt Mullenweg”,”description”:”In 2002 I started contributing to Open Source software, and life has just gotten better from there. Co-founder of WordPress, founder Automattic.”,”image”:{“@type”:”ImageObject”,”@id”:”https://wordpress.com/schema.org/author/5#personimage”,”url”:”https://secure.gravatar.com/avatar/767fc9c115a1b989744c755db47feb60?s=96&d=identicon&r=g”,”width”:96,”height”:96,”caption”:”Matt Mullenweg”}},”numberOfEmployees”:1909,”sameAs”:[“https://twitter.com/automattic”,”https://www.facebook.com/AutomatticInc”,”https://www.linkedin.com/company/automattic/”,”https://en.wikipedia.org/wiki/Automattic”,”https://www.youtube.com/c/automattic”],”subOrganization”:{“@id”:”https://wordpress.com/#organization”}},{“@type”:”Organization”,”@id”:”https://wordpress.com/#organization”,”url”:”https://wordpress.com/”,”name”:”WordPress.com”,”legalName”:”Automattic, Inc.”,”foundingDate”:”2005-08-01″,”slogan”:”Build a website, build a movement.”,”description”:”Create a free website or build a blog with ease on WordPress.com. Dozens of free, customizable, mobile-ready designs and themes. Free hosting and support.”,”logo”:{“@type”:”ImageObject”,”@id”:”https://wordpress.com/#logo”,”url”:”https://s0.wp.com/home.logged-out/images/wpcom-a-website-that-can.jpg”,”width”:1024,”height”:512,”caption”:”WordPress.com”},”image”:{“@id”:”https://wordpress.com/#logo”},”address”:{“@type”:”PostalAddress”,”streetAddress”:”60 29th Street #343″,”addressLocality”:”San Francisco”,”addressRegion”:”CA”,”postalCode”:”94110″,”addressCountry”:”US”},”founder”:{“@type”:”Person”,”@id”:”https://wordpress.com/schema.org/author/5#person”,”name”:”Matt Mullenweg”,”description”:”In 2002 I started contributing to Open Source software, and life has just gotten better from there. Co-founder of WordPress, founder Automattic.”,”image”:{“@type”:”ImageObject”,”@id”:”https://wordpress.com/schema.org/author/5#personimage”,”url”:”https://secure.gravatar.com/avatar/767fc9c115a1b989744c755db47feb60?s=96&d=identicon&r=g”,”width”:96,”height”:96,”caption”:”Matt Mullenweg”}},”numberOfEmployees”:1909,”sameAs”:[“https://twitter.com/wordpressdotcom”,”https://www.facebook.com/WordPresscom”,”https://www.instagram.com/wordpressdotcom/”,”https://www.linkedin.com/company/wordpress”,”https://www.youtube.com/WordPressdotcom”,”https://www.pinterest.com/wordpressdotcom/”,”https://en.wikipedia.org/wiki/WordPress.com”],”parentOrganization”:{“@id”:”https://automattic.com/#organization”}},{“@type”:”WebSite”,”@id”:”https://wordpress.com/learn/#website”,”url”:”https://wordpress.com/learn/”,”name”:”WordPress Tutorials for Beginners”,”description”:””,”potentialAction”:{“@type”:”SearchAction”,”target”:”https://wordpress.com/learn/search/{search_term_string}/”,”query-input”:”required name=search_term_string”},”publisher”:{“@id”:”https://wordpress.com/#organization”}},{“@type”:”BreadcrumbList”,”@id”:”https://wordpress.com/learn/courses/intro-to-seo/seo-best-practices/#breadcrumbs”,”itemListElement”:[{“@type”:”ListItem”,”position”:0,”item”:{“@type”:”WebSite”,”@id”:”https://wordpress.com/learn/#website-breadcrumb”,”url”:”https://wordpress.com/learn/”,”name”:”Home”}},{“@type”:”ListItem”,”position”:1,”item”:{“@type”:”WebPage”,”@id”:”https://wordpress.com/learn/courses/#ancestor-breadcrumb”,”url”:”https://wordpress.com/learn/courses/”,”name”:”Courses”}},{“@type”:”ListItem”,”position”:2,”item”:{“@type”:”WebPage”,”@id”:”https://wordpress.com/learn/courses/intro-to-seo/#ancestor-breadcrumb”,”url”:”https://wordpress.com/learn/courses/intro-to-seo/”,”name”:”Intro to SEO”}},{“@type”:”ListItem”,”position”:3,”item”:{“@type”:”WebPage”,”@id”:”https://wordpress.com/learn/courses/intro-to-seo/seo-best-practices/#webpage-breadcrumb”,”url”:”https://wordpress.com/learn/courses/intro-to-seo/seo-best-practices/”,”name”:”SEO best practices u2014″}}]},{“@type”:”ImageObject”,”@id”:”https://wordpress.com/learn/courses/intro-to-seo/seo-best-practices/#primaryimage”,”url”:”https://learn.files.wordpress.com/2023/12/wp_blue_block.png?w=200″,”width”:200,”height”:200,”caption”:”SEO best practices u2014″},{“@type”:”WebPage”,”@id”:”https://wordpress.com/learn/courses/intro-to-seo/seo-best-practices/#webpage”,”url”:”https://wordpress.com/learn/courses/intro-to-seo/seo-best-practices/”,”name”:”SEO best practices u2014″,”description”:””,”inLanguage”:”en”,”isPartOf”:{“@id”:”https://wordpress.com/learn/#website”},”primaryImageOfPage”:{“@id”:”https://wordpress.com/learn/courses/intro-to-seo/seo-best-practices/#primaryimage”},”breadcrumb”:{“@id”:”https://wordpress.com/learn/courses/intro-to-seo/seo-best-practices/#breadcrumbs”},”publisher”:{“@id”:”https://wordpress.com/#organization”},”datePublished”:”2022-11-25T01:18:26+0000″,”dateModified”:”2024-04-11T03:24:34+0000″},{“@type”:”Article”,”@id”:”https://wordpress.com/learn/courses/intro-to-seo/seo-best-practices/#article”,”headline”:”SEO best practices u2014″,”commentCount”:0,”keywords”:””,”datePublished”:”2022-11-25T01:18:26+0000″,”dateModified”:”2024-04-11T03:24:34+0000″,”mainEntityOfPage”:{“@id”:”https://wordpress.com/learn/courses/intro-to-seo/seo-best-practices/#webpage”},”isPartOf”:{“@id”:”https://wordpress.com/learn/courses/intro-to-seo/seo-best-practices/#webpage”},”image”:{“@id”:”https://wordpress.com/learn/courses/intro-to-seo/seo-best-practices/#primaryimage”},”publisher”:{“@id”:”https://wordpress.com/#organization”},”author”:{“@id”:”https://wordpress.com/#organization”}}]} ]]>

When it comes to search engine optimization, there are things that can both help and hinder how well your site’s content is served to people on SERPs. It goes without saying that if your goal is for your site to rank more highly, you’ll want to do more of the good things and try to avoid the bad tactics altogether. The trick, however, is understanding that search engine algorithms are constantly changing. So, what was perhaps considered best practice in the past may very well be an old tactic that can hurt your SEO rating today. 

With that being said, here are some evergreen ways to optimize your site for search engines:

  • Publish and/or update content consistently. It is much better to get into a cadence of publishing one blog post per month than it is to publish 6 posts in one month and then nothing for the next half-year.
  • Write content that is relevant and engaging for your human audience. Search engines take into account how long visitors stay on your site, whether they like and/or comment on your posts, and if your content is shared on social media. If people like your content, search engines see that as a positive thing.
  • Aim for your page or post to be at least 300 words. Some posts can certainly be shorter, and some may be much longer, but it’s more difficult for search engines to get a good understanding of your content if it’s short.
  • Optimize your important pages and/or posts by trying to include your ideal keyword(s) in the title, the page URL (which is determined by the permalink slug in the page/post settings), the first paragraph, within a heading, and 1-2 times in the remaining body of text.
  • If your page or post content includes images, make sure the uploaded filenames of the images include your ideal keyword(s).

These are great ways to ensure your content is working towards a stronger SEO rating. At the same time, you’ll want to make sure you’re not doing anything that can penalize that rating. Here are some outdated and/or detrimental SEO tactics:

  • Writing content only for search engines. As we’ve already mentioned, it’s important to write for your human audience first.
  • Keyword Stuffing. This is the practice of adding your ideal keyword(s) way too much in the body paragraphs of your page’s content. For example, instead of using the keyword(s) 1-2 times, a page using keyword stuffing would have it appear 10+ times.
  • Keyword Cannibalization. This occurs when you have too many identical or similar keywords spread throughout the content on your site. As a result, search engines aren’t able to determine which page or post to rank more highly. This confusion can result in a decreased SEO rating.
  • Bad Backlinks. Although legitimate backlinks from external sites with good authority can help your SEO ranking, unethical means of attaining backlinks (e.g. buying or exchanging them, guest posting on irrelevant sites, spam comments in forums/directories, etc) will not have a positive impact.
  • Article Spinning. This is when popular content is essentially duplicated (it doesn’t have to be an exact copy, but the content and intent are highly similar to the original) and published on the same site or another one. 
  • Duplicate Content. This is when people copy content from other sites and publish the same content on their site. Search engines can recognize where the original content is published, and duplicate posts/pages could be seen as spammy. Also, when the same content exists in multiple places online, that only serves to increase competition, and likely doesn’t help the SEO rating.

Doing the good and avoiding the bad, as it relates to SEO practices, will go a long way over time to increase your site’s SEO rating. The field of search engine optimization is always changing, because companies like Google are constantly trying to improve their algorithms to present the most relevant results to the searches that people conduct. However, long-term, consistent publishing of quality content will always remain a key component for bettering your SEO ranking. 

It’s also important to know that improving your site’s search ranking on SERPs can take weeks, or even months, to achieve. It’s not a fast or overnight process, so be skeptical of anyone promising such results. Again, search engines will prioritize relevant, quality content over everything else.

Copied to clipboard!

Learn more, including how to control cookies.”,”v2Text”:”As an open source company, we take your privacy seriously and want to be as transparent as possible. So: We use cookies to collect some personal data from you (like your browsing data, IP addresses, and other unique identifiers). Some of these cookies we absolutely need in order to make things work, and others you can choose in order to optimize your experience while using our site and services.”,”v2OptionsText”:”Your privacy is critically important to us. We and our partners use, store, and process your personal data to optimize: our website such as by improving security or conducting analytics, marketing activities to help deliver relevant marketing or content, and your user experience such as by remembering your account name, language settings, or cart information, where applicable. You can customize your cookie settings below. Learn more in our Privacy Policy and Cookie Policy.”,”v2EssentialOptionHeading”:”Required”,”v2EssentialOptionText”:”These cookies are essential for our websites and services to perform basic functions and are necessary for us to operate certain features, like allowing registered users to authenticate and perform account-related functions, storing preferences set by users (like account name, language, and location), and ensuring our services operate properly.”,”v2AnalyticsOptionHeading”:”Analytics”,”v2AnalyticsOptionText”:”These cookies allow us to optimize performance by collecting information on how users interact with our websites.”,”v2AdvertisingOptionHeading”:”Advertising”,”v2AdvertisingOptionText”:”We and our advertising partners set these cookies to provide you with relevant content and to understand that contentu2019s effectiveness.”,”v1ButtonText”:”Got It!”,”v2CustomizeButtonText”:”Customize”,”v2AcceptAllButtonText”:”Accept all”,”v2AcceptSelectionButtonText”:”Accept selection”,”hiddenConsents”:[],”isLoggedIn”:false},”doNotSellDialog”:{“contactEmailAddress”:”privacypolicyupdates@automattic.com”},”adminAnalytics”:”analytics-wpcom-admin.php”,”fireAnalyticsOptions”:[]}; }; if ( window.defQueue && defQueue.isLOHP && defQueue.isLOHP === 2020 ) { defQueue.items.push( setupAnalytics ); } else { setupAnalytics(); } } )(); ]]>

{ let { target: element } = event; let foundElement = null; while ( element && !foundElement ) { for ( const selector of selectors ) { if ( element.matches( selector ) ) { foundElement = element; break; } } element = element.parentElement; } return foundElement; } /** * Establish the closest parent from an element matching * a given list of selectors. Selectors can be css classes, IDs, * element types, etc. (e.g. ‘.my-class’, ‘#my-id’, ‘div’, etc.) */ const getClosestMatchingAncestor = ( event, selectors ) => { let { target: element } = event; let foundElement; for ( const selector of selectors ) { foundElement = element.closest( selector ); if ( foundElement ) { break; } } return foundElement; } /** * Main function to setup analytics. */ const setupAnalytics = () => { /** * Returns the current page path. */ function getCurrentPagePath( pathname = ” ) { return ( pathname || window.location.pathname ).replace( /^/|/$/g, ” ); } /** * Returns the current page name. */ function getCurrentPageName( pathname = ” ) { return getCurrentPagePath( pathname ).replace( getLocaleInPagePathRegExp(), ” ); } /** * Returns the current page locale. */ function getCurrentPageLocale() { const currentPagePath = getLocaleInPagePathRegExp().exec( getCurrentPagePath() ); return getCurrentPagePath !== null && getCurrentPagePath.length === 2 ? getCurrentPagePath[1] : ”; } /** * Helper function to extract locale from page path. */ function getLocaleInPagePathRegExp() { return /^(af|als|am|an|ar|arc|as|ast|av|ay|az|ba|bel|bg|bm|bn|bo|br|bs|ca|ce|ckb|cs|csb|cv|cy|da|de|dv|dz|el|el-po|en|en-gb|eo|es|es-mx|et|eu|fa|fi|fo|fr|fr-be|fr-ca|fr-ch|fur|fy|ga|gd|gl|gn|gu|he|hi|hr|hu|hy|ia|id|ii|ilo|is|it|ja|ka|kir|km|kn|ko|kk|ks|kv|la|li|lo|lv|lt|mk|ml|mwl|mn|mr|ms|mya|nah|nap|ne|nds|nl|nn|nb|non|nv|oci|or|os|pa|pl|ps|pt|pt-br|qu|ro|ru|rup|sc|si|sk|skr|sl|snd|so|sq|sr|su|sv|ta|te|th|tl|tir|tr|tt|ty|udm|ug|uk|ur|uz|vec|vi|wa|xal|yi|yo|za|zh-cn|zh-hk|zh-tw)(?:/|$)/; } /** * Returns the config for WPcom analytics. Sets various event props * used in tracking, e.g. locale, page path, etc. Mainly used for Tracks * event props. */ function getWPCOMAnalyticsDefaultConfig() { const currentGenericPageName = null; const cannonicalPath = null; return { // Current page props. currentPagePath: getCurrentPagePath(), currentPageName: getCurrentPageName(), currentGenericPageName: currentGenericPageName ?? getCurrentPageName( cannonicalPath ), currentPageLocale: getCurrentPageLocale(), // Page variation props. pageVariation: ”, pagePersonalVariation: ”, // Current user props. currentUserIdHash: “”, currentUserIdHashShort: “”, currentUserEmailHash: “”, // Other misc. props. isHomepage: false, affiliateJSVersion: “1716355472”, } } // When a8c-analytics:loaded is fired, start main event handling. document.addEventListener( ‘a8c-analytics:loaded’, () => { const cb = window.a8cAnalytics.cb; const kit = window.a8cAnalytics.kit; const config = getWPCOMAnalyticsDefaultConfig(); const configOptions = window.a8cAnalyticsConfig.fireAnalyticsOptions; // Extend config with any custom props. Object.assign( window.a8cAnalyticsConfig, config ); // Backcompat. for `lpName` and `lpVariation` config properties. config.currentPageName = ! configOptions.currentPageName && ‘logged-out-homepage’ === configOptions.lpName ? configOptions.lpName : config.currentPageName; config.currentPageName = ! configOptions.currentPageName && ‘logged-out-app-promo’ === configOptions.lpName ? configOptions.lpName : config.currentPageName; // Backcompat. for `lpPersonalVariation` config property. config.pageVariation = ! configOptions.pageVariation && configOptions.lpVariation ? configOptions.lpVariation : config.pageVariation; config.pagePersonalVariation = ! configOptions.pagePersonalVariation && configOptions.lpPersonalVariation ? configOptions.lpPersonalVariation : config.pagePersonalVariation; /** * Applies linkers, e.g. for “forwarding” certain URL parameters between WordPress.com * and other properties (e.g. Jetpack.com). Used for affiliate tracking, coupons, etc. */ const applyLinkers = () => { kit.linkQueryVars( [ { includeRegExps: [ /^(?:[^/]+.)?(?:wordpress|jetpack|woocommerce|crowdsignal|wpjobmanager).com(?:/|$)/i, ], linkQueryVars: [ ‘aff’, ‘affiliate’, ‘cid’, // Aff campaign ID. ‘sid’, // Aff sub ID. ‘irclickid’ // Impact Affiliate Click ID ], }, { includeRegExps: [ /^(?:[^/]+.)?(?:wordpress|jetpack).com(?:/|$)/i, ], linkQueryVars: [ ‘coupon’, ], }, ] ); } /** * Handles currencies. Gets the currency value from cookies, and sets the currency * if the cookie is not present. Can also be overridden by setting the `currency` URL * paramter. */ const fireCurrencyHandlers = () => { let currency = kit.getQueryVar( ‘currency’ ) || ”; if ( ! currency && ‘amex-business-in’ === config.currentPageName ) { currency = ‘USD’; // Special case for this LP. } if ( currency ) { kit.docCookies.setItem( ‘landingpage_currency’, currency, 31536000, ‘/’, ‘.rootDomain’ ); } }; /** * Fires the `wpcom_page_view` Tracks event. */ const fireTracks = () => { const props = Object.assign( {}, kit.getQueryVars( ”, kit.QUERY_PARAMS ), { // Page props. path: config.currentPagePath, name: config.currentPageName, locale: config.currentPageLocale, variation: config.pageVariation, personal_variation: config.pagePersonalVariation, // Back compat. LP props. lp_name: config.currentGenericPageName, lp_variation: config.pageVariation, lp_personal_variation: config.pagePersonalVariation, } ); window._tkq.push( [ ‘recordEvent’, ‘wpcom_page_view’, props ] ); }; function fireRedditAdvertisingPixel() { !function(w,d){if(!w.rdt){var p=w.rdt=function(){p.sendEvent?p.sendEvent.apply(p,arguments):p.callQueue.push(arguments)};p.callQueue=[];var t=d.createElement(“script”);t.src=”https://www.redditstatic.com/ads/pixel.js”,t.async=!0;var s=d.getElementsByTagName(“script”)[0];s.parentNode.insertBefore(t,s)}}(window,document); rdt(‘init’,’a2_ehx23cq176s3′); rdt(‘track’, ‘PageVisit’); } /** * Handles the referral tracking. */ const fireAffiliateReferrals = () => { kit.attachScriptElement( ‘https://s1.wp.com/wp-content/themes/h4/landing/marketing/js/affiliate-referrals.js?v=’ + config.affiliateJSVersion ); }; /** * Loads the Google Ads gtag. */ const loadGoogleAdsGtag = () => { kit.loadGtag( ‘AW-946162814’ ); } /** * Loads and fires the Google Analytics 4. */ const fireGoogleAnalyticsFour = () => { const gtagOptions = { ‘anonymize_ip’: true, ‘use_amp_client_id’: true }; kit.loadGtag( ‘G-1H4VG5F5JF’, gtagOptions ); } const fireParsely = ( trackingId ) => { kit.loadParselyTracker( trackingId ); } const fireHotJar = () => { if ( ! kit.pertainsToSTS() ) { kit.fireHotjar( 227769 ); } } /** * Loads and fires the Facebook Pixel. */ const fireFacebook = () => { kit.loadFacebook(); fbq( ‘init’, ‘823166884443641’ ); fbq( ‘track’, ‘PageView’ ); } /** * Loads and fires Microsoft Clarity */ const fireMicrosoftClarity = () => { if ( window.clarity ) { return; } // Needs to be set prior to loading the external script. window.clarity = window.clarity || function () { ( window.clarity.q = window.clarity.q || [] ).push( arguments ); }; const clarityScript = kit.attachScriptElement( ‘https://www.clarity.ms/tag/j0cc1i1dba’ ); document.body.appendChild( clarityScript ); }; const fireImpactAffiliate = () => { kit.loadImpactAffiliate( config.currentUserIdHash, config.currentUserEmailHash ); } /** * Handles scroll percentage tracking. */ const trackScrollPercentage = () => { const scrollPosition = window.pageYOffset; const pageHeight = document.body.scrollHeight – window.innerHeight; const scrollProgress = ( scrollPosition / pageHeight ) * 100; // Check if the user has scrolled to 25%, 50%, 75%, or 100% of the page if ( scrollProgress >= 25 && scrollProgress = 50 && scrollProgress = 75 && scrollProgress = 100 ) { dispatchScrollCustomEvent( 100 ) } } /** * Dispatches a custom event with the scroll percentage. */ const dispatchScrollCustomEvent = ( scrollPercentage ) => { const event = new CustomEvent( `PageScrollPercentage${scrollPercentage}`, { detail: scrollPercentage } ); window.dispatchEvent(event); } /** * Handles the scroll tracking callback. E.g. firing Tracks and GA events. */ const scrollTrackingCallback = ( event ) => { const { detail: scrollPercentage } = event; const trackingProps = {}; // Event props. trackingProps.percent = event.detail ?? 0; trackingProps.path = config.currentPagePath || ”; trackingProps.name = config.currentPageName || ”; trackingProps.locale = config.currentPageLocale || ”; trackingProps.variation = config.pageVariation || ”; trackingProps.personal_variation = config.pagePersonalVariation || ”; trackingProps.lp_name = config.currentGenericPageName || ”; trackingProps.lp_variation = config.pageVariation || ”; trackingProps.lp_personal_variation = config.pagePersonalVariation || ”; tracksAnalyticsScrollEvent( trackingProps ); } /** * Dispatches a Tracks event for page scroll. */ const tracksAnalyticsScrollEvent = ( trackingProps ) => { window._tkq.push( [ ‘recordEvent’, ‘wpcom_page_scroll’, trackingProps ] ); } // Call the trackScrollProgress function every time the user scrolls window.addEventListener( ‘scroll’, trackScrollPercentage ); // Listen to events for specific scroll percentages, each event is only acted upon once. window.addEventListener( ‘PageScrollPercentage25’, scrollTrackingCallback, { once: true } ) window.addEventListener( ‘PageScrollPercentage50’, scrollTrackingCallback, { once: true } ) window.addEventListener( ‘PageScrollPercentage75’, scrollTrackingCallback, { once: true } ) window.addEventListener( ‘PageScrollPercentage100’, scrollTrackingCallback, { once: true } ) /** * Handles click tracking for certain elements in Tracks and GA. */ const setupTracksGAClickTracking = () => { document.querySelector( ‘body’ ).addEventListener( ‘click’, ( event ) => { // We only care about clicks on certain elements. if ( event.target.matches( ‘a, button, .click-tracking-enable’ ) ) { const { target: clickEventTarget } = event; // Initialize eventProps object with some defaults. const eventProps = {}; eventProps.path = config.currentPagePath || ”; eventProps.name = config.currentPageName || ”; eventProps.lp_name = config.currentGenericPageName || ”; eventProps.locale = config.currentPageLocale || ”; eventProps.variation = config.pageVariation || ”; eventProps.personal_variation = config.pagePersonalVariation || ”; // Identify farthest and closest parent element. const selectors = [ ‘.wpcom-masterbar.wpcom-header’, ‘.lp-block’, ‘.lpc’, ‘.lp-module’, ‘section’, ‘post’, ‘article’ ]; const section = getLastMatchingAncestor( event, selectors ); const container = getClosestMatchingAncestor( event, selectors ); // Get class name and ID for container and add to props. eventProps.container_id = container ? container.getAttribute( ‘id’ ) : ”; eventProps.container_class = container ? container.getAttribute( ‘class’ ) : ”; eventProps.container = eventProps.container_id || eventProps.container_class; // What type of element have we clicked? eventProps.is_cta = clickEventTarget.matches( ‘is-cta’ ) ?? false; eventProps.is_in_header_nav = clickEventTarget.classList.contains(‘x-nav-link’) || clickEventTarget.classList.contains(‘x-dropdown-link’) || clickEventTarget.classList.contains(‘x-menu-link’) || section === ‘lpc-header-nav’ || section === ‘wpcom-masterbar.wpcom-header’; const isClickedElementButton = clickEventTarget.classList.contains(‘lpc-button’) || clickEventTarget.classList.contains(‘button’) || clickEventTarget.classList.contains(‘wp-block-button__link’); const isParentElementButton = clickEventTarget.parentElement && (clickEventTarget.parentElement.classList.contains(‘lpc-button’) || clickEventTarget.parentElement.classList.contains(‘button’) || clickEventTarget.parentElement.classList.contains(‘wp-block-button__link’)); eventProps.is_button = isClickedElementButton || isParentElementButton; // Link data. eventProps.href = clickEventTarget.getAttribute( ‘href’ ) || ”; eventProps.target = clickEventTarget.getAttribute( ‘target’ ) || ”; eventProps.text = clickEventTarget.innerText || ”; eventProps.use_beacon = true; // Emit tracking event in Tracks and GA. window._tkq.push( [ ‘recordEvent’, ‘wpcom_link_click’, eventProps ] ); // TODO: Implement a click delay on navigation links and CTA buttons to improve data integrity. // if ( props.is_in_header_nav || props.is_cta || props.is_button ) { // if ( props.href && 0 !== props.href.indexOf( ‘#’ ) && -1 !== [ ”, ‘_top’, ‘_self’ ].indexOf( props.target ) ) { // event.preventDefault(); // Allow time for trackers to record the click. // setTimeout( function() { // document.location = props.href; // }, 300 ); // } // } } }); } /** * Add cookie and stats tracking for the Landpack language picker. */ const setupLocaleChangeTracking = () => { function createLocaleCookie( locale ) { const cookieDomain = ‘.wordpress.com’; const cookieName = ‘wpcom_locale’; const date = new Date(); date.setTime( date.getTime() + ( 5 * 365 * 24 * 60 * 60 * 1000 ) ); const expires = ” expires=” + date.toGMTString(); document.cookie = cookieName + ‘=’ + locale + ‘;’ + expires +’; path=/; domain=’ + cookieDomain; } function createStatsRequest( locale, href ) { const languageChangeStat = new Image(); languageChangeStat.onload = () => window.location.href = href; languageChangeStat.onerror = languageChangeStat.onload; languageChangeStat.src = ‘https://pixel.wp.com/g.gif?v=wpcom-no-pv&x_language-switcher=manual-switch-‘ + locale + ‘&rm=’ + Math.random(); } document.body.addEventListener( ‘click’, ( event ) => { const { target } = event; if ( target.matches( ‘.lp-language-picker a[lang]’ ) ) { event.preventDefault(); const code = target.getAttribute( ‘lang’ ); const href = target.getAttribute( ‘href’ ); createLocaleCookie( code ); createStatsRequest( code, href ); } }); } /** * Loads and fires the Bing tracking pixel. */ const fireBing = () => { ( function( w, d, t, r, u ) { var f, n, i; w[ u ] = w[ u ] || [], f = function() { var o = { ti: “4074038” }; o.q = w[ u ], w[ u ] = new UET( o ), w[ u ].push( “pageLoad” ) }, n = d.createElement( t ), n.src = r, n.async = 1, n.onload = n.onreadystatechange = function() { var s = this.readyState; s && s !== “loaded” && s !== “complete” || ( f(), n.onload = n.onreadystatechange = null ) }, i = d.getElementsByTagName( t )[ 0 ], i.parentNode.insertBefore( n, i ) } )( window, document, “script”, “//bat.bing.com/bat.js”, “uetq” ); } /** * Adds a click event for Facebook pixel tracking on the /webinar sub pages. */ const trackFacebookWebinarClicks = () => { const facebookPixelURL = ‘https://www.facebook.com/tr?id=759053181468957&ev=SubscribedButtonClick&noscript=1’; const elementsToTrack = document.getElementsByClassName( ‘webinar-facebook-click-track’ ); const handleFacebookClickEvent = ( event ) => { const facebookImgPixel = document.createElement( ‘img’ ); facebookImgPixel.width = 1; facebookImgPixel.height = 1; facebookImgPixel.src = facebookPixelURL; document.body.appendChild( facebookImgPixel ); } Array.from( elementsToTrack ).forEach( ( element ) => element.addEventListener( ‘click’, handleFacebookClickEvent )); } // Apply the URL parameter linkers. applyLinkers(); // Add “essential” trackers to queue. cb.addTracker( ‘essential’, false, fireCurrencyHandlers ); // Add “analytics” trackers to queue. cb.addTracker( ‘analytics’, false, fireTracks ); cb.addTracker( ‘analytics’, false, fireAffiliateReferrals ); cb.addTracker( ‘analytics’, false, setupTracksGAClickTracking ); cb.addTracker( ‘analytics’, false, trackScrollPercentage ); cb.addTracker( ‘analytics’, false, setupLocaleChangeTracking ); cb.addTracker( ‘analytics’, true, fireGoogleAnalyticsFour ); cb.addTracker( ‘analytics’, true, () => fireParsely( ‘wordpress.com’ ) ); // Add “advertising” trackers to queue. cb.addTracker( ‘advertising’, true, loadGoogleAdsGtag ); cb.addTracker( ‘advertising’, true, fireFacebook ); cb.addTracker( ‘advertising’, true, trackFacebookWebinarClicks ); cb.addTracker( ‘advertising’, true, fireBing ); cb.addTracker( ‘advertising’, true, fireRedditAdvertisingPixel); // cb.addTracker( ‘advertising’, true, fireHotJar ); – Disabling for now. Enable when Hotjar is required to be used. // cb.addTracker( ‘advertising’, true, fireMicrosoftClarity ); – Disabling for now. cb.addTracker( ‘advertising’, true, fireImpactAffiliate ); // Maybe fire trackers now, via cookie banner, based on bucketed consent. cb.maybeFireTrackers(); }); }; // CCPA – Do Not Sell My Data. document.addEventListener( ‘a8c-analytics:loaded-is-ccpa’, ( event ) => { const { detail } = event; const isCCPAEligible = JSON.parse( detail ).isCCPA; if ( ! isCCPAEligible ) { document.querySelectorAll( ‘[data-is-ccpa-dnsd]’ ).forEach( ( element ) => { const parent = element.parentNode; const parentTagName = parent.tagName.toLowerCase(); // If the link in a part of a list, remove the entire parent item. // Otherwise, remove only the link element. ( parentTagName === ‘li’ ? parent : element ).remove(); } ); return; } document.querySelector( ‘[data-is-ccpa-dnsd-trigger]’ ).onclick = ( event ) => { event.preventDefault(); window.a8cAnalytics.dnsd.show(); }; } ); if ( window.defQueue && defQueue.isLOHP && defQueue.isLOHP === 2020 ) { defQueue.items.push( setupAnalytics ); } else { setupAnalytics(); } } )(); ]]>

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button