Category: WordPress

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');
}

How To Recover From An Error Caused By Plugin

I could neither open nor edit a post in WordPress. The error “Uncaught (in promise) TypeError: Cannot read property ‘replace’ of undefined” occurred.

Problem

I created a post with “Enlighter Sourcecode” block by using Enlighter plugin and save the post. When I opened the saved post, the error “Uncaught (in promise) TypeError: Cannot read property ‘replace’ of undefined” occurred and nothing was displayed.

Environment

WordPress 5.5.3
Enlighter – Customizable Syntax Highlighter 4.4.1

The cause of this problem

Reference: Unable to edit posts when EnlighterJs is enabled

The block is somehow corrupted.

Solution

1. Deactivate the plugin at issue.

2. Open the post in edit mode and copy all contents.

3. Activate the plugin again. And create new post and paste it.

Create single.php for original theme

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

GOAL

To create single.php

Environment

WordPress 5.5.1
XAMPP 7.4.10

single.php

<?php
/**
*this is the single post template
*@package WordPress
*@subpackage Techblog
*@since Techblog 1.0
*/
get_header(); ?>
<div class="container">
<main id="main" class="site-main">
	<?php
		while ( have_posts() ) :
			the_post();
			get_template_part( 'content/content', 'single' );
			if ( comments_open() || '0' != get_comments_number() ) :
				comments_template();
				endif;
	endwhile;
	?>
</main>
<?php get_sidebar();?>
</div>
<?php get_footer(); ?>

content/content-single.php

<?php
/**
 * The template used for displaying single post content in single.php
*@package WordPress
*@subpackage Techblog
*@since Techblog 1.0
*/
?>
<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
	<div class="main-content">
		<div class="page-item">
			<h1 class="entry-title"><?php the_title(); ?></h1>
			<div class="post-info">
				<span class="sns"><a href="https://twitter.com/share" data-url="<?php the_permalink(); ?>" data-text="<?php echo get_the_title(); ?>" class="twitter-share-button" data-via="nako_new_high" data-show-count="false">Tweet</a><script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script></span><br/>
        		<span class="post-date"><?php the_date();?></span>
        		<?php
        			$post_categories = get_the_category();
        			if ( $post_categories ) {
						foreach( $post_categories as $category ): ?>
						<span class= "post-categories"><a class="category" href= "<?php echo get_category_link($category->term_id) ?>" >
						<?php echo $category->cat_name ?>
						</a></span>
					<?php endforeach; ?>
				<?php }; ?>
				<br/>
				<?php if ( has_tag() ) : ?>
					<?php $tags = get_the_tags( get_the_ID() );
						foreach ( $tags as $tag ) {
							echo '<span class= "post-tags"><a href="'. get_tag_link( $tag->term_id ) . '">#' . $tag->name . '</a></span>';
						}
					?>
		  		<?php endif; ?>
        	</div>
		  	<?php the_content(); ?>
		</div>
	</div>
</article>

Functions

has_tag()

This return true if the current post has tags.

get_the_tags( get_the_ID())

get_the_tags() retrieves the tags for the post that takes the id of the post as an argument. get_the_ID() retrieve the ID of the current item.

The tag objects can be retrieved by using for loop.

get_tag_link()

This function retrieves the link to the tag. It gets tag ID or object as an argument.

Result

Change the style

Create 404.php for original theme

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

GOAL

To create 404.php

Environment

WordPress 5.5.1
XAMPP 7.4.10

What content should be contained?

These are examples of contents in the 404 page.

  • Search
  • Category list
  • Recent posts
  • Archives of year or month
  • Links

Examples

There are many unique and interesting designs of 404 pages.

10 great examples of 404 error pages

20 Top Examples of 404 Error Pages

404.php

<?php
/**
*this is the 404 page template
*@package WordPress
*@subpackage Techblog
*@since Techblog 1.0
*/
get_header(); ?>
<div class="container">
<main id="main" class="site-main">
	<div class= "main-content">
		<h1>404! Sorry, the page can't be found.</h1>
			<br/>
		<?php get_search_form(); ?>
		<h2>Recent Posts</h2>
		<?php
			$lastposts = get_posts( array(
    			'posts_per_page' => 4
			) ); ?>
		<div class="post-item recent-post">
			<?php if ( $lastposts ) {
    			foreach ( $lastposts as $post ) : setup_postdata( $post ); ?>
        		<h3><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3>
    	    		<div class="post-info">
        				<span class="post-date"><?php the_date();?></span>
        				<?php $post_categories = get_the_category();
        				if ( $post_categories ) {
							foreach( $post_categories as $category ): ?>
								<span class= "post-categories"><a class="category" href= "<?php echo get_category_link($category->term_id) ?>" >
								<?php echo $category->cat_name ?>
								</a></span>
							<?php endforeach; ?>
						<?php }; ?>
        			</div>
        	<?php endforeach; 
    		wp_reset_postdata();
			}?>
		</div>
		<h2>Categories</h2>
		<?php
			$categories = get_categories();
			if ( $categories ) {
				foreach( $categories as $category ): ?>
					<a class="index category" href= "<?php echo get_category_link($category->term_id) ?>" >
					<?php echo $category->cat_name ?>
					</a>
				<?php endforeach; ?>
			<?php }; ?>
	</div>
</main>
<?php get_sidebar(); ?>
</div>
<?php get_footer(); ?>

Result

Change the style

Create archive.php for original theme

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

GOAL

To create page.php

Environment

WordPress 5.5.1
XAMPP 7.4.10

archive.php

<?php
/**
 * The template to display posts archve
 *@package WordPress
 *@subpackage Techblog
 *@since Techblog 1.0
 */
 get_header(); ?>
<main id="main" class="site-main" role="main">
	<div class= "main-content">
	<?php if ( have_posts() ) :?>
		<header class="page-header">
			<?php
				the_archive_title('<h1>', '</h1>' );
				the_archive_description();
			?>
		</header>
		<?php
			while ( have_posts() ) :
				the_post();
				get_template_part( 'content/content', get_post_format() );
			endwhile;
			the_posts_pagination(
				array('prev_text' => '<u>Back<<</>  ',
					'next_text' => '  <u>>>Next</>', )
			);
		endif; ?>
	</div>
</main>
<?php
	get_sidebar();
	get_footer(); ?>

contetnt.php

/**
*@package WordPress
*@subpackage Techblog
*@since Techblog 1.0
*/
?>
<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
	<div class="main-content">
		<div class="post-item">
			<a href="<?php the_permalink(); ?>"></a>
			<h2 class="entry-title"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
			<div class="post-info">
				<span class="sns"><a href="https://twitter.com/share" data-url="<?php the_permalink(); ?>" data-text="<?php echo get_the_title(); ?>" class="twitter-share-button" data-via="nako_new_high" data-show-count="false">Tweet</a><script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script></span><br/>
				<span class="post-date"><?php the_date();?></span>
				<?php 
					$post_categories = get_the_category();
        			if ( $post_categories ) {
						foreach( $post_categories as $category ): ?>
						<span class= "post-categories"><a class="category" href= "<?php echo get_category_link($category->term_id) ?>" >
						<?php echo $category->cat_name ?>
						</a></span>
						<?php endforeach; ?>
					<?php }; ?>
			</div>
			<?php the_content(); ?>
		</div>
		<?php if ( is_search() ) : ?>
			<div>
				<?php the_excerpt(); ?>
				<p><a class="read-more" href="<?php the_permalink(); ?>"></p>
			</div>
		<?php endif; ?>
	</div>
</article>

Functions

the_archive_title()

This function displays the archive title such as “Search: <word>” or “Category: <category_name>”

You can use html tags as argument before and after.

the_archive_title('<h1 class = "class_name">', '</h1>' );

the_archive_description()

This function displays category, tag, term, or author description. You can use html tags as argument before and after.

the_posts_pagination(array $args = array())

This function displays a paginated navigation to next/previous set of posts, when applicable.

the_posts_pagination( array(
    'mid_size'  => 2,
    'prev_text' => __( '<u>Back</u>'),
    'next_text' => __( '<u>Next</u>'),
) ); 
Result

<article id=”post-<?php the_ID(); ?>” <?php post_class(); ?>>

the_ID() returns the unique id of current post and post_class() returns the classes for the post container element.

is_search()

This returns true if the query is for a search.

Result

Change style

How to add Tags in WordPress

GOAL

To understand tags in WordPress and how to add it.

Environment

WordPress 5.5.1

Examples

<!–nextpage–>

This tag is used to split a single post up into different web pages.

<!–more>

This tag is used to add the “Read More” to the post.

How to add tags

Create new widget “Custom HTML” in the editing page.

Input the tag in the Input the tag in the Custom HTML widget.

Appendix

If your theme doesn’t support nextpage, put wp_link_pages() function on the php file in the theme.

<?php
	the_content();
	wp_link_pages();
?>

Create page.php for original theme

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

GOAL

To create page.php

Environment

WordPress 5.5.1
XAMPP 7.4.10

page.php

page.php is used to display fixed page such as “About”, “Access”, “Contact” and so on.

<?php
/**
*this is the fixed page template
*@package WordPress
*@subpackage Techblog
*@since Techblog 1.0
*/
get_header(); ?>
<div class="container">
<main id="main" class="site-main">
	<?php
		while ( have_posts() ) : the_post(); ?>
			<?php get_template_part( 'content/content', 'page' ); ?>
			<?php
				// If comments are open or we have at least one comment, load up the comment template
				if ( comments_open() || '0' != get_comments_number() ) :
					comments_template();
				endif;
			?>
		<?php endwhile;?>
</main>
<?php get_sidebar(); ?>
</div>
<?php get_footer(); ?>

content/content-page.php

<?php
/**
 * The template used for displaying page content in page.php
*@package WordPress
*@subpackage Techblog
*@since Techblog 1.0
 */
?>
<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
	<div class= "main-content">
		<div class="page-item">
			<h1 class="entry-title"><?php the_title(); ?></h1>
			<div class="post-info">
				<span class="sns"><a href="https://twitter.com/share" data-url="<?php the_permalink(); ?>" data-text="<?php echo get_the_title(); ?>" class="twitter-share-button" data-via="nako_new_high" data-show-count="false">Tweet</a><script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script></span><br/>
				<span class="post-date"><?php the_date();?></span>
			</div>
			<?php
				the_content();
				wp_link_pages();
			?>
			<?php if(get_edit_post_link()) : ?>
				<footer>
					<?php edit_post_link(); ?>
				</footer>
			<?php endif; ?>
		</div>
	</div>
</article>

page.php and content-page.php

content-page.php is one of the template parts that is loaded by using get_template_part() in page.php.

Functions

get_template_part($slug, $name )

This function loads a template part $slug.php or $slug-$name.php into a template.

comments_open()

Determines whether the current post is open for comments.

comments_templatestring $file = ‘/comments.php’)

This loads comment template defined by /comments.php, (but the comments.php is nor generated yet).

wp_link_pages()

The formatted output of a list of pages. This is used for repagination.

Result

Change the style

Create index.php for original theme

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

GOAL

To create index.php

Environment

WordPress 5.5.1
XAMPP 7.4.10

index.php

<?php
/**
*This is main file for "techblog" theme
*@package WordPress
*@subpackage Techblog
*@since Techblog 1.0
 */
get_header(); ?>
<div class="container">
<main id="main" class="site-main">
	<div class= "main-content">
	<h1>Recent Posts</h1>
	<?php
		$lastposts = get_posts( array(
    		'posts_per_page' => 3
		) );
		if ( $lastposts ) {
    		foreach ( $lastposts as $post ) : setup_postdata( $post ); ?>
    			<div class="post-item recent-post">
        		<h2 class="entry-title"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
        		<div class="post-info">
        			<span class="post-date"><?php the_date();?></span>
        			<?php
        				$post_categories = get_the_category();
        				if ( $post_categories ) {
							foreach( $post_categories as $category ): ?>
							<span class= "post-categories"><a class="category" href= "<?php echo get_category_link($category->term_id) ?>" >
							<?php echo $category->cat_name ?>
							</a></span>
						<?php endforeach; ?>
					<?php }; ?>
        		</div>
        		<?php the_excerpt(); ?>
        		</div>
    	<?php endforeach; 
    		wp_reset_postdata();
		}?>
	<h1>Categories</h1>
	<?php
		$categories = get_categories();
		if ( $categories ) {
			foreach( $categories as $category ): ?>
				<a class="index category" href= "<?php echo get_category_link($category->term_id) ?>" >
				<?php echo $category->cat_name ?>
				</a>
			<?php endforeach; ?>
		<?php }; ?>
	</div>
</main>
<?php 
get_sidebar(); ?>
</div>
<?php 
get_footer(); ?>

Functions

get posts

$lastposts = get_posts( array('posts_per_page' => 3) );

loop the posts

if ( $lastposts ) {
foreach ( $lastposts as $post ) : setup_postdata( $post ); ?>
 HTML is here
<?php endforeach; ?>

This is equal to the following.

if ( $lastposts ) {
	foreach ( $lastposts as $post ) {
		setup_postdata( $post ); 
		// Do something here
	}
}

get the url of each post that is “root/<year>/<month>/<day>/<title>/” by default.

the_title(); // works in the loop

get the title of each post

the_date(); //works in the loop

get the date when the post is posted

the_date(); //works in the loop

get the categories of current post

$post_categories = get_the_category();

loop the categories

if ( $post_categories ) {
	foreach( $post_categories as $category ): ?>
		HTML is here
	<?php endforeach; ?>
<?php }; ?>

This is equal to the following.

if ( $post_categories ) {
	foreach( $post_categories as $category ){
		HTML is here
	}
}

get the url of the category that is “root/category/<category name>/” by default

get_category_link($category->term_id)

get the category name from $category

$category->cat_name

get the excerpt of the post

the_excerpt();

How to change the length of the excerpt

Add filter in the functions.php. If you’d like to know about add_filter(), please check the article “What is Hook in WordPress?“.

function twpp_change_excerpt_length( $length ) {
  return 20;
}
add_filter( 'excerpt_length', 'twpp_change_excerpt_length', 999 );

get all categories of the site

$categories = get_categories();

Result

Change style

I customized the design of the page by editing style.css.

What is Hook in WordPress?

GOAL

To understand what is the hook in WordPress and how to use it.

Environment

WordPress 5.5.1

What the hook is in WordPress

Hooks are a way for one piece of code to interact/modify another piece of code at specific, pre-defined spots.

from Plugin Handbook in wordpress.org

When the specific event occurs, the registered function is hooked.

For example, if you define the function addName() and add it to the hook ‘the_content’, you can add name to the content of the article.

$name = 'Nako';
function addName($content) {
    return $content .'('.$name.')';
}
add_filter('the_content', 'addName');

Add filter and action

There are 2 types of hook, filter and action. You can see the list of filters in Plugin API/Filter Reference and the list of actions in Plugin API/Action Reference.

The filter hooks are defined by apply_filters() and add function to the filter hook by add_filter(). And the action hools are defined by do_action() and add action to the action hook by add_action().

The following is the outline diagram of apply_filters, do_action, add_action and add_filter.

Example

For example, this is one of the apply_filters functions in post-template.php.

function the_content( $more_link_text = null, $strip_teaser = false ) {
	$content = get_the_content( $more_link_text, $strip_teaser );

	$content = apply_filters( 'the_content', $content );
	$content = str_replace( ']]>', ']]>', $content );
	echo $content;
}

The difference between filters and actions

Action is used to do some user-defined action, but on the other hands filter is used to rewrite or return the variable. So the function added by add_filter() has always return value.

Why does category list return “Uncategorized”?

Problem

I’d like to display the list of all categories in my theme, but it return “Uncategorized”. The PHP code in index,php is as below.

<h1>Categories</h1>
<?php
	$categories = get_the_category();
	if ( $categories ) {
		foreach( $categories as $category ) {
			$output .= '<a href="' . get_category_link($category->term_id) 
			. '">' . $category->cat_name . '</a>' . ' ';
		}
		echo $output;
	}
?>

The result is the following.

The cause of this problem

get_the_category(); is the function to get the categories of “current” post or page. This page is index.php with no category, so it return “Uncategorized”.

Solution

Use get_categories(); instead of get_the_category();.

<h1>Categories</h1>
<?php
	$categories = get_categories();
	if ( $categories ) {
		foreach( $categories as $category ) {
			$output .= '<a href="' . get_category_link($category->term_id) 
				. '">' . $category->cat_name . '</a>' . ' ';
		}
	echo $output;
	}
?>

This is the result.