Author: Nako

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.

How To Backup WordPress

GOAL

To backup the content of WordPress.

Environment

WordPress 5.5.1

Method

Method 1. Download data from the server directly

Access the server where “wp” directory exits.

Open “wp” directories and download “wp-content” directory that contains all uploaded files such as images and videos, plugins and themes installed. wp-includes and wp-admin can be recovered from WordPress.org.

“wp-content” doesn’t contain text and information of the articles. It is saved in the SQL database. You can download it by clicking Tools>Export in Dashboard.

Then select “All content” and click “Download Export file” button.

Method 2. Use Plugins

There are some plugins for backup.

I use All-in-One WP Migration because it is easy to use and has some useful functions in addition to backup.

The way for backup is to click backup button and just download created file.

How To Use Qt Designeer

GOAL

To understand what QtCreator is and how to use it.

What is Qt and PySide?

Qt is a cross-platform application framework with many modules providing services like network abstraction and XML handling, along with a very rich GUI package. Check the article “First PySide Application” for details of Qt and PySide.

What is Qt Designer?

Qt Designer is the Qt tool for designing and building GUIs with Qt Widgets. Qt Designer makes it easy to layout UI widgets with PySide.
Reference: Qt Designer Manual

How to use

Environment

Windows10
Python3.8.5
PySide2-5.15.1

Install and Start Qt Designer

1. Install PySide or PySide2

pip install PySide2
Collecting PySide2
  Downloading PySide2-5.15.1-5.15.1-cp35.cp36.cp37.cp38.cp39-none-win_amd64.whl (136.9 MB)
     |████████████████████████        | 101.6 MB 1.7 MB/s eta 0:00:22    
...
omitted
...
Successfully installed PySide2-5.15.1 shiboken2-5.15.1

Use pip3 if you need. When you use Python2, PySide2 can’t be installed by pip command, so please install python3 or use PySide.

2. Start designer.exe

Start PythonDir\site-packages\PySide2\designer.exe

You can find the directory “PySide2” by PySide2.__file__

import PySide2
print(PySide2.__file__)

Or you can find the python directory with the command below.

C: >where python

If you are using Python2, designer.exe exists in Python2\Lib\site-packages\PySide directory.

Create Dialog

1. Create a new form

When you start the designer.exe, the “New Form” window will open automatically. If not, click File > New

Select any template you like and click the button “Create”.

An empty untitled widget with “OK” and “Cancel” buttons will appear.

2 Put the widget on the empty Dialog

Drag & Drop any widget you like from “Widget Box” and put it into the empty Dialog. I created a dialog to export reduced object in DCC tool.

from Qt Designer

The construction of this form is the following.

And reform the widgets in main layout. Right-click on the form outside of the form Layout and click layout>Lay Out Vertically.

The widgets are arranged at even intervals in the main layout.

Set the default values and change settings of each property with “Property Editor.”

from Qt Designer

3. Connect the signals to the slots

In Qt Designer, you can connect the signal of the widget to the slot of another widget, in other words connect some widgets as input and output. In this case, Spin Box and Horizontal Slider should move in conjunction with each other.

Change the mode to edit signals/slots by clicking Form>Edit Signals/Slots.

Drag & drop from Spin Box to Horizontal Slider.

The signal is valueChanged and the connected slot is setValue.

In contrast, drag & drop from Horizontal Slider to Spin Box and connect them in the same way.

4. Preview

Preview the form you created by Form>Preview… and check if it works well.

5. Save the UI as Designer UI files (.ui)

Save the dialog you created as “reduced_export.ui”.

Load .ui from Python file

You can load .ui file you created from python file.

Run the program below and the dialog you created will be displayed.

# -*- coding: utf-8 -*
import sys
from PySide2 import QtWidgets
from PySide2.QtUiTools import QUiLoader

if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    loader = QUiLoader()
    widget = loader.load('reduced_export.ui', None)
    if not widget:
        print(loader.errorString())
        sys.exit(-1)
    widget.show()
    sys.exit(app.exec_())

Or define ExportUI class that inherits QMainWindow.

class ExportUI(QtWidgets.QMainWindow):
    def __init__(self, parent=None):
        super(ExportUI, self).__init__(parent)
        loader = QUiLoader()
        self.ui = loader.load('reduced_export.ui')
        if not self.ui:
            print(loader.errorString())
            sys.exit(-1)
        print("OPEN")
    def getUi(self):
        return self.ui

if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    exportUi = ExportUI()
    widget = exportUi.getUi()
    widget.show()
    sys.exit(app.exec_())

Connect functions you defined to the widgets

When the “OK” button is clicked, or the buttonBox widget is accepted, call the function export() that is the function to export the selected object in DCC tools. You can connect them by using “self.ui.buttonBox.accepted.connect(self.export)”.

In this example the function export() is omitted.

# -*- coding: utf-8 -*
import sys
from PySide2 import QtWidgets
from PySide2.QtUiTools import QUiLoader

def exportObj(name, extension, detail, options):
    # omitted the function to export object
    ext = 'fbx' if extension else 'obj' 
    print(f"exported {name}.{ext} with {detail}% detail and option {options}.")

class ExportUI(QtWidgets.QMainWindow):
    def __init__(self, parent=None):
        super(ExportUI, self).__init__(parent)
        loader = QUiLoader()
        self.ui = loader.load('reduced_export.ui')
        if not self.ui:
            print(loader.errorString())
            sys.exit(-1)
        print("OPEN")
        self.ui.buttonBox.accepted.connect(self.export)

    def getUi(self):
        return self.ui

    def export(self):
        name = self.ui.nameLineEdit.text()
        extension = 0 if self.ui.radioButton.toggle() else 1
        detail = self.ui.horizontalSlider.value()
        options = [self.ui.checkBox.isChecked(), self.ui.checkBox_2.isChecked() ,self.ui.checkBox_3.isChecked()]
        exportObj(name, extension, detail, options)

if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    exportUi = ExportUI()
    widget = exportUi.getUi()
    widget.show()
    sys.exit(app.exec_())

You should know the classes and functions to get values such as QnameLineEdit.text() or QRadioButton.isChecked(). And you can see the class and the name of each widget in Property Editor of Qt Designer.

Run

Run the python code above and set the values on the displayed dialog.

Click the “OK” button. Then the message below will be displayed on the console.

exported HumanModel.fbx with 66% detail and option [False, True, True].

Other tools for Qt programming

QtCreator

QtCreator is C++ IDE for development with Qt. It has an editor with useful functions, navigation tools, GUI tools for UI design and so on.
Reference: Qt Creator Manual

Qt Linguist

Qt Linguist is a tool for translating Qt C++ and Qt Quick applications into local languages.
Reference: Qt Linguist Manual

Qt Assistant

Qt Assistant is a tool for viewing on-line documentation for Qt programming. 
Reference: Qt Assistant Manual

[Tips]How to switch python3 and python2 in VSCode

I ‘ve been using python2 in VSCode for a long time, but I have to run python3 code this time. How to switch python2 and python3?

GOAL

To switch python2 and python3 in VSCode

Environment

Windows10
python2.7 and python3.8.5
Visual Studio Code1.49.0

Method

Open command palette with the shortcut Ctrl+Shift+P. *If you are working on macOS, use the shortcut Command+Shift+P.

And select “select interpreter”

from VSCode

And choose the python version that you’d like to use.

from VSCode

If you need, please install Linker such as pylint for the new version of python.

First PySide Application

GOAL

To understand Qt and PySide(PySide2) and create PySide application that

Emvironment

WIndows10
Python2.7.8

*I use python2 because python3 can’t be used in Maya, but I think python3 is better for general application development. And PySide2 which is used in Maya2017~ is easy to use in python3.

What is Qt?

Qt is a cross-platform application framework with many modules providing services like network abstraction and XML handling, along with a very rich GUI package.

Though Qt is developed in C++, it can be used in Python, Java, Perl and so on with API. The application developed with Qt can be executed in any platform such as Windows, Linux, macOS, desktop and mobile.

Qt has been upgraded constantly, and the latest version in 2020 is Qt5.

What is PySide?

PySide is the python module as a Python binding of Qt. Functions, variables and modules of Qt can be used in Python via PySide. GUI application can be developed on multi platform, windows, Linux and macOS using Python with PySide.

PySide and Pyside2

PySide2 is upgraded PySide. PySide2 provides access to the Qt 5 framework while PySide provide access to Qt4 or below. Qt4 and PySide can be used in Maya2016 and before, Qt5 and PySide2 is used in Maya2017 and after.

If you are using python2, it’s easy to install PySide by using pip install, but you should build PySide2 by yourself. So If you want to use PySide2, please use python3 and its pip install.

The difference between PySide and PyQt

PyQt is also one of the python modules as a Python binding of Qt. The document “Differences Between PySide and PyQt” is clear and detailed. And “PyQt vs Pyside” is easy to understand their advantages and disadvantages.

Method

The following is the method to create your first PySide application. This is for PySide so please replace words for PySide2 if you need.

Install PySide

Open Command prompt and input pip command. In my case, ‘pip2’ is used because python3 is installed and the command just ‘pip’ is equal to pip3.

> pip2 install pyside

Check if PySide is successfully installed.

>py -2
Python 2.7.8....
>>> import PySide
>>> PySide.__version__
'1.2.4'
>>>

Hello World

This is an application program to display HelloWorld.

import sys
from PySide.QtCore import *
from PySide.QtGui import *

#Create QApplication
firstApp = QApplication(sys.argv)
# Create a Label
label = QLabel("Hello World")
label.show()
# Enter Qt application main loop
firstApp.exec_()
sys.exit()

Execute and small window will appear.

QtGui

QtGui module contains classes that control widgets of PySide. Widget is a UI component that is used in GUI application such as button, label, Matrix, Layout and so on. You can see all class in PySide.QtGui.

Create Widget

You can create original widget as a Class. Add single widgets into QVBoxLayout.

import sys
from PySide.QtCore import *
from PySide.QtGui import *

class MyWidget(QWidget):
    def __init__(self):
        super(MyWidget, self).__init__()
        self.text = QLabel("Say Hello")
        self.text.setAlignment(Qt.AlignCenter)
        self.edit = QLineEdit("who?")
        self.button = QPushButton("Click here")
        self.output = QLabel("")
        self.layout = QVBoxLayout()
        self.layout.addWidget(self.text)
        self.layout.addWidget(self.edit)
        self.layout.addWidget(self.button)
        self.layout.addWidget(self.output)
        self.setLayout(self.layout)
        self.button.clicked.connect(self.sayHello)

    def sayHello(self):
        self.output.clear()
        self.output.setText("Hello " + self.edit.text()+"!")
        
if __name__ == '__main__':
    app = QApplication(sys.argv)

    widget = MyWidget()
    widget.resize(300, 100)
    widget.show()
    widget.setWindowTitle("My Widget Test")
    sys.exit(app.exec_())

This is the window. Input name into line edit and click the button.

Then name you enter in the field is displayed.