Adding Google Adsense to Hexo Blog

2021-09-02

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.

1
npm install -g hexo-cli

And create the new project.

1
2
3
hexo init my-blog
cd my-blog
npm install

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.

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

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.

1
2
3
4
5
# _config.yml

# ...
theme: landscape
# ...

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:

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

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

1
2
3
4
<!-- 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>

Once added, insert this to layout.ejs.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<!-- 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>

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:

1
hexo server

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

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

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

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.