Month: July 2020

Create search.php for original theme

This is one of the articles about project “Create Original Theme in WordPress”.

GOAL

To create search.php and searchform.php

Environment

WordPress 5.5.1
XAMPP 7.4.10

search.php

It is easy to create search.php by copying and changing from archive.php.

<?php
/**
* The template to display search results
*@package WordPress
*@subpackage Techblog
*@since Techblog 1.0
*/
get_header(); ?>
<div class="container">
<main id="main" class="site-main">
	<div class= "main-content">
		<?php if ( have_posts() ) :?>
			<h1><?php echo esc_html__( 'Search Results for: ', 'techblog' ).'<span>'.esc_html(get_search_query()).'</span>'; ?></h1>
		<?php
			while ( have_posts() ) :
				the_post();
				get_template_part( 'content/content', 'search');
			endwhile;
				the_posts_pagination(
					array('prev_text' => '<u>Back<<</u>  ',
						'next_text' => '  <u>>>Next</u>', )
				);
		endif; ?>
	</div>
</main>
	<?php get_sidebar(); ?>
</div>
<?php
	get_footer(); ?>

Functions

get_search_query()

This function is used to get the posted search query from the search form. The definition is in wp-includes/general-template.php.

 function get_search_query( $escaped = true ) {
    $query = apply_filters( 'get_search_query', get_query_var( 's' ) );
    if ( $escaped ) {
        $query = esc_attr( $query );
    }
    return $query;
}

get_query_var( ‘s’ ) is the function to get the value of a query variable from the key ‘s’. So the input form should be named ‘s’.

get_template_part( $slug, $name = null, $args = array() )

This function is used to get template from {}-{}.php.

In my case, get the template from content/content-search.php by using get_template_part( ‘content/content’, ‘search’). But I don’t need content-search.php because the template content/content-search.php is the same as content.php.

Result

searchform.php

searchform is used as one of the widgets.

<?php
/**
* The search form template
*@package WordPress
*@subpackage Techblog
*@since Techblog 1.0
*/
?>

<form role="search" method="get" class="search-form" action="<?php echo esc_url( home_url( '/' ) ); ?>">
	<div class="search-group">
  		<label class="screen-label" for="s"><?php esc_html_e( 'Search:', 'techblog' ); ?></label><br/>
  		<span>
		<input type="text"  class="search-query" placeholder="<?php esc_attr_e('word', 'techblog;' ); ?>" value="<?php echo get_search_query(); ?>" name="s" title="<?php esc_attr_e( 'Search for:', 'techblog' ); ?>"/>
		<button type="submit" class="search-submit" name="submit" value="<?php esc_attr_e( 'Search', 'techblog' ); ?>"><span class="material-icons">search</span></button>
		</span>
	</div>
</form>

Result

Change the style

[Tips] How to fit p content in the parent box.

Problem

In HTML, some URL or long sentence sticks out of the parent box. The following is an example.

<div class="box">
	<p>This is an example of short message</p>
</div>
<br/>
<div class="box">
	<p>ThisIsAnExampleOfLongMessage</p>
</div>
.box{
	width:120px;
	border: 2px solid #111;
}

Result

The cause of this problem

This is because of the settings of word-break or overflow-wrap (or word-wrap). Define word break point by word-break css property or define when the browser should insert line breaks within an otherwise unbreakable string.

Reference: word-break, overflow-wrap

Solution

Solution1. Set “word-break” break-word

.box{
	width:120px;
	border: 2px solid #111;
	word-break: break-word;
}

Solution2. Set “overflow-wrap” break-word

.box{
	width:120px;
	border: 2px solid #111;
	overflow-wrap: break-word;
}

Result

Create comments.php for original theme

This is one of the articles about project “Create Original Theme in WordPress”.

GOAL

To create comments.php

Environment

WordPress 5.5.1
XAMPP 7.4.10

Method

WordPress has useful function to display comment form and functions to post comments.

comments.php

<?php
/**
* The comment form for techblog.
* @package WordPress
* @subpackage Techblog
* @since Techblog 1.0
*/
if ( post_password_required() ) {
	return;
}?>
<div class="comment-area">
	<div id="comments" class="comment-main">
		<?php if ( have_comments() ) : ?>
		<h3 class="comments-title">
			<?php echo "Comments for ".get_the_title(); ?>
		</h3>
		<ol class="comment-list">
			<?php wp_list_comments(
					array(
						'style'       => 'ol',
						'short_ping'  => true,
					)
				);
			?>
		</ol>
		<?php endif;?>
		<?php if (!comments_open() && get_comments_number() != '0' && post_type_supports( get_post_type(), 'comments' ) ) :?>
			<p class="no-comments"><?php esc_html_e( 'Comments are closed.', 'techblog' ); ?></p>
		<?php endif;
			comment_form();
		?>
	</div>
</div>

Functions

post_password_required()

post_password_required() is used to protect contents (posts) with password. This function detect whether post requires password and correct password has been provided.

have_comments()

This returns true if comments are available for current WordPress query.

wp_list_comments($args = array(), $comments = null)

This function is used to displays a list of comments for current post or page. The argument array $args defines formatting options.

Reference: Parameters of wp_list_comments() in wordpress.org

comments_open()

This returns true if the current post is open for comments.

get_comments_number()

This function return string that represent the number of comments for the current post or page.

post_type_supports( $post_type, $feature )

This function checks a post type’s support for a given feature. The first argument $post_type is the post type being checked and the second one $feature is the feature being checked.

In my case, get the post type of the current post with get_post_type(), and check if it is ‘comments’.

comment_form( $args = array(), $post_id = null )

comment_form() is used to output a complete commenting form for use within a template.

This function is used to displays a list of comments for current post or page. The argument array $args defines default arguments and form fields to override. You can use it to change class and id names.

Reference: Parameters of comment_form() in wordpress.org

Result

Change the style

Create sidebar.php for original theme

This is one of the articles about project “Create Original Theme in WordPress”.

GOAL

To create sidebar.php

Environment

WordPress 5.5.1
XAMPP 7.4.10

sidebar.php

<?php
/**
* The template used for the sidebar
*@package WordPress
*@subpackage Techblog
*@since Techblog 1.0
*/
?>
<?php if ( is_active_sidebar('sidebar') ) : ?>
	<aside id="sidebar">
	<?php dynamic_sidebar('sidebar'); ?>
	</aside>
<?php endif; ?>

functions.php

‘widgets_init’

‘widgets_init’ is the hook to initialize widgets such as sidebar. You should hook the register function register_sidebar() with add_action(). Please check the article “What is Hook in WordPress?” for detail about hook in WordPress.

In my case, techblog_widgets_init() is the function to register sidebar.

/*sidebar*/
function techblog_widgets_init() {
	register_sidebar( array(
		'name'          => esc_attr__( 'SideBar', 'techblog' ),
		'id'            => 'sidebar',
		'before_widget' => '<div id="%1$s" class="widget %2$s">',
		'after_widget'  => '</div>',
		'before_title'  => '<h3 class="widget-title">',
		'after_title'   => '</h3>',
	) );
}
add_action( 'widgets_init', 'techblog_widgets_init' );

Add widget

Add widgets into the created sidebar into the created sidebar with name “SideBar”.

Result

Change the style

Create footer.php for original theme

This is one of the articles about project “Create Original Theme in WordPress”.

GOAL

To create footer.php

Environment

WordPress 5.5.1
XAMPP 7.4.10

footer.php

<?php
/**
* The footer for techblog.
*@package WordPress
*@subpackage Techblog
*@since Techblog 1.0
*/
?>
<footer class="site-footer" role="contentinfo">
	<div class="footer-main">
		<div class="footer-info">
			<p class="footer-credits">
				<span class="footer-copyright">
					&copy;<?php echo esc_html( date_i18n('Y') );?> <a href="<?php echo esc_url(home_url());?>" rel="home"><?php bloginfo('name');?></a>
				</span>
				<span class="theme-credits">
					<?php echo '|Theme by <a href="s-nako.work"> Nako </a>' ?>
				</span>
			</p>
		</div>
	</div>
	<div class="scroll-to-top" onclick="location.href='#'">
		<span class="material-icons">navigation</span>
	</div>
</footer>
<?php wp_footer(); ?>
</body>
</html>

functions.php

/*-------------------
enqueue scripts
-------------------*/
add_action( 'wp_enqueue_scripts', 'techblog_scripts' );
function techblog_scripts() {
	//add icon with Google Material Icons
	wp_enqueue_style( 'google-mateial-style', "https://fonts.googleapis.com/icon?family=Material+Icons", null);
	//------omitted------
}

Functions

date_i18n()

This function retrieves the date in localized format, based on a sum of Unix timestamp and time zone offset in seconds.

It get format such as ‘Y-m-d H:i:s’, ‘l, F j, Y’ or ‘U’ as an argument. In this case, I’d like to retrieve year such as 2020. So I use template “Y”.

date_i18n('Y') /*output is 2020)*/

esc_html() and esc_url()

Escape functions in WordPress. Please check the article “Escape function in WordPress” for detail.

home_url()

This function retrieves the URL for the current site.

How to use icons with Google Material Icon

I used navigation icon in Google Material for the button to scroll to the top.

Search the icon , copy and paste the span tag.

From Google Material Icons page

Enqueue the css by using wp_enqueue_style() in functions.php

wp_enqueue_style( 'google-mateial-style', "https://fonts.googleapis.com/icon?family=Material+Icons", null);

You can use web icon service such as Font Awesome or Foundation Icon Fonts 3 in the same way.

Result

Change the style

Create header.php for original theme

This is one of the articles about project “Create Original Theme in WordPress”.

GOAL

To create header.php

Environment

WordPress 5.5.1
XAMPP 7.4.10

What content should be contained?

These are examples of contents in the header.

  • Title
  • Description
  • Menu

hader.php

<?php
/* *
* The Header for techblog.
*@package WordPress
*@subpackage Techblog
*@since Techblog 1.0
*/
?>

<!doctype html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<?php wp_head(); ?>
</head>

<body <?php body_class(); ?>>
<?php wp_body_open(); ?>

<header class="site-header">
	<a class="skip-link" href="#content"><?php esc_html_e( 'Skip to content', 'techblog' ); ?></a>
	<div class="header-main">
		<h1 class="site-title">
			<?php if (has_custom_logo()):
				the_custom_logo();
			else : ?>
				<a class="title-link" href="<?php echo esc_url( home_url( '/' ) ); ?>" title="<?php echo esc_attr(get_bloginfo('name'));?>"><?php echo esc_html(get_bloginfo('name'));?></a>
			<?php endif; ?>
			<span class="site-description">
				<?php echo esc_html(get_bloginfo('description'));?>
			</span>
		</h1>
		<?php 
		wp_nav_menu(
			array(
				'menu'				=> '',
				'theme_location'	=> '',
				'container'			=> 'div',
				'container_class'	=> 'manubar',
				'menu_class'		=> 'nav',
				'fallback_cb'		=> 'wp_page_menu',
				'items_wrap'		=> '<ul id="%1$s" class="%2$s">%3$s</ul>',
			)
		); ?>
	</div>
</header>

functions.php

/*-------------------
enqueue scripts
-------------------*/
add_action( 'wp_enqueue_scripts', 'techblog_scripts' );
function techblog_scripts() {
	// Add main theme stylesheet
	wp_enqueue_style( 'techblog-main-style', get_stylesheet_uri(), null);
}

Functions

wp_head()htmq.com/style/font-weight.shtml

The function wp_head() should be in <head></head>. This is initially the same as do_action(‘wp_head’).

function wp_head() {
    /**
     * Prints scripts or data in the head tag on the front end.
     *
     * @since 1.5.0
     */
    do_action( 'wp_head' );
}

This function fire functions attached to the hook ‘wp_head’. For example, some functions are added to the hook ‘wp_head’ in wordpress\wp-includes\default-filters.php as below.

// Actions.
add_action( 'wp_head', '_wp_render_title_tag', 1 );
add_action( 'wp_head', 'wp_enqueue_scripts', 1 );
add_action( 'wp_head', 'wp_resource_hints', 2 );
add_action( 'wp_head', 'feed_links', 2 );
add_action( 'wp_head', 'feed_links_extra', 3 );
add_action( 'wp_head', 'rsd_link' );
...

Please check “What is Hook in WordPress?” for details about hooks in WordPress.

body_class()

The function body_class() is displays the class names for the body element.

function body_class( $class = '' ) {
    // Separates class names with a single space, collates class names for body element.
    echo 'class="' . esc_attr( implode( ' ', get_body_class( $class ) ) ) . '"';
}

The following is an example of actual HTML output.

<body class="home blog logged-in admin-bar no-customize-support">

wp_body_open()

This function is initially the same as do_action(‘wp_body_open’).

function wp_body_open() {
    /**
     * Triggered after the opening body tag.
     *
     * @since 5.2.0
     */
    do_action( 'wp_body_open' );
}

Menu bar

wp_nav_menu(array $args = array())

wp_nav_menu() is the function to display navigation menu. the arguments list can be seen here.

How to import style.css in the header

It is recommended to use wp_enqueue_scripts instead of embedding <link rel=”stylesheet” href=”wordpress/wp-content/themes/techblog/style.css” type=”text/css”/> in header.php directly.

Add add_action( ‘wp_enqueue_scripts’, ‘<enque_function_name>‘ ); in functions.php of your theme.

add_action( 'wp_enqueue_scripts', 'techblog_scripts' );
function techblog_scripts() {
	// Add main theme stylesheet
	wp_enqueue_style( 'techblog-main-style', get_stylesheet_uri(), null);
}

Result

Change the style

Appendix

<link rel=”profile” href=”http://gmpg.org/xfn/11″>

In many WordPress themes, the link tag <link rel=”profile” href=”http://gmpg.org/xfn/11″> is contained within <head>. This tag is used for making relationship to  XMDP (Xhtml Meta Data Profiles). You don’t need include this. You can see more information in “What rel=profile is for?“.

How to use wp_enqueue_scripts in WordPress

GOAL

To understand what wp_enqueue_scripts() is and how to use it in WordPress

Environment

WordPress5.5.3

What is wp_enqueue_scripts?

‘wp_enqueue_scripts’ is one of the hooks built in WordPress. It can be used by hooking some function. Please visit “What is Hook in WordPress?” for details about hooks.

Reference: wp_enqueue_scripts in wordpress.org

When is it used?

‘wp_enqueue_scripts’ can be used to register and enqueue When calledscripts(.js) or stylesheet(.css) to your theme. It call attached function with add_action( ‘wp_enqueue_scripts’, ‘attached_function_name‘ );

Functions wp_register_script(), wp_register_style(), wp_enqueue_script() and wp_enqueue_style() can be used in the function attached to ‘wp_enqueue_scripts’.

register

Register functions registers a script(js file) or stylesheet(css file) to use later on WordPress.

enqueue

Enqueue function add registered script or stylesheet to the queue in which enqueued scripts and stylesheets are outputted in the header.

Why is is used?

That’s because it is better to register script once and use it in some different pages. While if you embed scripts and stylesheets directly in header php file, the scripts and stylesheets are loaded in all pages, sometimes you’d like to use scripts only one page or use different scripts in a special case.

How to use wp_enqueue_scripts

Add add_action( ‘wp_enqueue_scripts’, ‘my_enque_function’ ); in functions.php of your theme and define my_enque_function to register and enqueue scripts and stylesheets.

add_action( 'wp_enqueue_scripts', 'my_enque_function' );
function my_enque_function() {
    wp_register_style('mystyle', 'dir_name/css/style.css' );
    wp_register_script('myscript', 'dir_name/js/myfunc.js' );
    wp_register_style('font-styles', 'https://fonts.googleapis.com/css2?family=Open+Sans:ital@0;1&family=Roboto+Slab:wght@600;700&display=swap');
    wp_enqueue_style('mystyle');
    wp_enqueue_script('myscript');
    wp_enqueue_style('font-styles');
}

Register function can be omitted by using src arguments. Incidentally, the argument src is required in wp_register_style() and wp_register_script().

add_action( 'wp_enqueue_scripts', 'my_enque_function' );
function my_enque_function() {
    wp_enqueue_style('mystyle', 'dir_name/css/style.css' );
    wp_enqueue_script('myscript', 'dir_name/js/myfunc.js' );
    wp_enqueue_style('font-styles', 'https://fonts.googleapis.com/css2?family=Open+Sans:ital@0;1&family=Roboto+Slab:wght@600;700&display=swap');
}

[Tips]How to detect “Enter Key” pressed in C/C++?

GOAL

To detect enter key pressed in C/C++ program.

Environment

Windows 10
Visual Studio 2017

Method

Method 1. get char

If you just detect enter key pressed at any time, use getchar() or cin.get() function.

C language

#include <stdio.h>
#include <windows.h> // for Sleep function

int main(void)
{
	while(true){
		if (getchar() == '\n') {
			printf("Enter key is pressed");
			Sleep(1000); //wait for check printed message.
			break;
		}
	}
	return 0;
}

C++

#include <iostream>
using namespace std;

int main() {
	while (1) {
		if (cin.get() == '\n') {
			cout << "Enter key is pressed" << endl;
			break;
		}
	}
	return 0;
}

Method 2. get line

If you’d like to detect that only enter key is pressed without input another key before enter, use scanf() , fgets() or gets() in C language or getline() in C++

C language

#include <stdio.h>
#include <string.h>
#include <windows.h> // for Sleep function

int main(void)
{
	while (1) {
		//if (getchar() == '\n') {
		char str[32];
		gets(str);
		if(strcmp(str,"")==0){
			printf("Enter key is pressed");
			Sleep(1000); //wait for check printed message.
			break;
		}
	}
	return 0;
}

C++

#include <iostream>
using namespace std;

int main() {
	string str;
	while (1) {
		getline(cin, str);
		if (str == "") {
			cout << "Enter key is pressed" << endl;
			break;
		}
	}
	return 0;
}

Method 3. GetKeyState

GetKeyState() is only provided on Windows. You can get the current “state” of the key. It returns 0 when the key is not pressed.

The key code is here.

#include <iostream>
#include <windows.h> // for GetKeyState function
using namespace std;

int main() {
	cout << "some process here" << endl;
	while (1) {
		if (GetKeyState(VK_RETURN) < 0) {
			cout << "Enter Key is Pressing" << endl;
		}
		else if (GetKeyState(VK_ESCAPE) < 0) {
			break;
		}
	}
	return 0;
}

What is gettext

Gettext is an library for internationalization(I18N) and localization(L10N).

GOAL

To understand what is gettext and how to use it.

What is gettext

gettext is a library for translation in software. It can make sentences in the software multilingual.

pot file

Pot file is the template file for translation. Sentences to translate are defined in it.

po file

Translations of the sentences defined in pot file in each language are listed in po file.

mo file

mo file is binary file generated from po file.

domain

Domain is the identifier with that gettext module find the template for traslation.

How to use gettext in Python

Use gettext module.

Method 1. GNU gettext API

This method can work only in linux and unix because it uses the environment variables LANGUAGE, LC_ALL, LC_MESSAGES.
Reference: GNU gettext API

1. Create source file “gettext_test.py”

The argument ‘myapplication’ is domain and ‘locale_dir’ is the directory where mo file is.

import gettext

gettext.bindtextdomain('myapplication', 'locale_dir')
gettext.textdomain('myapplication')
_ = gettext.gettext
print (_('Hello World!'))

2. Create <domain>.pot file with pygettext.py that is in Python<version>\Tools\i18n directory. The pot file myapplication.pot will be generated in the directory “locale_dir”.

python Python<version>\Tools\i18n\pygettext.py -d myapplication -p locale_dir gettext_test.py

The following is generated myapplication.pot.

# SOME DESCRIPTIVE TITLE.
# Copyright (C) YEAR ORGANIZATION
# FIRST AUTHOR <EMAIL@ADDRESS>, YEAR.

msgid ""
msgstr ""
"Project-Id-Version: PACKAGE VERSION\n"
"POT-Creation-Date: 2020-07-20 01:35+0900\n"
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
"Language-Team: LANGUAGE <LL@li.org>\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=cp932\n"
"Content-Transfer-Encoding: 8bit\n"
"Generated-By: pygettext.py 1.5\n"

#: gettext_test.py:7
msgid "Hello World!"
msgstr ""

3. Create po file and put it in the language directory.

Change the charset into utf-8, input the translation and save it chadnged myapplication.po. In my case, the Japanese “こんにちは世界!” that means “Hello World!” is put in msgstr.

# SOME DESCRIPTIVE TITLE.
.
.
.
"Content-Type: text/plain; charset=utf-8\n"
.
.
.
#: gettext_test.py:7
msgid "Hello World!"
msgstr "こんにちは世界!"

Put the chadnged myapplication.po in the <directory_name>/language/LC_MESSAGES. The language is <language codes>_<country codes>. I put it in locale_dir/ja_JP/LC_MESSAGES.
The list of language code and country code: ISO-3166 Country Codes and ISO-639 Language Codes

4. Generate mo file from po file with Python<version>\Tools\i18n\msgfmt.py

python Python<version>\Tools\i18n\msgfmt.py myapplication.po

This image is the file construction.

5. Execute gettext_test.py

python gettext_test.py
こんにちは世界!

Method 2. Class-based API

This can be used in linux, unix and Windows.
Reference: Class-based API

1. Create source file “gettext_test.py”

Use translation(). The argument ‘myapplication’ is domain and ‘locale_dir’ is the directory where mo file is.

import os
import gettext

_ = gettext.translation(
    domain='myapplication',
    localedir = 'locale_dir',
    languages=['ja_JP'], 
    fallback=True).gettext

print (_('Hello World!'))

The rest processes are same as “Method 1. GNU gettext API” above.

2. Create <domain>.pot file with pygettext.py

3. Create po file and put it in the language directory <directory_name>/language/LC_MESSAGES.

4. Generate mo file from po file with Python<version>\Tools\i18n\msgfmt.py

5. Execute gettext_test.py

python gettext_test.py
こんにちは世界!

What is pch.h

When I create a new C/C++ project in VisualStudio, an header file named “pch.h” is generated.

GOAL

To understand what is pch.h and how to use it.

Environment

Windows 10
VisualStudio 2017

What is pch.h

pch.h is a precompiled header that is an header file where any stable header files such as Standard Library headers are included. You can add header files you’d like to pre compile. The precompiled header is compiled only when it, or any files it includes, are modified.

Reference: Precompiled Header Files in Microsoft documentation

The following is initial pch.h

#ifndef PCH_H
#define PCH_H

// TODO: add headers that you want to pre-compile here
#endif //PCH_H

The advantage of pch.h

Using pch.h reduce compilation time, especially when applied to large header files, header files that include many other header files.

How to use pch.h

Add header files you’d like to use in the pch.h as below.

#ifndef PCH_H
#define PCH_H

#include <stdio.h>
#include <math.h>
#include "myheader.h"

#endif //PCH_H