Home Blog Page 24

WordPress REST API With Python

0

In this post, we will use the power of the REST API with Python and will perform a crud operation. What we will do in this blog is we will fetch all posts, create one new post, update it and delete it using REST API with Python. WordPress REST API With Python?

WordPress REST API With Python using Authentication

First of all, we need basic authentication for performing crud operation and it won’t work until you install a special plugin named application password to get the application password.

Go to your dashboard -> plugin -> Add new and type application password in the search box.

Once you installed the plugin go to your profile settings and scroll to the bottom. You will see one application password field will be added there. Type your application name and hit enter and a popup will appear with a password. Copy generated password from the popup.

It’s time to go through the Python

Now, Create one file with the .py extension. You can give it any name (for example app.py).

Import some required packages:


import requests
import json
import base64

Fetch Posts

url = "https://wholeblogs.com/wp-json/wp/v2/posts"

user = "your-username"
password = "your-application-password"

credentials = user + ':' + password

token = base64.b64encode(credentials.encode())

header = {'Authorization': 'Basic ' + token.decode('utf-8')}

responce = requests.get(url , headers=header)

print(responce)

Let’s understand this code.

  • URL is the URL of the site from which you want to fetch posts.
  • User is your admin username.
  • The password is the application password that you have generated just before.
  • Encode your credentials and pass them in header authorization as shown in code.
  • At the bottom of the line, we are printing our response to see what we are getting.

Now, open your terminal and run your app.py file.


python app.py

Create Post

To create a post we need to make the post request with some required parameters like URL, your JSON data. Let’s do that:

url = "https://wholeblogs.com/wp-json/wp/v2/posts"

user = "your-username"
password = "your-application-password"

credentials = user + ':' + password

token = base64.b64encode(credentials.encode())

header = {'Authorization': 'Basic ' + token.decode('utf-8')}

post = {
	'title'   	: 'Hello World',
	'status'  	: 'publish', 
	'content' 	: 'This is my first post created using rest API',
	'categories': 5, // category ID
	'date' 		: '2020-01-05T10:00:00'
}

responce = requests.post(url , headers=header, json=post)

print(responce)

Update Post

To update posts you need to pass post id to tell REST API which post you want to update.

Let’s see how to do that.

url = "https://wholeblogs.com/wp-json/wp/v2/posts/"

postID = 1

user = "your-username"
password = "your-application-password"

credentials = user + ':' + password

token = base64.b64encode(credentials.encode())

header = {'Authorization': 'Basic ' + token.decode('utf-8')}

post = {
	'title'   	: 'Hello World Updated',
	'content' 	: 'This is my first post created using rest API Updated'
}

responce = requests.post(url + postID , headers=header, json=post)

print(responce)

Here, post ID is the id of the post you want to update.

Delete Post

To delete a post we need to use delete requests provided by Python.


url = "https://wholeblogs.com/wp-json/wp/v2/posts/"

user = "your-username"
password = "your-application-password"

credentials = user + ':' + password

token = base64.b64encode(credentials.encode())

header = {'Authorization': 'Basic ' + token.decode('utf-8')}

responce = requests.delete(url + postID , headers=header)

print(responce)

This was a small introduction to WordPress REST API with Python. Here, we have top reasons why you should learn WordPress

You can check the code at my GitHub repository. Here

How to Create Common Categories & Tags for Multiple Custom Post Types in WordPress?

0

In WordPress, to use default categories & tags for custom post types you’ve created you need to define it in the taxonomies parameter when you are creating custom post type.Create Common Categories & Tags for Multiple Custom Post Types in WordPress?

You can check the following example.


function custom_post_type() {

// Set UI labels for Custom Post Type
$labels = array(
'name' => _x( 'Movies', 'Post Type General Name', 'twentytwenty' ),
'singular_name' => _x( 'Movie', 'Post Type Singular Name', 'twentytwenty' ),
'menu_name' => __( 'Movies', 'twentytwenty' ),
'parent_item_colon' => __( 'Parent Movie', 'twentytwenty' ),
'all_items' => __( 'All Movies', 'twentytwenty' ),
'view_item' => __( 'View Movie', 'twentytwenty' ),
'add_new_item' => __( 'Add New Movie', 'twentytwenty' ),
'add_new' => __( 'Add New', 'twentytwenty' ),
'edit_item' => __( 'Edit Movie', 'twentytwenty' ),
'update_item' => __( 'Update Movie', 'twentytwenty' ),
'search_items' => __( 'Search Movie', 'twentytwenty' ),
'not_found' => __( 'Not Found', 'twentytwenty' ),
'not_found_in_trash' => __( 'Not found in Trash', 'twentytwenty' ),
);

// Set other options for Custom Post Type

$args = array(
'label' => __( 'movies', 'twentytwenty' ),
'description' => __( 'Movie news and reviews', 'twentytwenty' ),
'labels' => $labels,
// Features this CPT supports in Post Editor
'supports' => array( 'title', 'editor', 'excerpt', 'author', 'thumbnail', 'comments', 'revisions', 'custom-fields', ),
// You can associate this CPT with a taxonomy or custom taxonomy.
'taxonomies' => array( 'category', 'post_tag'),
'hierarchical' => false,
'public' => true,
'show_ui' => true,
'show_in_menu' => true,
'show_in_nav_menus' => true,
'show_in_admin_bar' => true,
'menu_position' => 5,
'can_export' => true,
'has_archive' => true,
'exclude_from_search' => false,
'publicly_queryable' => true,
'capability_type' => 'post',
'show_in_rest' => true,

);
add_action( 'init', 'custom_post_type', 0 );

I am creating a custom post type named movie and want to use the default category and tag for it. So that I have added category and post_tag in the taxonomies parameter. Create Common Categories & Tags for Multiple Custom Post Types in WordPress?

Can I able to change the WordPress theme layout with CSS?

Yes, you can change the WordPress theme layout CSS. Let’s see how!! There are two ways to do that

  1. You need to create a child theme first, After creating it you can write your own CSS inside your child theme’s style.css file to override the parent theme’s CSS.
  2. If you don’t want to create a child theme then it’s ok. You can also write CSS inside an additional CSS option in customization.

WordPress VS Joomla – Which CMS Is Better

0

WordPress VS Joomla which cms is best? this question raises in many people when they are a beginner. but wait!! let’s talk about cms before we start to compare WordPress and Joomla.

A content management system(CMS) is software that facilitates creating, editing, organizing, and publishing content. WordPress VS Joomla – Which CMS Is Better?

WordPress VS Joomla – Which CMS Is Better

WordPress may be a Content Management System, that permits you to make and publish your content online. Although it’s mostly used for web publishing, it is often wont to manage content on an intranet, or during a single computer.

What is CMS?

CMS (Content Management System) is a set of related programs that are mainly wont to create and manage digital content. When it involves a CMS, two names WordPress and Joomla that strike the developer’s mind.

Selecting among the both may be a bit complex and for this, you would like to deeply analyze the necessity of your business then stick with any decision. So, if you’re confused between them both, this blog will help you tons.

Here you’ll get the solution WordPress vs Joomla – who is the best.

WordPress

It is a platform for private publishing with attention to web standards and usefulness. WordPress is a free and priceless CMS. If you’re trying to find an internet site that’s easy to use, flexible, and scalable then WordPress is best.

Initially, WordPress was started for the blogging system, on the other hand, it came as an entire content management system.

As a CMS it provides thousands of plugins, widgets, and themes to make a beautiful website. For the straightforward blog or brochure-type or simply information-related site, WordPress is the most suitable option. You can get more information regarding WordPress here.

Joomla

Joomla is a platform between WordPress and Drupal. Because it offers a better site than box type website from WordPress and also it’s not flexible as Drupal.

It’s used everywhere on the planet for creating an easy website for complex applications. Joomla is straightforward to put in and also easy to manage. It can deliver a more reliable website than WordPress.

Search Engine Optimization (SEO)

it’s vital for the ranking of your website and a CMS can either increase it or decrease it drastically. So, you ought to choose the one that provides you more SEO benefits. WordPress has inbuilt SEO features than Joomla.

Customization

does one want to customize your website? If yes, WordPress is the best CMS to use. This is often because it’s easier to feature plugins, extensions, templates, or other functionality to the present CMS than the Joomla.

Security

Another important thing you would like to offer attention to while developing your website is its security, which you can’t deem granted anyways. When it involves the security and security of your overall website, so, Joomla takes the cake with its safer feature.

Flexibility

Website Development is the most vital part, so you’ve got to be very careful while picking the CMS at this stage. Both the CMS is a touch bit complex and permits users to manage the website but WordPress makes this work easier, especially for a non-technical person than the Joomla.

Surely, you ought to choose this feature if you’re a non-technical person and do not want to probe the pool of coding.

Final Words

I hope you are clear now about the comparison of WordPress vs Joomla. little question, Joomla is ideal in its own way because.

It offers fantastic functionality to reinforce your website but when it involves flexibility, performance, SEO, customization, and content management potential, WordPress wins the race.

So, you ought to choose this feature because it makes your developing experience way better than ever. If you continue to have any doubt-free Reprint Articles, consulting a reputed website Development is a perfect choice this is often because they’re experts and know which platform suits your business needs.

Create a Single Page Application With React js and WordPress REST API

0

In this blog, I will explain to you how to create a single-page application for to-do lists using React js and WordPress REST API. Create a Single Page Application With React js and WordPress REST API

Create custom post type for todo lists in WordPress

Note: I am using the default twenty nineteen themes provided by WordPress but you can also use your custom theme.

We will not use default posts of WordPress for our to-do lists.

So let’s create a custom post type named todo list. Open your functions.php file and add the following code inside it:

add_action( 'init', 'todo_list' );
/**
* Register a Todo-Lists post type.
*/
function todo_list() {
$labels = array(
'name' => _x( 'Todo-Lists', 'post type general name', 'customtheme' ),
'singular_name' => _x( 'Todo-list', 'post type singular name', 'customtheme' ),
'menu_name' => _x( 'Todo-Lists', 'admin menu', 'customtheme' ),
'name_admin_bar' => _x( 'Todo-list', 'add new on admin bar', 'customtheme' ),
'add_new' => _x( 'Add New', 'Todo-list', 'customtheme' ),
'add_new_item' => __( 'Add New Todo-Lists', 'customtheme' ),
'new_item' => __( 'New Todo-list', 'customtheme' ),
'edit_item' => __( 'Edit Todo-list', 'customtheme' ),
'view_item' => __( 'View Todo-list', 'customtheme' ),
'all_items' => __( 'All Todo-Lists', 'customtheme' ),
'search_items' => __( 'Search Todo-Lists', 'customtheme' ),
'parent_item_colon' => __( 'Parent Todo-Lists:', 'customtheme' ),
'not_found' => __( 'No Todo-Lists found.', 'customtheme' ),
'not_found_in_trash' => __( 'No Todo-Lists found in Trash.', 'customtheme' )
); $args = array(
'labels' => $labels,
'description' => __( 'Description.', 'customtheme' ),
'public' => true,
'publicly_queryable' => false,
'show_ui' => true,
'show_in_menu' => true,
'query_var' => true,
'rewrite' => array( 'slug' => 'todo-list', 'with_front' => false ),
'capability_type' => 'post',
'has_archive' => false,
'hierarchical' => false,
'menu_position' => null,
'supports' => array( 'title', 'editor', 'author', 'thumbnail')
);
register_post_type( 'todo-list', $args );
}

Create front end form

Now we will create a front-end form from where user can enter their details like task name, task description etc.

Let’s create a new template file for that.

In this template file, we will add code for custom form to display it in WordPress front end for data insertion.

<?php
/**
* The template name: Front-End Post
*
*/
get_header(); ?><?php
$page_id = get_queried_object()->ID;
$page_url = get_permalink(get_queried_object()->ID);
?><div id="primary" class="content-area" style=" width: 800px;margin: -73px 215px 0px;" ><h2>Todo List</h2>
<form method="post" action="<?php echo $page_url; ?>">
<div class="form-group">
<label for="title">Task Title:</label>
<br>
<input type="text" class="form-control" id="title" name="title" style="width: 100%;">
</div>

<div class="form-group">
<label for="pwd">Task Description :</label>
<textarea class="form-control" name="description"></textarea>
</div>
<br>
<button type="submit" class="btn btn-default">Submit</button>
</form></div><?php
get_footer();

Now, create a new page from the WordPress admin panel and apply your template to it. Open that page in the browser it will look like this:

Create a custom endpoint for REST API

Next, we need to create a custom endpoint for our custom post type to access our post types data. So, open the functions.php file and add the below code in it.

function sections_endpoint( $request_data ) {
$args = array(
'post_type' => 'todo-list',
'posts_per_page'=>-1,
'numberposts'=>-1
);
$posts = get_posts($args);
foreach ($posts as $key => $post) {
$posts[$key]->post_title;
$posts[$key]->post_content;
}
return $posts;
}
add_action( 'rest_api_init', function () {
register_rest_route( 'sections/v1', '/todo-list/', array(
'methods' => 'GET',
'callback' => 'sections_endpoint'
));
});

Create React Application

We will first install the create-react-app globally. Then we create a project using create-react-app command.

npm install -g create-react-app
create-react-app yourprojectname
cd yourprojectname
npm run start

After running the above command, a new folder will be created in your system with your selected name. You also need to install another important package named Axios. To install it, run the command npm install axios. You can get more information here.

It’s time to unlock the power of React

After installing react app, open the app.js file in your favorite code editor. You can also create your own js file and import it into your index.js file. Open your js file and add code for accessing the todo lists that you have created using WordPress.

import React, { Fragment } from "react";
import axios from "axios";
import "./App.css";
import {
BrowserRouter as Router,
} from "react-router-dom";export default class App extends React.Component {
constructor(props) {
super(props);this.state = {
posts: []
};
}getAllPosts = async () => {
let responce = await axios.get(
'<a href="https://localhost/gutenberg-demo/wp-json/sections/v1/todo-list">https://localhost/gutenberg-demo/wp-json/sections/v1/todo-list</a>
);
let { data } = await responce;
this.setState({ posts: data });
};componentDidMount = async () => {
await this.getAllPosts();
};render() {
const { posts } = this.state;return (
<Router>
<Fragment>
{/* Links */}
<div className="container">
<div className="wrap-list">
{posts.map((page, index) => {
return (
<>
<div className="wrap-input">
<input type="checkbox" name={page.post_title} value={page.post_title} />
<h2 className={"post-title"}>{page.post_title}</h2>
<div className={"post-content"}>{page.post_content}</div>
</div>
</>
);
})}
</div>
</div>
</Fragment>
</Router>
);
}
}

Now, open

 https://localhost:3000 

in any browser to view your to-do list. I have added some bits of CSS. It will look like this:

Read more: wordpress rest api with python

You can check the code for more information on my Github.

How to Create Custom Gutenberg Block

0

Gutenberg block is the future of WordPress. This blog helps you in the development of a custom Gutenberg block from scratch. I am using ES6 and JSX in my code so you need to install npm.

How to create a custom Gutenberg block If you are using ES5 then you don’t need to install npm. How to create a custom Gutenberg block?

Create Custom Gutenberg Block

I am preferring the ES6 concept because it is simple compared to ES5 and it gives you the freedom to write both javascript and HTML code at the same time using the concept of JSX.

If you want to create a Gutenberg block using ES6 then simply follow the below steps for creating your first beautiful Gutenberg block.

If you are using any default theme of WordPress like twenty nineteen then there will be one file named package.json but if you are using any custom theme then you need to generate package.json first. create custom Gutenberg block

package.json is a file that is mainly used to store the metadata associated with your project. It is also used to store the list of dependency packages.

If you want to add any package to your project then you need to create a package.json file.

Create package.json file

To create a package.json file, first of all, move to your theme’s root directory and run the following command.

npm init

After running the above command it will prompt some questions. Answer all the questions and that’s it.

You have successfully generated your packge.json file. You can see it inside your theme’s root directory.

Install NPM

Move to your theme’s root directory and run the following command.

npm install

After running this command you can see one folder named node_modules added inside your theme’s root directory which contains all the required packages and modules.

Create build and src folder

After installation is completed, create one folder named src inside your theme’s root directory and add your js file inside it. Note: It is required to name your js file as index.js as react starts rendering all the components from the index.js file.

Add one another folder named build inside your theme’s root directory.

Note: Don’t add any files now inside the build folder as it will automatically add a minified version of your index.js file when running the npm build command.

Edit your package.json file

Now, open your package.json file and add the following line inside the script array.

"build:scripts": "wp-scripts build"

This will simply start building your script when you fire npm run build: scripts command and add a minified version of your index.js file inside the build folder which you created previously.

Create Required Files

Now, our real work starts. Create the following files.

  • index.php
  • index.js

index.php You can create this file anywhere you want and include it in your theme’s functions.php file.

In the index.php file, you need to create one function in which you need to register your script first using

wp_register_script

The function and add another function named.

register_block_type

Which contains your namespace as a first parameter and an array of scripts as a second parameter.

index.js In the js file, you can write code for all the custom blocks you want to add inside the default function named registerBlockType. you also need to import some packages from WordPress before you start writing any codes.

Run NPM

After you have written your code for your first custom Gutenberg block then you need to run a command for running your script using the following command.

npm start-build 

After running this command your scripts will start building and you can see a message like wp-scripts start as shown in the screenshot below.

Read more: Why SEO is important for online success

Now, open your posts section click on add block in the left top, and search for your custom block. add some content inside it and save it. after saving your post view post you can see your first custom block there.