Category: PHP

How to get count of posts in a particular category?

You can get get count of posts in a particular category by using below code. Before use please replace “CUSTOM_POST_TYPE” and “CUSTOM_TAXONOMY” with your post type and taxonomy.

$the_query = new WP_Query( array(
    'post_type' => 'CUSTOM_POST_TYPE',
    'tax_query' => array(
        array(
            'taxonomy' => 'CUSTOM_TAXONOMY',
            'field' => 'id',
            'terms' => TERM_ID
        )
    )
) );
$count = $the_query->found_posts;

Have any doubt please comment here.

Redirect non admin users to home page and disallow back end access in WordPress

For redirect non admin users to home page and disallow back end access in WordPress, you need to simply copy and paste the following code in your theme’s functions.php file.

function redirect_non_admin_user(){
    if ( !defined( 'DOING_AJAX' ) && !current_user_can('administrator') ){
        wp_redirect( site_url() );  exit;
    } 
}
add_action( 'admin_init', 'redirect_non_admin_user' );

Have any doubt, then comment here!

Disable WooCommerce Payment methods based on cart item quantity

To disable WooCommerce Payment methods based on cart item quantity, you need to simply copy and paste the following code in your theme’s functions.php file.
Here I’m unsetting the COD when cart item quantity limit reached 10.

add_filter('woocommerce_available_payment_gateways', 'disable_payment_gateway_based_on_quantity', 10, 1);
function disable_payment_gateway_based_on_quantity( $available_gateways ) 
{
    $qty_limit = 10;
    $limit_reached = false;
    foreach(WC()->cart->get_cart() as $cart_item){
        if($cart_item['quantity'] > $qty_limit ){
            $limit_reached = true;
            break;
        }
    }
    if($limit_reached){
        unset($available_gateways['cod']);
    }
    return $available_gateways;
}

You can use the same code for disable WooCommerce Payment methods based on cart item quantity. Change quantity and payment method slug for your needs.

Have any doubt, then comment here!