Admin Page

Create pages in blog CMS using PHP and MYSQL | Part 10

Pages are also very important for blog CMS. Although the content has been given importance in the blog, the page also has great importance in any blog website. Here we are learning to create a complete blog CMS from the beginning » how to create a blog from scratch in PHP » tutorial. Pages are very important for SEO. Pages represent the blog website, what kind of content is written on this blog website. Pages help you even if you have to take approval for your blog website. In order to create a blog website in a professional manner, the page has to be created in the blog.

In the previous tutorials, we have created separate pages for tags and categories; similarly, we will use PHP and MYSQL to build pages. First, let’s understand the database table. To create pages in a blog, a table is created in the MYSQL database. Let’s have a table in which the page data will be inserted.
Table name — techno_pages

Читайте также:  Date convert to timestamp in java

Create pages in blog using PHP and MYSQL database

All the fields related to the page are taken in the table above. Make page ID auto increment. All these fields will be used to create pages and display page data. Page fields are created for SEO purpose, such as — Page Keywords and Meta Description.

Let’s learn to add a page to dynamic blog CMS.

admin/blog-pages.php

First of all, create the main page for blog pages. It will contain all the blog pages on the HTML table. Here we will create edit, delete and add a new page button.
We have learned this operation in the last few tutorials. In this tutorial, we will understand the main part.

 $stmt = $db->query('SELECT pageId,pageTitle FROM techno_pages ORDER BY pageId DESC'); 

As you can see in the query above, we are using here by fetching the title and id of the page. It becomes very simple. After this, we display the blog pages in descending order using the while loop.
Complete PHP code for blog pages — “

admin/blog-pages.php

is_logged_in()) < header('Location: login.php'); >if(isset($_GET[‘delpost’]))< $stmt = $db->prepare(‘DELETE FROM techno_pages WHERE pageId = :pageId’) ; $stmt->execute(array(‘:pageId’ => $_GET[‘delpost’])); header(‘Location: blog-pages.php?action=deleted’); exit; > ?>

Post ‘.$_GET[‘action’].’.

‘; > ?>

query(‘SELECT pageId,pageTitle,pageDescrip,pageContent,pageKeywords FROM techno_pages ORDER BY pageId DESC’); while($row = $stmt->fetch())< echo '

‘; echo ‘

‘; ?>

‘; > > catch(PDOException $e) < echo $e->getMessage(); > ?>

Article Title Update Delete
‘.$row[‘pageTitle’].’

Now, create another PHP file to create pages in blog CMS.

admin/add-blog-page.php

Creating a page becomes very easy if you have understood all the previous blog tutorials well. Building a page like creating blog posts, as a blog post, the page also has to write the title of the page, page tags, page description, and page content. If you have understood the operation of adding blog posts, then it will also become easy for you. Let’s understand the main part.

 $ pageSlug = slug ($ pageTitle);// insert into database$ stmt = $ db-> prepare ('INSERT INTO techno_pages (pageTitle, pageSlug, pageDescrip, pageContent, pageKeywords) VALUES (: pageTitle,: pageSlug,: pageDescrip,: pageContent,: pageKeywords)');

In the code lines given above, you can see that all the fields related to the page have been inserted in the MYSQL database by the query. The slug() function is used to convert page title to slug. The slug function was created in previous tutorial. To make SEO friendly URL for the page, we convert page tile to slug.
Complete PHP code for add blog page-“
admin/add-blog-page.php

is_logged_in()) < header('Location: login.php'); >?>

Add New Article

if($pageDescrip ==») < $error[] = 'Please enter the Page description.'; >if($pageContent ==») < $error[] = 'Please enter the content.'; >if($pageKeywords ==») < $error[] = 'Please enter the Page Keywords.'; >if(!isset($error))< try < $pageSlug = slug($pageTitle); //insert into database $stmt = $db->prepare(‘INSERT INTO techno_pages (pageTitle,pageSlug,pageDescrip,pageContent,pageKeywords) VALUES (:pageTitle, :pageSlug, :pageDescrip, :pageContent,:pageKeywords)’) ; $stmt->execute(array( ‘:pageTitle’ => $pageTitle, ‘:pageSlug’ => $pageSlug, ‘:pageDescrip’ => $pageDescrip, ‘:pageContent’ => $pageContent, ‘:pageKeywords’ => $pageKeywords )); //redirect to index page header(‘Location: blog-pages.php?action=added’); exit; >catch(PDOException $e) < echo $e->getMessage(); > > > //check for any errors if(isset($error))< foreach($error as $error)< echo '

‘.$error.’

‘; > > ?>


?>’>




?>’ style=»width:100%;height:40px»>

Now, add the update operation in blog CMS.

admin/edit-blog-page.php

The page can be edited using the update operation.
We have also understood the update operation in the previous tutorials.
We use the MYSQL update query to update the MYSQL database fields.
Complete PHP code for Update operation-

admin/edit-blog-page.php

is_logged_in()) < header('Location: login.php'); >?>

Edit Post

if($pageTitle ==») < $error[] = 'Please enter the Page title.'; >if($pageDescrip ==») < $error[] = 'Please enter the Page description.'; >if($pageContent ==») < $error[] = 'Please enter the content.'; >if($pageKeywords ==») < $error[] = 'Please enter the Article Keywords.'; >if(!isset($error))< try < $pageSlug = slug($pageTitle); //insert into database $stmt = $db->prepare(‘UPDATE techno_pages SET pageTitle = :pageTitle, pageSlug = :pageSlug, pageDescrip = :pageDescrip, pageContent = :pageContent, pageKeywords = :pageKeywords WHERE pageId = :pageId’) ; $stmt->execute(array( ‘:pageTitle’ => $pageTitle, ‘:pageSlug’ => $pageSlug, ‘:pageDescrip’ => $pageDescrip, ‘:pageContent’ => $pageContent, ‘:pageId’ => $pageId, ‘:pageKeywords’ => $pageKeywords )); //redirect to index page header(‘Location: blog-pages.php?action=updated’); exit; > catch(PDOException $e) < echo $e->getMessage(); > > > ?> ‘; > > try < $stmt = $db->prepare(‘SELECT pageId, pageSlug,pageTitle, pageDescrip, pageContent, pageKeywords FROM techno_pages WHERE pageId = :pageId’) ; $stmt->execute(array(‘:pageId’ => $_GET[‘pageId’])); $row = $stmt->fetch(); > catch(PDOException $e) < echo $e->getMessage(); > ?> ‘>


‘>


admin/header.php

Add another link in header. Edit header file and add the line after categories.

After creating pages , the pages have to display in the listwise. Let’s display the page in the menu. All the pages that are made will be displayed in the menu.
blog/header.php
Add the code lines below at the line number 10 (Hint- Add after the home list inside the ul tag )

blog/header.php

In the code above, we are using page title and page slug. Here, the base URL is also defined, which represents the path of the page.

After creating the page, the page content has to be displayed on another page. Like in the previous tutorials, the show.php file was created to display the post content, similarly, we will create another PHP file to display the page content separately.

Complete PHP code for page

We discussed this code in the first tutorial. Follow the same process and understand the code below.

prepare(‘SELECT pageId,pageTitle,pageSlug,pageContent,pageDescrip,pageKeywords FROM techno_pages WHERE pageSlug = :pageSlug’); $stmt->execute(array(‘:pageSlug’ => $_GET[‘pageId’])); $row = $stmt->fetch(); //if post does not exists redirect user. if($row[‘pageId’] == ») < header('Location: ./'); exit; >?> «> «>

‘.$row[‘pageTitle’].’

‘; ?>


‘.$row[‘pageContent’].’

‘; ?>

If you click and visit the page now, the page will not open because we have need to add one line .htaccess file.
Add the line after the catlinks .

blog/.htaccess

 RewriteRule ^page/(.*)$ page.php?pageId=$1 [L] 

In the code line above, the page is another PHP file for all pages from MYSQL database
The complete code of the .htaccess file will be like this.

RewriteEngine On RewriteBase /blog/ RewriteRule ^category/(.*)$ catlinks.php?id=$1 [L] RewriteRule ^page/(.*)$ page.php?pageId=$1 [L] RewriteRule ^tag/(.*)$ taglinks.php?id=$1 [L] RewriteCond % !-d [NC] RewriteCond % !-f [NC] RewriteRule ^(.*)$ show.php?id=$1 [QSA,L] 

In this way, you can create pages in the blog CMS using PHP and MYSQL database.

Источник

Создание страниц PHP – печатаем сайт налету!

От автора: вы когда-нибудь наблюдали за работой талантливых писателей? У меня есть один знакомый из «таких». Свои произведения он печатает на машинке: считает, что компьютер не способен принять всю «полноту его мыслей». А я ему в ответ говорю, что он так же, как и любая программа, всего лишь умело манипулирует строковыми значениями переменных. В общем, каждый остался при своем мнении. Сегодня мы рассмотрим создание страниц PHP, чтобы доказать, что этот язык программирования обладает огромным талантом.

Динамический талант

На проявление таланта любого автора (знаю по себе) могут влиять множество «сопутствующих» факторов: собственное настроение, погода и другие «ненастья». Но PHP «наплевать» на погоду за окном или ворчание жены за поломанный кран :). Он выполняет заложенный в него код. Причем делает это не просто так, а динамично: формируя (собирая) страницы налету.
Сегодня я постараюсь на несложны примерах продемонстрировать часто применяемые методы реализации динамичности на основе PHP:

Использование одного шаблона для создания нескольких веб-страниц.

Интеграция кода PHP в HTML.

Онлайн курс «PHP-разработчик»

Изучите курс и создайте полноценный проект — облачное хранилище файлов

С нуля освоите язык программирования PHP, структурируете имеющиеся знания, а эксперты помогут разобраться с трудными для понимания темами, попрактикуетесь на реальных задачах. Напишете первый проект для портфолио.

Начнем рассмотрение динамического создания страниц на PHP c последнего пункта. Поскольку для изучения первых двух требуется знание третьего. Стартуем!

Разметка основного примера

Сейчас за пару минут «набросаю» разметку самой простой страницы на HTML без особых «изысков».

Источник

Creating a new page and automatically associating it with a template in WordPress

enter image description here

I’ve got three page templates called «Simple», «Front», and «Form» and I would like to add a shortcut in the admin side bar to directly create a page that would be associated with any of these templates. So below «Add new» there would be:

  • Add new Simple Page
  • Add new Front Page
  • Add new Form Page

I’ve searched for it on Google but can’t find any information. Is it possible to do this in WordPress?

What @phpuser said + when you click on «Add new Front Page» you send $_GET param and make changes on post editor page so «Fron» template is automatically selected. But be careful and read few articles on changing admin panel before you do it, so all your work doesn’t go up in smoke on next wordpress update.

2 Answers 2

I found this question very interesting ,So here is what i have done to make this possible.

Fetch page template and add them as sub menu of Post type page.

function addTemplateAddNewSubMenu() < global $submenu; // here we are fetching all page template from current activated theme. $templates = wp_get_theme()->get_page_templates( 'page' ); foreach ( $templates as $filename => $title ) < if ( $filename != 'default' && $filename != '' ) < // add page-template filename as query string to add new page link. $url = 'post-new.php?post_type=page&template=' . $filename; $submenu['edit.php?post_type=page'][] = array( 'Add new ' . $title , 'manage_options', $url ); >> > add_action( 'admin_menu', 'addTemplateAddNewSubMenu' ); 

I have added page template as query string to

/wp-admin/post-new.php?post_type=page&template=template-contact.php 

Making page template dropdown selected by jQuery and template Query string.

add_action( 'admin_head','selectPageTemplate' ); function selectPageTemplate() < global $pagenow; if ( $pagenow == 'post-new.php' ) < if ( get_post_type() == 'page' && isset($_GET['template']) ) < $template = $_GET['template']; ?>  > > 

enter image description here

Here’s an example how to set the page template, for new pages, through the custom wpse_page_template GET parameter:

https://examle.tld/wp-admin/post-new.php?post_type=page&wpse_page_template=tpl-test.php 

We can hook into the save_post_page hook and target the auto-draft status:

add_action( 'save_post_page', function ( $post_ID, $post, $update ) < // Target 'auto-draft' status only if ( 'auto-draft' !== get_post_status( $post ) ) return $post_ID; // User input $input_tpl = filter_input( INPUT_GET, 'wpse_page_template', FILTER_SANITIZE_STRING ); $input_tpl = sanitize_file_name( $input_tpl ); // Get current page templates $page_templates = wp_get_theme()->get_page_templates( $post ); // Nothing to do if user tries a non a valid page template if ( ! isset( $page_templates[$input_tpl] ) ) return $post_ID; // Update the user defined page template update_post_meta( $post_ID, '_wp_page_template', $input_tpl ); return $post_ID; >, 10, 3 ); 

This approach could be extended for custom post types in WordPress 4.7+.

Источник

Оцените статью