Category: PHP

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

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.

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 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 use posted data in the same page

GOAL

To post the input data and display it on the same page with PHP.

Environment

Windows10
XAMPP 7.4.10

Preparation

1. Change the PHP program

Create a new PHP file “index.php” to submit data. You can see the details of this program in “How To Run PHP in XAMPP“.

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>test</title>
</head>
<body>
	<form action="posted.php" method="POST">
		<label>Input message:</label>
		<input type="text" name="message" /> <input type="submit" value="Submit!" />
	</form>
</body>
</html>

2. Set action = “”

The action specifies the file to call. If you won’t move the page, action should be “”.

Method

Method 1. Use $_SERVER[‘REQUEST_METHOD’]

$_SERVER[‘REQUEST_METHOD’] is the variable to store the requested method. It returns the called requested method when the page is requested.

<body>
	<?php
	if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    	echo "The input data is ".$message;
    }
    ?>
	<form action="" method="POST">
		<label>Input message:</label>
		<input type="text" name="message" /> <input type="submit" value="Submit!" />
	</form>
</body>

Method 2. Use $_POST directly

<body>
	<?php
	if ($_POST) {
    	echo "The input data is ".$_POST['message'];
    }
    ?>
	<form action="" method="POST">
		<label>Input message:</label>
		<input type="text" name="message" /> <input type="submit" value="Submit!" />
	</form>
</body>

The result is the same as above.

Method 3. Use isset($_POST[‘message’])

<body>
	<?php
	if ($_POST) {
    	echo "The input data is ".$_POST['message'];
    }
    ?>
	<form action="" method="POST">
		<label>Input message:</label>
		<input type="text" name="message" /> <input type="submit" value="Submit!" />
	</form>
</body>

The result is the same as above. The strong point of this method is that the existence of each keys of $_POST can be determined.