Category: PHP

Implementation Of Ajax (Search Suggestion)

GOAL

Today’s goal is to implement a search suggestion as below. The suggestion should be displayed without page transition while inputting the search word.

Environment

Windows10
XAMPP 7.4.10

What is Ajax

AJAX, Asynchronous JavaScript And XML, is a term that refers to a group of Web development techniques for asynchronous communication on the client side using JavaScript. Please check “What Is AJAX (and Asynchronous Communication)?” for details about ajax.

The following is a brief explanation about the ajax mechanism.

How Ajax works

In Ajax, the 2 system “sending the request and getting the response from the server” and “get the data from the browser and reflect the received data to the browser” are separated. So users can operate on the browser while waiting the response.

This image has an empty alt attribute; its file name is image-2.png
(more…)

How To Create JSON Data In PHP

JSON is used for data exchange in PHP. But how can I create json data in php and pass it to JavaScript?

GOAL

Today’s goal is to generate Json data from PHP array and get the data in JavaScript. This can be used when getting data from the server in PHP and processing the data in JavaScript.

Method

1. Create a nested array data

<?php
$teachers = []
$teachers = [
    "101" => [
        "name" => "Poppins",
        "class" => "music",
    ],
    "102" => [
        "name" => "Dolittle",
        "class" => "natural history",
    ],
    "103" => [
        "name" => "Snape",
        "class" => "pharmacy",
    ],
];
?>

You can create the nested array with for loop, too.

<?php
$teachers = [];
$data_set = [["101", "Poppins", "music"],["102", "Dolittle", "natural history"],["103", "Snape", "pharmacy"]];
for($i=0; $i < count($data_set); $i++){
    $teacher = $teachers_list[$i];
    $teachers += array($teacher[0] => array("name" => $teacher[1], "class" => $teacher[2]));
}
?>

2. Generate Json with json_encode() function

<?php
echo json_encode($teachers);
?>
//output => {"101":{"name":"Poppins","class":"music"},"102":{"name":"Dolittle","class":"natural history"},"103":{"name":"Snape","class":"pharmacy"}}

3. Get the data in JavaScript

Get the json string from the variable $teachers and convert the string to the Object with JSON.parse().

<script type="text/javascript">
    var json_str='<?php echo json_encode($teachers); ?>';
    var json_obj = JSON.parse(json_str);
    console.log(json_str)
    for(k in json_obj){ // get keys
        var teacher = json_obj[k];
        console.log("name: " + teacher['name']);
        console.log("class: " + teacher['class']);
    }
/*
--console output--
name: Poppins
class: music
name: Dolittle
class: natural history
name: Snape
class: pharmacy
*/
</script>

Source Code

The Completed Code is as below.

<?php
$teachers = [];
$teachers = [
    "101" => [
        "name" => "Poppins",
        "class" => "music",
    ],
    "102" => [
        "name" => "Dolittle",
        "class" => "natural history",
    ],
    "103" => [
        "name" => "Snape",
        "class" => "pharmacy",
    ],
];
?>

<script type="text/javascript">
    var json_str='<?php echo json_encode($teachers); ?>';
    var json_obj = JSON.parse(json_str);
    console.log(json_str)
    for(i in json_obj){
        var teacher = json_obj[i];
        console.log("name: " + teacher['name']);
        console.log("class: " + teacher['class']);
    }
</script>

Create Search Form with PHP

GOAL

Today’s goal is to create search form to find the name from the database.

Environment

Windows10
XAMPP 7.4.10

Method

This is an adjusted version of the code in “Access MySQL with PHP in XAMPP“. So please check the article first.

Search form

Use post method and the form is named “word” as below.

<form action="" method="POST">
    <label>Name:</label>
    <input type="text" name="word" /> <input type="submit" value="Search" />
</form>
(more…)

Create Original Theme in WordPress 3

At the last time, in “Create Original Theme in WordPress 2“, I designed pages of my original theme “techblog”. Today, I start implementing them.

GOAL

To study the name of PHP file for each page and create PHP files.

Environment

WordPress 5.5.1
XAMPP 7.4.10

The corresponding PHP files to items

I created these files.

The all files are in https://github.com/s-nako/wordpressTheme/tree/main/techblog.

This is one of the simplest WordPress themes. I’ll customize it in the future.

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

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?“.

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