How to create blog CMS tags in PHP and MYSQL | Part 6


Create tags in PHP blog

We are learning the blog CMS in PHP from the first “ how to create a blog from beginning in PHP” tutorial in details with the better resources. In this tutorial, we are going to create the tags in the blog CMS. The tags are most essential for all blog CMS. CMS stands for the content management system . You should understand the importance of the tags in the dynamic blog website . We will display tags and link the related posts to the tags. If you will click on tags, the new page opens with related articles. We will use tags as SEO. SEO is an important part of every blog CMS. No-one can be rank own blog without SEO. We will use these tags as meta keywords . As you know, the meta keyword is read by the search engines (Google search engine, yahoo search engine or other search engines ). Meta keywords do not display on the page because these are created for SEO purposes only. You can say blog tags as blog keywords.

To create tags, the first one has to add a column to the table. Let's add a column to a table

.
Table Name - techno_blog

Create MYSQL table for Blog tags


In the table above, we have created a column for blog tags. In this blog tags column, we will insert all the tags and display. Here more than one tag can be created with a blog post. Using these tags, the tags will display relevant blog posts.
Let’s change the code and add tags functionality.


admin/add-blog-article.php


This page was being used to insert blog posts to the database. Till now the category of the blog post was also being linked, now we will insert the tags in the database table along with the blog post. We will separate blog tags by the commas. Some changes have to be made to its PHP file.


admin/add-blog-article.php

$stmt = $db->prepare('INSERT INTO techno_blog (articleTitle,articleSlug,articleDescrip,articleContent,articleDate) VALUES (:articleTitle, :articleSlug, :articleDescrip, :articleContent, :articleDate)') ;
  

$stmt->execute(array(
    ':articleTitle' => $articleTitle,
    ':articleSlug' => $articleSlug,//Blog article slug 
    ':articleDescrip' => $articleDescrip,
    ':articleContent' => $articleContent,
    ':articleDate' => date('Y-m-d H:i:s')
  
));
 

Change the code lines above to

 $stmt = $db->prepare('INSERT INTO techno_blog (articleTitle,articleSlug,articleDescrip,articleContent,articleDate,articleTags) VALUES (:articleTitle, :articleSlug, :articleDescrip, :articleContent, :articleDate, :articleTags)') ;
  



$stmt->execute(array(
    ':articleTitle' => $articleTitle,
    ':articleSlug' => $articleSlug,
    ':articleDescrip' => $articleDescrip,
    ':articleContent' => $articleContent,
    ':articleDate' => date('Y-m-d H:i:s'),
    ':articleTags' => $articleTags
));

In the code above, only tags are added to the MYSQL database. Here we are inserting the tags into the database table using MYSQL query.
As you know, we have added an input box for the title to insert the blog title from the admin side. Now, create another text box in the HTML form. You can use the text area. It’s your choice.
Now, add the code lines after the categories.


<input type='text' name='articleTags' value='<?php if(isset($error)){ echo $_POST['articleTags'];}?>' style="width:100%;height:40px">

admin/edit-blog-article.php


Admin can also be edited the tags after storing the blog article in the database. For that too, the blog displays the tags in a text box by fetching them. Blog tags are updated after the display in the text box. These are features of the PHP CRUD application.

$stmt = $db->prepare('UPDATE techno_blog SET articleTitle = :articleTitle, articleSlug = :articleSlug, articleDescrip = :articleDescrip, articleContent = :articleContent WHERE articleId = :articleId') ;
$stmt->execute(array(
    ':articleTitle' => $articleTitle,
    ':articleSlug' => $articleSlug,
    ':articleDescrip' => $articleDescrip,
    ':articleContent' => $articleContent,
    ':articleId' => $articleId
));

 

Change the code lines above to

 $stmt = $db->prepare('UPDATE techno_blog SET articleTitle = :articleTitle, articleSlug = :articleSlug, articleDescrip = :articleDescrip, articleContent = :articleContent,articleTags = :articleTags WHERE articleId = :articleId') ;
$stmt->execute(array(
    ':articleTitle' => $articleTitle,
    ':articleSlug' => $articleSlug,
    ':articleDescrip' => $articleDescrip,
    ':articleContent' => $articleContent,
    ':articleTags' => $articleTags,
    ':articleId' => $articleId
));

We have added tags column in the query. You can add manually or use code lines above. The update query will update the tags also.
Now, we fetch the blog tags using MYSQL SELECT query.

 $stmt = $db->prepare('SELECT articleId, articleSlug,articleTitle, articleDescrip, articleContent FROM techno_blog WHERE articleId = :articleId') ;

Change the code lines above to –

$stmt = $db->prepare('SELECT articleId, articleSlug,articleTitle, articleDescrip, articleContent,articleTags FROM techno_blog WHERE articleId = :articleId') ; 

The code above, will be fetched the data from the MYSQL table. Here, we are fetching blog tags also
Now add the text box for blog tags after the categories in the HTML form .

 


<input type='text' name='articleTags' style="width:100%;height:40px;"value='<?php echo $row['articleTags'];?>'>

Administrators can add tags from their panels.
Let's display these tags publicly, as well as link the blog post to the tags.


blog/index.php


As you can see, the blog posts list is displayed on the index page. Along with the blog posts, the blog categories are also displayed. Now here we will display the blog tags.

$stmt = $db->query('SELECT articleId, articleTitle, articleSlug, articleDescrip, articleDate FROM techno_blog ORDER BY articleId DESC'); 


Change the code lines above to

$stmt = $db->query('SELECT articleId, articleTitle, articleSlug, articleDescrip, articleDate, articleTags FROM techno_blog ORDER BY articleId DESC');  

We have added tags column in this query.
Add the code after the categories (Hint – Where you want to display the tags after category p tag closed )

 echo '

Tagged as: '; $links = array(); $parts = explode(',', $row['articleTags']); foreach ($parts as $tags) { $links[] = "<a href='tag/".$tags."'>".$tags."</a>"; } echo implode(", ", $links); echo '

'; echo '
';

In the PHP code above, we have displayed the blog tags. The path of the tag/ keyword is given before the tag name.
We use explode function split the string to array and implode function split the array to the string.
Now create a PHP file for tags. Blog posts will be displayed on that tags page.
Let’s create another page –


blog/taglinks.php


We created a page for the category that when a visitor clicks on the category title, then the blog posts related to that title appear on a new page, similarly if a visitor clicks on the tag name, the blog posts related to that blog tag appear on a new page. So we create a new page so that blog posts related to blog tags can be displayed as listwise.
Let’s understand the chunk part of code –

  $stmt = $db->prepare('SELECT articleId, articleTitle, articleSlug, articleDescrip, articleDate, articleTags FROM techno_blog WHERE articleTags like :articleTags ORDER BY articleId DESC');
                $stmt->execute(array(':articleTags' => '%'.$_GET['id'].'%'));
 

In the code above , we are getting tag name by the id . We use GET method to hold the URL encoded values .


Complete PHP code for blog tags

blog/taglinks.php


<?php require('includes/config.php'); ?>

<?php include("head.php");  ?>

    <?php echo htmlspecialchars($_GET['id']);?>-Techno Smarter
    <?php include("header.php");  ?>

Articles in tag:- <?php echo htmlspecialchars($_GET['id']);?>


<?php try { $stmt = $db->prepare('SELECT articleId, articleTitle, articleSlug, articleDescrip, articleDate, articleTags FROM techno_blog WHERE articleTags like :articleTags ORDER BY articleId DESC'); $stmt->execute(array(':articleTags' => '%'.$_GET['id'].'%')); while($row = $stmt->fetch()){ echo '
'; echo '

<a href="../'.$row['articleSlug'].'">'.$row['articleTitle'].'</a>

'; echo '

Posted on '.date('jS M Y H:i:s', strtotime($row['articleDate'])).' in '; $stmt2 = $db->prepare('SELECT categoryName, categorySlug FROM techno_category, techno_cat_links WHERE techno_category.categoryId = techno_cat_links.categoryId AND techno_cat_links.articleId = :articleId'); $stmt2->execute(array(':articleId' => $row['articleId'])); $catRow = $stmt2->fetchAll(PDO::FETCH_ASSOC); $links = array(); foreach ($catRow as $cat) { $links[] = "<a href='../category/".$cat['categorySlug']."'>".$cat['categoryName']."</a>"; } echo implode(", ", $links); echo '

'; echo '

Tagged as: '; $links = array(); $parts = explode(',', $row['articleTags']); foreach ($parts as $tags) { $links[] = "<a href='".$tags."'>".$tags."</a>"; } echo implode(", ", $links); echo '

'; echo '

'.$row['articleDescrip'].'

'; echo '

'; echo '
'; } } catch(PDOException $e) { echo $e->getMessage(); } ?>
<?php include("sidebar.php"); ?> <?php include("footer.php"); ?>

Blog tags should be redirect to the tags link file . Now , add a line in .htaccess file .


blog/.htaccess

Add the code line after the category code line( Hint- At line number 4) -


 RewriteRule ^tag/(.*)$ taglinks.php?id=$1 [L]

Now, all blog posts related to the tag will be displayed on a new page.
If you want to display the tags on the blog post content page too, then you will have to add code in this way.
Edit your show file –


blog/show.php

$stmt = $db->prepare('SELECT articleId,articleDescrip, articleSlug ,articleTitle, articleContent, articleDate FROM techno_blog WHERE articleSlug = :articleSlug'); 

Change the code lines above to

$stmt = $db->prepare('SELECT articleId,articleDescrip, articleSlug ,articleTitle, articleContent, articleTags, articleDate  FROM techno_blog WHERE articleSlug = :articleSlug'); 

Add the code lines where you want to display the blog tags. Add the code lines after the categories where the paragraph tag is closed by echo() function.(at line 45)

 echo '

Tagged as: '; $links = array(); $parts = explode(',', $row['articleTags']); foreach ($parts as $tags) { $links[] = "<a href='".$tags."'>".$tags."</a>"; } echo implode(", ", $links); echo '

';

Now post title, the post categories along with post tags also be displayed.

We were discussing SEO. SEO is more important for Blog CMS. We can use these blog tags as meta keywords. Open show.php file and change a code line –

blog/show.php

 
Change to –
 
All associated tags will serve as keywords.

Now, display the tags in the blog sidebar.
Edit your blog sidebar and change the code below .
blog/sidebar.php

<a href="#">Blog Tag 1</a>
         <a href="#">Blog Tag 2</a>
            <a href="#">Blog Tag 3</a>
                <a href="#">Blog Tags List (Later Tutorial)</a>
 


Change the code lines above to

<?php
    $tagsArray = [];
    $stmt = $db->query('select distinct LOWER(articleTags) as articleTags from techno_blog where articleTags != "" group by articleTags');
    while($row = $stmt->fetch()){
        $parts = explode(',', $row['articleTags']);
        foreach ($parts as $tag) {
            $tagsArray[] = $tag;
        }
    }

    $finalTags = array_unique($tagsArray);
    foreach ($finalTags as $tag) {
        echo "<a href='http://localhost/blog/tag/".$tag."'>".ucwords($tag)."</a>";
    }
    
    ?>
 

This is how tags are created in the blog.


Please Share

Recommended Posts:-

Previous Posts:-

Featured Item


Complete Blog CMS system in PHP with MYSQL database | PHP scripts

$13



Modern blog CMS in PHP with MYSQL database | PHP blog scripts

$67




2 Comments
moskano 11 Jul 2022

How to put ( - ) between spaces in tag links?

echo '<p>Tagged as: '; $links = array();

$parts = explode(',', $row['articleTags']);

foreach ($parts as $tags) {

$links[] = "<a href='".$tags."'>".$tags."</a>";

}
echo implode(", ", $links); echo '</p>';

 

@moskano replied by Techno Smarter 13 Jul 2022

You are asking for SEO-friendly tags for multiple words. Like - Tag - web development. 

The tag should be saved as web-development in the database. After that, you can fetch tags the same as above. Kindly use the slug() function to convert a simple to SEO-friendly tag. Like - PHP programming. The tag will be php-programming. Use slug function during insertion of the article. Follow these steps. 

1. Write tags separated by commas like - HTML,CSS,PHP programming,web development .

2. Explode these tags and save them in array. 

3. Use slug() function .

4. Implode again in tags variable .  

$res=explode(',', $tags);   
$tagarr=array();
foreach($res as $re)
{ 
 $tagarr[]=slug($re) ;
}
$tags=implode(',', $tagarr);

Now, you are able to create SEO-friendly tags. The slug() function will put the - sign between spaces. 

You can find slug() function from here - 

How to create SEO friendly URL for Blog posts in PHP

I want to make seo friendly url in PHP ?