DEV Community

hideckies
hideckies

Posted on • Originally published at blog.hdks.org

Adding Google Adsense to Hexo Blog

Hexo is a static site generator you can make blog easily.

Suppose you use the landscape theme.

1. Install Hexo and Create new project

First of all, install the Hexo CLI package.

npm install -g hexo-cli
Enter fullscreen mode Exit fullscreen mode

And create the new project.

hexo init my-blog
cd my-blog
npm install
Enter fullscreen mode Exit fullscreen mode

Please check the official documentation for details.

2. Add the landscape theme

If you created a new Hexo project, clone the git repository of the this repository in the project root directory.

git clone --depth 1 https://github.com/hexojs/hexo-theme-landscape themes/landscape
Enter fullscreen mode Exit fullscreen mode

Then you can see that landscape directory has been added to the theme directory.

After that, change theme in _config.yml to landscape. The config file in the root directory, not the landscape directory.

# _config.yml

# ...
theme: landscape
# ...
Enter fullscreen mode Exit fullscreen mode

This completes the basic settings.

3. Add the tag of Google Adsense into the landscape theme

Go to the Google Adsense page and register your domain.

Then you can get the tag like this:

<!-- Google Adsense -->
<script data-ad-client="ca-pub-48....." async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
Enter fullscreen mode Exit fullscreen mode

Next, create a new file named google-analytics.ejs in layout/_partial directory of the landscape.

<!-- source/themes/landscape/layout/_partial/google-analytics.ejs -->

<!-- Google Adsense -->
<script data-ad-client="ca-pub-48....." async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
Enter fullscreen mode Exit fullscreen mode

Once added, insert this to layout.ejs.

<!-- source/themes/landscape/layout/layout.ejs -->

<!DOCTYPE html>
<html>
<%- partial('_partial/head') %>
<body>
  <div id="container">
    <div id="wrap">
      <!-- ... -->
      <%- partial('_partial/google-adsense') %>
      <!-- ... -->
    </div>
    <!-- ... -->
  </div>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

The insert position is arbitrary, but in my case I did it to this position.

4. Check

Start Hexo server to check if it is reflected:

hexo server
Enter fullscreen mode Exit fullscreen mode

Open http://localhost:4000 in your favorite browser and open Developer Tools.

screenshot

you can see that there is <script> tags such like this:

<script type="text/javascript" src="https://adservice.google.com/adsid/integrator.js?domain=localhost"></script>
Enter fullscreen mode Exit fullscreen mode

This is a dedicated tag for Google Adsense.

After that, let's wait for the Google Adsense exam to pass. Actually, at the time of writing this article, I am waiting for the result, but I have failed several times.

Top comments (0)