Explor Wordpress

Month: July 2022 Page 1 of 11

WordPress get_post_type()

Syntax

get_post_type( int|WP_Post|null $post = null )

Usage

It returns a string of the post type of the post ID or the current post, from this value you can check on the post type to decide what you do with it, just like the code.
Add the below code to the wp-includes/post.php

function get_post_type( $post = null ) {
  $post = get_post( $post );
    if ( $post ) {
        return $post->post_type;
  }
    return false;
}

WordPress is_singular()

Syntax

is_singular>( string|array $post_types = ‘ ‘)

Usage

It determines whether the query is for an existing post under any page type (Blog post, attachment, page, custom post types). It enables you to target single-view pages, regular page pages, and the attachment page all in one swoop.
Add this below code to wp-includes/query.php

function is_singular( $post_types = '' ) {
    global $wp_query;
    if ( ! isset( $wp_query ) ) {
        _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1.0' );
        return false;
    }
    return $wp_query->is_singular( $post_types );
}

WordPress get_template_part()

Syntax

get_template_part( string $slug, string $name = null )

Usage

It includes a template part of the theme. Providing a simple mechanism for child themes to overload reusable sections of code in the theme.
Add the below code in wp-includes/general-template.php.

function get_template_part( $slug, $name = null ) {
        do_action( "get_template_part_{$slug}", $slug, $name );
        $templates = array();
        $name      = (string) $name;
        if ( '' !== $name ) {
            $templates[] = "{$slug}-{$name}.php";
        }
        $templates[] = "{$slug}.php";
        do_action( 'get_template_part', $slug, $name, $templates );
        locate_template( $templates, true, false );
}

WordPress absint()

Syntax

absint( mixed $maybeint)

Usage

It used to convert a value into a non-negative integer.
Add this below code in wp-includes/functions.php

function absint( $maybeint ) {
    return abs( intval( $maybeint ) );
}

WordPress esc_url()

Syntax

esc_url( string $url, array $protocols = null, string $_context = ‘display’ )

Usage

It is used to clean and escape for output as a URL and to convert and fixe the HTML entities.  Sanitizes a string and removes disallowed URL protocols. Retrieve a list of protocols to allow in HTML attributes.
Add this below code in wp-includes/plugin.php


function esc_url( $url, $protocols = null, $_context = 'display' ) {
    $original_url = $url;
    if ( '' == $url ) {
        return $url;
    }
    $url = str_replace( ' ', '%20', ltrim( $url ) );
    $url = preg_replace( '|[^a-z0-9-~+_.?#=!&;,/:%@$\|*\'()\[\]\\x80-\\xff]|i', '', $url );
    if ( '' === $url ) {
        return $url;
    }
    if ( 0 !== stripos( $url, 'mailto:' ) ) {
        $strip = array( '%0d', '%0a', '%0D', '%0A' );
        $url = _deep_replace( $strip, $url );
    }
    $url = str_replace( ';//', '://', $url );
   
    if ( strpos( $url, ':' ) === false && ! in_array( $url[0], array( '/', '#', '?' ) ) &&
        ! preg_match( '/^[a-z0-9-]+?\.php/i', $url ) ) {
        $url = 'http://' . $url;
    }
    // Replace ampersands and single quotes only when displaying.
    if ( 'display' == $_context ) {
        $url = wp_kses_normalize_entities( $url );
        $url = str_replace( '&', '&', $url );
        $url = str_replace( "'", ''', $url );
    }
    if ( ( false !== strpos( $url, '[' ) ) || ( false !== strpos( $url, ']' ) ) ) {
        $parsed = wp_parse_url( $url );
        $front = '';
        if ( isset( $parsed['scheme'] ) ) {
            $front .= $parsed['scheme'] . '://';
        } elseif ( '/' === $url[0] ) {
            $front .= '//';
        }
        if ( isset( $parsed['user'] ) ) {
            $front .= $parsed['user'];
        }
        if ( isset( $parsed['pass'] ) ) {
            $front .= ':' . $parsed['pass'];
        }
        if ( isset( $parsed['user'] ) || isset( $parsed['pass'] ) ) {
            $front .= '@';
        }
        if ( isset( $parsed['host'] ) ) {
            $front .= $parsed['host'];
        }
        if ( isset( $parsed['port'] ) ) {
            $front .= ':' . $parsed['port'];
        }
        $end_dirty = str_replace( $front, '', $url );
        $end_clean = str_replace( array( '[', ']' ), array( '%5B', '%5D' ), $end_dirty );
        $url   = str_replace( $end_dirty, $end_clean, $url );
    }
    if ( '/' === $url[0] ) {
        $good_protocol_url = $url;
    } else {
        if ( ! is_array( $protocols ) ) {
            $protocols = wp_allowed_protocols();
        }
        $good_protocol_url = wp_kses_bad_protocol( $url, $protocols );
        if ( strtolower( $good_protocol_url ) != strtolower( $url ) ) {
            return '';
        }
    }
    return apply_filters( 'clean_url', $good_protocol_url, $original_url, $_context );
}

WordPress get_option()

Syntax

get_option( string $option, mixed $default = false )

Usage

It is used to check whether you need to install an option. get_option() is commonly used during the installation of plugin options and to test whether upgrading is required or not.
Add this below code in wp-includes/plugin.php

function get_option( $option, $default = false ) {
    global $wpdb;
    $option = trim( $option );
    if ( empty( $option ) ) {
        return false;
    }
    $pre = apply_filters( "pre_option_{$option}", false, $option, $default );
    if ( false !== $pre ) {
        return $pre;
    }
    if ( defined( 'WP_SETUP_CONFIG' ) ) {
        return false;
    }
    $passed_default = func_num_args() > 1;
    if ( ! wp_installing() ) {
        // prevent non-existent options from triggering multiple queries
        $notoptions = wp_cache_get( 'notoptions', 'options' );
        if ( isset( $notoptions[ $option ] ) ) {
            return apply_filters( "default_option_{$option}", $default, $option, $passed_default );
        }
    $alloptions = wp_load_alloptions();
        if ( isset( $alloptions[ $option ] ) ) {
            $value = $alloptions[ $option ];
        } else {
            $value = wp_cache_get( $option, 'options' );
            if ( false === $value ) {
                $row = $wpdb->get_row( $wpdb->prepare( "SELECT option_value FROM $wpdb->options WHERE option_name = %s LIMIT 1", $option ) );
                // Has to be get_row instead of get_var because of funkiness with 0, false, null values
                if ( is_object( $row ) ) {
                    $value = $row->option_value;
                    wp_cache_add( $option, $value, 'options' );
                } else { // option does not exist, so we must cache its non-existence
                    if ( ! is_array( $notoptions ) ) {
                        $notoptions = array();
                    }
                    $notoptions[ $option ] = true;
                    wp_cache_set( 'notoptions', $notoptions, 'options' );
                    /** This filter is documented in wp-includes/option.php */
                    return apply_filters( "default_option_{$option}", $default, $option, $passed_default );
                }
            }
        }
    } else {
        $suppress = $wpdb->suppress_errors();
        $row   = $wpdb->get_row( $wpdb->prepare( "SELECT option_value FROM $wpdb->options WHERE option_name = %s LIMIT 1", $option ) );
        $wpdb->suppress_errors( $suppress );
        if ( is_object( $row ) ) {
            $value = $row->option_value;
        } else {
            /** This filter is documented in wp-includes/option.php */
            return apply_filters( "default_option_{$option}", $default, $option, $passed_default );
        }
    }
    if ( 'home' == $option && '' == $value ) {
        return get_option( 'siteurl' );
    }
    if ( in_array( $option, array( 'siteurl', 'home', 'category_base', 'tag_base' ) ) ) {
        $value = untrailingslashit( $value );
    }
    return apply_filters( "option_{$option}", maybe_unserialize( $value ), $option );
}

WordPress add_filter()

Syntax

add_filter( string $tag, callable $function_to_add, int $priority = 10, int $accepted_args = 1)

Usage

It is called by themes/plugins, is used to add filters to the queue to be applied to the hook by core.
Add this below code in wp-includes/plugin.php

function apply_filters( $tag, $value ) {
    global $wp_filter, $wp_current_filter;
    $args = func_get_args();
    if ( isset( $wp_filter['all'] ) ) {
        $wp_current_filter[] = $tag;
        _wp_call_all_hook( $args );
    }
    if ( ! isset( $wp_filter[ $tag ] ) ) {
        if ( isset( $wp_filter['all'] ) ) {
            array_pop( $wp_current_filter );
        }
        return $value;
    }
    if ( ! isset( $wp_filter['all'] ) ) {
        $wp_current_filter[] = $tag;
    }
    array_shift( $args );
    $filtered = $wp_filter[ $tag ]->apply_filters( $value, $args );
    array_pop( $wp_current_filter );
    return $filtered;
}

WordPress apply_filters()

Syntax

apply_filters(string $tag, mixed $value)

Usage

This is a callback function that has to been added to a filter hook.  The callback functions attached to the filter hook are invoked by calling this function. apply_filters() function can be used to create a new filter hook by simply calling this function with the name of the new hook specified using the $tag parameter.
Add this below code in wp-includes/plugin.php.

function apply_filters( $tag, $value ) {
    global $wp_filter, $wp_current_filter;
    $args = func_get_args();
    if ( isset( $wp_filter['all'] ) ) {
        $wp_current_filter[] = $tag;
        _wp_call_all_hook( $args );
    }
    if ( ! isset( $wp_filter[ $tag ] ) ) {
        if ( isset( $wp_filter['all'] ) ) {
            array_pop( $wp_current_filter );
        }
        return $value;
    }
    if ( ! isset( $wp_filter['all'] ) ) {
        $wp_current_filter[] = $tag;
    }
    array_shift( $args );
    $filtered = $wp_filter[ $tag ]->apply_filters( $value, $args );
    array_pop( $wp_current_filter );
    return $filtered;
}

WordPress get_theme_mod()

Syntax 

get_theme_mod(string $name, string|false $default = false)

Usage

get_theme_mod() is used to filter the theme modification, retrieve all the theme modifications.
Add this below code in wp-includes/theme.php to do the same.

<?php Function get_theme_mod($name, $default = false) {
	$mod = get_theme_mods();
	if( isset( $mod [ $name ] ) ) {
		Return apply_filters( "theme_mod_{$name}", $mod[ $name ]);
}
if ( is_string( $default ) ) {
        // Only run the replacement if an sprintf() string format pattern was found.
        if ( preg_match( '#(?<!%)%(?:\d+\$?)?s#', $default ) ) {
            $default = sprintf( $default, get_template_directory_uri(), get_stylesheet_directory_uri() );
        }
    }
return apply_filters( "theme_mod_{$name}", $default );
}

In header.php  add, 

<?php get_theme_mod( $name, $default );?>

How to Ban Users Accounts in WordPress

Are you looking for a way to allow the admin to band WordPress user accounts? While there’s probably a plugin for this, we have created a quick code snippet that you can use to ban users accounts in WordPress.

All you have to do is add this code to your theme’s functions.php file or in a site-specific plugin:

// display checkbox to admin
add_action( 'edit_user_profile', 'ban_user_profile_fields' );
function ban_user_profile_fields( $user ) {
 global $current_user;
 if ( current_user_can( 'edit_user' ) && $user->ID != $current_user->ID ){
  $status = get_the_author_meta( 'ban_user', $user->ID  );
  ?>
  <h3><?php _e("Account Status", "blank"); ?></h3>
  <table class="form-table">
 
  <tr>
       <th>Ban User</th>
       <td><label for="ban_user"><input type="checkbox" name="ban_user" id="ban_user" value="1" <?php if($status == 1){ echo ' checked'; } ?> /></label>
       <span class="description"><?php _e("Check this option to ban this users account."); ?></span>
       </td>
  </tr>
 
  </table>
  <?php
 }
}
 
// Save profile update
add_action( 'edit_user_profile_update', 'save_extra_user_profile_fields' );
function save_extra_user_profile_fields( $user_id ){
      if ( !current_user_can( 'edit_user', $user_id ) ) { return false; }
      update_usermeta( $user_id, 'ban_user', $_POST['ban_user'] );
}
 
// Check if user is banned
add_filter( 'wp_authenticate_user', 'login_ban_status', 1 );
function login_ban_status($user) {
 
        if ( is_wp_error( $user ) ) { return $user; }
        $status = get_user_meta( $user->ID, 'ban_user', 'true' );
 
        if($status == 1){
          return new WP_Error( 'banned', __('<strong>ERROR</strong>: This user account has been banned.', 'banned') );
        }
 
        return $user;
}

Note: If this is your first time adding code snippets in WordPress, then please refer to our guide on how to properly copy / paste code snippets in WordPress, so you don’t accidentally break your site.

Page 1 of 11

Powered by WordPress & Theme by Anders Norén