Category: WordPress

How to change loop times in WordPress

GOAL

To stop the loop at the number of times specified in WordPress.

Environment

WordPress 5.5.1

Loop in WordPress

The Loop is PHP code used by WordPress to display posts. The following is an example of the loop.

<?php 
if ( have_posts() ) {
	while ( have_posts() ) {
		the_post(); 
		//
		// Post Content here
		//
	} // end while
} // end if
?>

Check “The Loop” in wordpress.org for details about the loop.

Method

Use get_posts function

<?php
	$recentposts = get_posts( array( 'posts_per_page' => 3) );
	if ( $lastposts ) {
    		foreach ( $lastposts as $post ) : setup_postdata( $post );
			the_title();
        		//
			// Post Content here
			//
		endforeach; 
    		wp_reset_postdata();
	} //end if
?>

Appendix

Though <?php query_posts(‘posts_per_page=NUMBER’); ?> can be also used to limit the number of posts, it is not recommended.

Create Original Theme in WordPress 2

At the last time, in “Create Original Theme in WordPress 1“, I created the simplest minimum theme “techblog”. I’ll create practical WordPress theme from now on.

GOAL

To design the configuration of the WordPress site.

the configuration of pages

This is the page transition diagram. The top page is home. Pages “Home”, “About”, “Links” and “Posts(Post List)” can be accessed directly with main menu.

This is the construction of each page and links among them.

Detail design of each page

Home page

This page is used for “Home”.

Posts page

This page is used for “Posts (all posts)”, the result searched by categories and the result searched by words.

Single Page

This page is used for “About”, “Links” and the page for each single posts.

Side bar

Some of these items can be added easily by using Plugins.

Create Original Theme in WordPress 1

ULTIMATE GOAL

To create the original WordPress theme

GOAL

Today’s goal is to make the smallest WordPress theme as below.

File construction for WordPress theme

The following is an example of file construction.

  • index.php
  • header.php
  • footer.php
  • archive.php
  • comments.php
  • 404.php
  • page.php
    • page-fullwidth.php
  • sidebar.php
    • sidebar-home.php
    • sidebar-footer.php
  • single.php
  • category.php
  • tag.php
  • functions.php
  • style.css
  • templaete-parts
    • content.php
    • content-frontpage.php
    • content-none.php
    • content-single.php

You can see the role of each file in wordpress.org “Template Files”. Today, I create index.php, functions.php and style.css

index.php

This is the main PHP file displayed as a top page.

<?php
/**
*This is main file for "techblog" theme
*@package Techblog
*@since Techblog 1.0
 */
get_header(); ?>
<main id="main" class="site-main" role="main">
	<header>
		<h1 class="page-title"><?php bloginfo('name'); ?></h1>
		<h2 class="description"> <?php bloginfo('description'); ?></h2>
	</header>
	<?php if ( have_posts() ) : ?>
		<ul id="posts">
			<?php while ( have_posts() ) : the_post(); ?>
                <li><a href="<?php the_permalink(); ?>">
                	<h2 class = "post_item"><?php the_title(); ?></h2>
                </a></li>
			<?php endwhile; ?>
		</ul>
	<?php endif; ?>
</main>
<?php get_footer(); ?>

PHP Doc Tags

Some PHP doc tags are used in WordPress. You can see the list of PHP doc tags in “PHPDoc Tags” in wordpress.org.

*@package Techblog
*@since Techblog 1.0

php functions

You can see the functions that can be used in WordPress in “Code Reference“.

  • get_header()
    • Includes the header template for a theme
    • If you have no header.php, it includes the default header.
  • bloginfo()
    • Display information about the site you defined.
    • You can get information such as ‘name’, ‘description’ and so on.
  • have_posts()
    • It can be used to determines whether current WordPress query has posts to loop over
  • the_post()
    • Iterate the post index in the loop
    • It can be used when have_posts() is True
  • the_permalink()
    • Displays the permalink for the current post
    • It displays the url to the_post()
  • the_title()
    • Display or retrieve the current post title
    • It displays the titel of the_post()
  • get_footer()
    • Includes the footer template for a theme

style.css

style.css is the style sheet for the site. style.css should have infromation about the theme. Please check “Main Stylesheet (style.css)” in wordpress.org for details.

/*
Theme Name: Techblog
Theme URI: #
Author: Nako
Author URI: https://s-nako.work
Description: This is the simplest theme for engineer's technical blog
Version: 1.0.0
License: GNU General Public License v2 or later
License URI: http://www.gnu.org/licenses/gpl-2.0.html
Text Domain: techblog
Domain Path: /languages/
Tags: blog, news,

This theme, like WordPress, is licensed under the GPL.
*/

body {
    color: #6B6B6B;
    background-color:#DADADA;
    font-family: 'Open Sans', sans-serif;
    line-height: 1.7;
    font-size: 14px;
}

The information in style.css is displayed in Appearance >Themes.

functions.php

functions.php is function set for the site. I don’t use any original function at this time.

<?php
/**
 * techblog functions and definitions
 * @package Techblog
 * @since Techblog 1.0
 */
if ( ! defined( 'TECHBLOG_VERSION' ) ) {
	// Replace the version number of the theme on each release.
	define( 'TECHBLOG_VERSION', '1.0.0' );
}

Install the created theme

Put the directory where index.php, style.css and functions.php is into the themes directory “xampp\htdocs\wordpress\wp-content\themes”.

You can activate the theme you created in the Appearance >Themes.

How To Develop WordPress in XAMPP

I’d like to create my original theme for WordPress. This is the preparation for development of WordPress in XAMPP.

GOAL

To create develop environment for WordPress development in XAMPP.

Environment

Windows10
XAMPP 7.4.10

If you don’t have XAMPP, please install it first according to “Installation of XAMPP“. And If you’ll use MariaDB in a production environment, make it secure by setting password according to “How To Set MySQL Password in XAMPP“.

Method

1. Install WordPress

Download WordPress from wordpress.org.

2. Put the WordPress into the root doc

The default root doc is xampp\htdocs.

3. Create a new database for WordPress

Reference: Using phpMyAdmin in Support page of wordpress.org

Open XAMPP Control Panel and run Apache and MySQL. Then access phpMyAdmin, localhost/phpmyadmin.
Create a new database for WordPress as below.

4. Connecting the database to WordPress

Access localhost/wordpress. In my case, the page is redirected to localhost/wordpress/wp-admin/setup-config.php.

Select language and go next page.

Input the data of your database and press Submit. Database Name is the database name you defined.

You can see Username, Password and Database Host in phpMyAdmin.

The connection to the database will be established. Press “Run the installation”.

5. Input information of your WordPress.

Input information of your new WordPress and press “Install WordPress”.

6. Confirm that you can login WordPress

You can login localhost/wordpress/wp-admin/ with Username and Password you defined at the last page.

Appendix

*You can import post, pages, comments, custom fields, categories, and tags from a WordPress export .xml file with Import tab.

How to embed code in header of child-theme

I embed Google Analytics tag in my WordPress in “How to use Google Analytics in WordPress site“. And I created child-theme in “How To Create Child Themes In WordPress“. But, how can I embed google analytics tags into the header of the child-theme?

GOAL

To embed code in heder.php by adding the function to “functions.php” in the child theme.

Method

Use function add_action( ‘wp_head‘, <function_name> ), <<<(heredoc) and echo.

add_action( 'wp_head', 'header_customize');
function header_customize() {
	$header_tags = <<<EOM

	<!--ADD YOUR HTML HERE such as <script src="..."></script>-->

	EOM;
	echo $header_tags;
}

The argument function header_customize() is added when wp_head() is called in functions.php of parent theme as below.

<?php wp_head(); ?>

You can see the code written in the source of your website.

How To Use Google Fonts in your WordPress

GOAL

Change the default font of your theme in WordPress to google fonts.

Environment

WordPress 5.5.1
Theme: Sparkling (I have child-theme sparkling-child)

What is Google Fonts?

Google font is abundant font set that can be used in websites without install and upload. It can be used by just putting code in your HTML.

We believe the best way to bring personality and performance to websites and products is through great design and technology. Our goal is to make that process simple, by offering an intuitive and robust collection of open source designer web fonts.

Google Fonts

Method

1. Get the link to use Google Fonts

Choose the font you want to use from Google Fonts.

For example, I use “Open Sans” and “Roboto Slab” in this blog.

Copy the URL to link the fonts you selected.

You can see the css to use this fonts by accessing the URL you copied (example).

2. Enqueue the link with wp_enqueue_style()

The function wp_enqueue_style() can be used to add stylesheet in WordPress.

Add the function to functions.php in your child theme or parent theme.

add_action( 'wp_enqueue_scripts', 'add_fonts' );
function add_fonts() {
	wp_enqueue_style( 'font-styles' , 'https://fonts.googleapis.com/css2?family=Open+Sans:ital@0;1&family=Roboto+Slab:wght@600;700&display=swap' ,false);
}

In my case, I add the wp_enqueue_style() into the existing function in functions.php of child theme as below.

<?php
add_action( 'wp_enqueue_scripts', 'theme_enqueue_styles' );
function theme_enqueue_styles() {
	wp_enqueue_style( 'sparkling-bootstrap', get_template_directory_uri() . '/assets/css/bootstrap.min.css' );
	wp_enqueue_style( 'sparkling-icons', get_template_directory_uri() . '/assets/css/fontawesome-all.min.css', null, '5.1.1.', 'all' );
	wp_enqueue_style( 'font-styles' , 'https://fonts.googleapis.com/css2?family=Open+Sans:ital@0;1&family=Roboto+Slab:wght@600;700&display=swap' ,false);
    wp_enqueue_style( 'parent-style' , get_template_directory_uri() . '/style.css' );
}
?>

3. Change CSS

Change style.css to use added fonts. For example, I use “Roboto Slab” for heading elements.

h1, h2, h3, h4, h5, h6{
color: #DA4453;
font-weight: 700;
font-family: 'Roboto Slab', serif;
}

How To Create Child Themes In WordPress

GOAL

To understand What child themes in WordPress is and create it

Environment

WordPress 5.5.1
Theme: Sparkling

What is Theme and child-theme in WordPress

What is theme?

WordPress Themes can provide much more control over the visual presentation of your content and other data on your WordPress site, as well as behavior of certain site’s elements while interacting with visitors.

From wordpress.org Using Themes

A WordPress Theme is a collection of files that work together to produce a graphical interface with an underlying unifying design for a website.

From wordpress.org Using Themes

You can see themes from Appearance>Themes.

And you can customize the themes from Appearance>Customize.

What are themes made of?

The following is an example of file construction of the theme. You can see these files from Appearance>Theme Editor.

  • Required files
    • index.php: the main template file
    • style.css
  • Additional files
    • PHP files
    • Localization files: this is used for translating an internationalized theme
    • CSS files
      • bootstrap.css, flexslider.css, etc
    • Graphics
    • JavaScript
      • customizer.js, functions.js, flexslider-custom.js, etc. 
    • Text files
      • license.txt, readme.txt, etc.

What is child-theme?

As indicated in the overview, a child theme inherits the look and feel of the parent theme and all of its functions, but can be used to make modifications to any part of the theme. In this way, customizations are kept separate from the parent theme’s files.

From wordpress.org Child Themes

And the most important point of child-theme is that the customized data won’t be removed when the theme is updated.

Using a child theme lets you upgrade the parent theme without affecting the customizations you’ve made to your site.

From wordpress.org Child Themes

How to create a child-theme

Reference: How to Create a Child Theme by wordpress.org

I summarized the document above.

1. Create a new directory for child-theme

Create a new directory in wp/wp-content/themes and named it “<theme name>-child”. In my case, the name is sparkling-child.

2. Create a stylesheet: style.css

Create style.css in <theme name>-child directory. And write information at the top of style.css as below. “Theme URI” is the path to the child theme in the server and “Template” is the directory name of the parent theme. “Theme Name” needs to be unique.

/*
 Theme Name:   Sparkling Child
 Theme URI:    http://example.com/sparkling-child/
 Description:  Sparkling Child Theme
 Author:       Nako
 Author URI:   http://example.com
 Template:     sparkling
 Version:      1.0.0
 License:      GNU General Public License v2 or later
 License URI:  http://www.gnu.org/licenses/gpl-2.0.html
 Tags:         blog
 Text Domain: sparklingchild
*/

/* Add your css here*/

3. Enqueue stylesheet

Create functions.php in <theme name>-child directory. And write the function to enqueue stylesheets of the parent theme.

<?php
add_action( 'wp_enqueue_scripts', 'theme_enqueue_styles' );
function theme_enqueue_styles() {
    wp_enqueue_style( 'parent-style' , get_template_directory_uri() . '/style.css' );
}
?>

If the parent theme has some css in addition to ‘/style.css’, you should contain them in theme_enque_styles().
If the stylesheet of the child theme doesn’t loaded automatically, you should enqueue ‘child-style’ in theme_enque_styles().

4. Install and customize child theme

Open Appearance>Themes in Dashboard.

Then select the child-theme you created and customize it.

5. Activate child theme

Appendix

The order of style sheet to read will changed if child-theme is added. So you should move some additional css from the parent style.css to child style.css.

When only parent theme is used, sparkling/style.css is loaded after loading font (Google Fonts). You can use the font in parent sparkling/style.css.

When child theme is used in addition to parent theme, sparkling/style.css is loaded at first and font (Google Font) is load after that. You can’t use the font in parent sparkling/style.css.

So you should put css related to the font in sparkling-child/style.css or read every stylesheet in sparkling-child/function.php.

<?php
add_action( 'wp_enqueue_scripts', 'theme_enqueue_styles' );
function theme_enqueue_styles() {
	wp_enqueue_style( 'sparkling-bootstrap', get_template_directory_uri() . '/assets/css/bootstrap.min.css' );
	wp_enqueue_style( 'sparkling-icons', get_template_directory_uri() . '/assets/css/fontawesome-all.min.css', null, '5.1.1.', 'all' );
	wp_enqueue_style( 'font-styles' , '//fonts.googleapis.com/css?family=Open+Sans:400italic,400,600,700|Roboto+Slab:400,300,700' ,false);
    wp_enqueue_style( 'parent-style' , get_template_directory_uri() . '/style.css' );
}
?>

How to use Google Analytics in WordPress site

GOAL

To understand the way to use Google Analytics and add google analytics tag into the header of the WordPress site.

Environment

WordPress 5.5.1
Theme: sparkling
Registered with Google Analytics

What is Google Analytics

Google Analytics is one of the services to analyze access log such as the number of access users, sessions, bounce rate and so on.

If you’ve not registered with Google Analytics yet, create an account and register.

Method

1. Get the tracking code

Login Google Analytics and open Admin menu.

Click “Tracking Code” and copy the Global Site Tag (gtag.js).

2. Paste the site tag to header.php of the theme

Open Appearance>Theme Editor in Dashboard.

Open hedaer.php and paste the copied code into the bottom of <head></head> tag.

<!--[if gt IE 9]><!-->
<html class="no-js" <?php language_attributes(); ?>> <!--<![endif]-->
<head>
<meta charset="<?php bloginfo( 'charset' ); ?>">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="theme-color" content="<?php echo of_get_option( 'nav_bg_color' ); ?>">
<?php wp_head(); ?>

========================================
   put the tag from <script> to </script> here 
========================================

</head>

Save the change. Confirm that the tag is added in the source of your website.

Fitting the width of web page that has long formula to display size

The width of my WordPress blog doesn’t fit mobile display. What is the cause? How can I fix this?

The room at the right side of the page

GOAL

To adjust the width of pages in my WordPress blog for mobile phone.

Environment

WordPress 5.5.1
Theme: Sparkling
Plugin: MathJax-LaTeX

Cause

The page size is expanded by mathematical formula. (For example, an article “What is Hermite interpolation?” has long formula)

How I found it…

In my case, though the width of main html is fit to the display the width of the whole page is expanded for some reasons. And it doesn’t occur when single article is opened (you can see the size of background is fit to the display as below).

I found that the change of the width happens with a time lag after main header and footer are loaded. I captured display and find that the change happened just after “Typesetting math” process completed.

This process is creation of the formula with the greatly useful plugin “MathJax-LaTeX“. When “MathJax-LaTeX” plugin is deactivated, the size of the page fit to the display.

Methods

The following is html source related to MathJax.

<p>
  <span class="MathJax_Preview" style=""></span>
  <div class="MathJax_Display" style="text-align: center;">
    <span class="MathJax" id="MathJax-Element-6-Frame" tabindex="0" style="text-align: center;">
      <nobr>
       ------ omitted ------

Workaround currently is to add the css below to the “Additional CSS.”

.MathJax_Display{
	height: 55px;
	overflow-x: auto;
}

This enables formula with MathJax-LaTeX to fit the width of page and be scrolled with scroll bar.

How to scroll the source code in WordPress

How can I show all of the source code for mobile sites with plugin “Enlighter – Customizable Syntax Highlighter” in WordPress?

GOAL

To scroll source code embedded with Enlighter – Customizable Syntax Highlighter.

When my blog is seen in mobile, part of the source code is hidden and invisible.

Environment

WordPress 5.5.1
Enlighter – Customizable Syntax Highlighter 4.3.1

Method

Open Elighter>Appearance

Change the drop-down menu “Text overflow” to “Add scrollbar” and save changes.

Result

The scroll bar is add and I can see all of the source code from left end to the right end.