WordPress Plugin Development Questions and Answers

1. How many types of hooks are in WordPress?

Ans- There are mainly two types of hooks in WordPress:

i. Action Hooks: Actions hooks let you do something at certain predefined points in the WordPress runtime.

ii. Filter Hooks: Filter hooks let you modify any data processed by WordPress and return it.

2. How to create a Shortcode in WordPress without a plugin?

Ans- add_shortcode() is used to add a new shortcode. It has the following syntax:

add_shortcode(string $tag, callable $callback);

The callback function is to run when the shortcode is found. Every shortcode callback is passed three parameters by default, including an array of attributes ($atts), the shortcode content or null if not set ($content), and finally the shortcode tag itself ($shortcode_tag), in that order.

3. How to create a custom widget in WordPress?

Ans – The register_widget() function is used to register a widget. To display this widget:

<?php 
function function_name_widgets_init()
{
register_sidebar(array(
'name' => __('Primary Sidebar', 'ace_service'),
'id' => 'main-sidebar',
'description' => 'Main sidebar on right side',
'before_widget' => '<li id ="%1$s" class="widget %2$s">',
'after_widget' => '<h2 class ="widgettitle">',
'after_title' => '</h2>',
));
register_sidebar(array(
'name' => __('Footer Widget 1', 'ace_service'),
'id' => 'footer-1',
'description' => 'Widgets in the area will be shown on all posts and pages.',
'before_widget' => '<li id ="%1$s" class="widget %2$s">',
'after_widget' => '<h2 class ="widgettitle">',
'after_title' => '</h2>',
));
register_sidebar(array(
'name' => __('Footer Widget 2', 'ace_service'),
'id' => 'footer-2',
'description' => 'Widgets in the area will be shown on all posts and pages.',
'before_widget' => '<li id ="%1$s" class="widget %2$s">',
'after_widget' => '<h2 class ="widgettitle">',
'after_title' => '</h2>',
));
register_sidebar(array(
'name' => __('Footer Widget 3', 'ace_service'),
'id' => 'footer-3',
'description' => 'Widgets in the area will be shown on all posts and pages.',
'before_widget' => '<li id ="%1$s" class="widget %2$s">',
'after_widget' => '<h2 class ="widgettitle">',
'after_title' => '</h2>',
));
}
add_action('widgets_init', 'function_name_widgets_init');
?>

4. How to create a custom post type in WordPress?

Step-1: Create custom post type: Add the following code into [php]functions.php[/php] file.

function function_name_cpt() {

	$labels = array(
		'name' => _x( 'teachers', 'Post Type General Name', 'text_domain' ),
		'singular_name' => _x( 'teacher', 'Post Type Singular Name', 'text_domain' ),
		'menu_name' => _x( 'teachers', 'Admin Menu text', 'text_domain' ),
		'name_admin_bar' => _x( 'teacher', 'Add New on Toolbar', 'text_domain' ),
		'archives' => __( 'teacher Archives', 'text_domain' ),
		'attributes' => __( 'teacher Attributes', 'text_domain' ),
		'parent_item_colon' => __( 'Parent teacher:', 'text_domain' ),
		'all_items' => __( 'All teachers', 'text_domain' ),
		'add_new_item' => __( 'Add New teacher', 'text_domain' ),
		'add_new' => __( 'Add New', 'text_domain' ),
		'new_item' => __( 'New teacher', 'text_domain' ),
		'edit_item' => __( 'Edit teacher', 'text_domain' ),
		'update_item' => __( 'Update teacher', 'text_domain' ),
		'view_item' => __( 'View teacher', 'text_domain' ),
		'view_items' => __( 'View teachers', 'text_domain' ),
		'search_items' => __( 'Search teacher', 'text_domain' ),
		'not_found' => __( 'Not found', 'text_domain' ),
		'not_found_in_trash' => __( 'Not found in Trash', 'text_domain' ),
		'featured_image' => __( 'Featured Image', 'text_domain' ),
		'set_featured_image' => __( 'Set featured image', 'text_domain' ),
		'remove_featured_image' => __( 'Remove featured image', 'text_domain' ),
		'use_featured_image' => __( 'Use as featured image', 'text_domain' ),
		'insert_into_item' => __( 'Insert into teacher', 'text_domain' ),
		'uploaded_to_this_item' => __( 'Uploaded to this teacher', 'text_domain' ),
		'items_list' => __( 'teachers list', 'text_domain' ),
		'items_list_navigation' => __( 'teachers list navigation', 'text_domain' ),
		'filter_items_list' => __( 'Filter teachers list', 'text_domain' ),
	);
	$args = array(
		'label' => __( 'teacher', 'text_domain' ),
		'description' => __( '', 'text_domain' ),
		'labels' => $labels,
		'menu_icon' => 'dashicons-admin-users',
		'supports' => array('title', 'editor', 'excerpt', 'thumbnail', 'author', 'custom-fields'),
		'taxonomies' => array(),
		'public' => true,
		'show_ui' => true,
		'show_in_menu' => true,
		'menu_position' => 5,
		'show_in_admin_bar' => true,
		'show_in_nav_menus' => true,
		'can_export' => true,
		'has_archive' => true,
		'hierarchical' => false,
		'exclude_from_search' => false,
		'show_in_rest' => true,
		'publicly_queryable' => true,
		'capability_type' => 'post',
	);
	register_post_type( 'teacher', $args );

}
add_action( 'init', 'function_name_cpt', 0 );

Step-2: Display the custom post type: Add the HTML code with WP_Query php code.

<?php 
$query = new WP_Query(array( 'post_type' => 'teacher', 'posts_per_page' => 3 ));
query_posts($query); while($query ->have_posts())
{ 
$query ->the_post(); ?>
<div class="col-lg-4 col-sm-6 mb-5 mb-lg-0">
<div class="card border-0 rounded-0 hover-shadow"><?php the_post_thumbnail('thumbnail', array('class' => 'card-img-top rounded-0')); ?>
<div class="card-body">
<h4 class="card-title"><?php the_title(); ?> </h4>
</div>
</div>
</div>
<?php } ?>

5. How to create custom WordPress blocks?

Step-1: Create a plugin to call up your custom block

/**
 * Plugin Name: Custom Plugin
 * Author: Webeduclick
 * Version: 2.0
 */
  
function MyCustomBlock() {
  wp_enqueue_script(
    'my-new-block',
    plugin_dir_url(__FILE__) . 'test-block.js',
    array('wp-blocks','wp-editor'),
    true
  );
}
   
add_action('enqueue_block_editor_assets', 'MyCustomBlock');

Step-2: Register your custom block

Create a test-block.js in the plugin.php directory.

/* This section of the code registers a new block, sets an icon and a category, and indicates what type of fields it'll include. */
  
wp.blocks.registerBlockType('brad/border-box', {
  title: 'Simple Box',
  icon: 'smiley',
  category: 'common',
  attributes: {
    content: {type: 'string'},
    color: {type: 'string'}
  },
  
/* This configures how the content and color fields will work, and sets up the necessary elements */
  
  edit: function(props) {
    function updateContent(event) {
      props.setAttributes({content: event.target.value})
    }
    function updateColor(value) {
      props.setAttributes({color: value.hex})
    }
    return React.createElement(
      "div",
      null,
      React.createElement(
        "h3",
        null,
        "Simple Box"
      ),
      React.createElement("input", { type: "text", value: props.attributes.content, onChange: updateContent }),
      React.createElement(wp.components.ColorPicker, { color: props.attributes.color, onChangeComplete: updateColor })
    );
  },
  save: function(props) {
    return wp.element.createElement(
      "h3",
      { style: { border: "3px solid " + props.attributes.color } },
      props.attributes.content
    );
  }
})

Step-3: Activate this plugin Next, open the Block Editor and add a new block.

6. How to create and display custom meta box values in WordPress?

Ans –

Step-1: Add the Meta Box

function add_my_meta_box(){

add_meta_box('my-meta-box', 'Year', 'my_meta_fields', 'property');

}

Step-2: Adding the Meta Box Field

function my_meta_fields()
{

	$year = get_post_meta( get_the_ID(), 'year_field', true );
?>

"/>

Step-3: Saving the Data of Custom Meta Fields

function save_meta_data(){
	global $post;
 if(isset($_POST["year_field"])):
         
        update_post_meta($post->ID, 'my-meta-data', $_POST["year_field"]);
     
    endif;
}
add_action('save_post', 'save_meta_data');

7. What is metadata in WordPress?

Ans – metadata is data or information. In the case of WordPress, it’s information associated with posts, users, comments and terms.

8. How to use nonce in WordPress?

Ans – Nonce is a string value, a temporary unique key that is generated by WordPress automatically. It acts as a special security token to check whether you are the same person who’s acting or someone else while submitting a form, adding a post, deleting a post, etc.

9. What is Data Validation in WordPress?

Data Validation is the process of testing data against a predefined pattern with a definitive result: valid or invalid. It is a more specific approach when compared to sanitization. To validate is to ensure that the data requested from a user matches what they have submitted.

Example:


This code example demonstrates a method for validating the [html]my-zipcode[/html] field:

$safe_zipcode = absint( $_POST['my-zipcode'] );
if ( strlen( $safe_zipcode ) !== 5 ) {
	$safe_zipcode = '';
}
update_post_meta( $post->ID, 'my_zipcode', $safe_zipcode );

The [php]absint()[/php] function converts a value to a non-negative integer, and defaults to zero if the input is a non-numeric value. It then checks to see if the value ends up as five characters. If it does, it will save an empty value to the database. Otherwise, it will save the properly validated zip code.

10. How to sanitize data in WordPress?

Sanitizing Data is the process of securing/cleaning/filtering input data. Validation is preferred over sanitization because validation is more specific.


We can’t use Validation here because the text field is too general: it can be anything at all. So we sanitize the input data with the sanitize_text_field() function:

$title = sanitize_text_field( $_POST['title'] );
update_post_meta( $post->ID, 'title', $title );

11. What are WordPress Salts? How to Change Your WordPress Salts Keys?

Salts are a type of secret key. It is located in two places: in the database and the wp-config. php file. These secret key in the database is randomly generated and will be appended to the secret keys in wp-config.php.

Method-1: Using a Plugin

Method-2: Changing Your Salt Keys Manually

12. What are the data escaping techniques in WordPress?

Escaping Data: It is very important for security when you building your WordPress plugins. It is the process of securing output data by stripping out unwanted data, like malformed HTML or script tags.

esc_html(): It escapes for HTML blocks and converts <, >, &, ", ' characters to HTML entities.

wp_kses(): KSES stands for KSES Strips Evil Scripts. It is a recursive acronym which is used to filter text content and strips out disallowed HTML.

esc_url(): It cleans the URL for use in text, changes the wrong and removes the dangerous characters.

esc_js(): Escape the text strings for echoing in JS. It is intended to be used for inline JS.

esc_attr(): This function is intended to convert a raw string into a valid one for output in HTML attributes.

esc_textarea(): Escaping for text-area values.

.

Leave a Reply

Your email address will not be published. Required fields are marked *