WordPress
Embed WordPress Functions Outside WordPress
Create a Sub directory on the wordpress and add the code
require( '../my_wordpress_install_root/wp-load.php' );
get_header();
echo 'new content outside WordPress';
get_footer();
Programmatically login a user without a password:
$username = "admin";
$user = get_user_by('login', $username );
if ( !is_wp_error( $user ) && !is_user_logged_in())
{
wp_clear_auth_cookie();
wp_set_current_user ( $user->ID );
wp_set_auth_cookie ( $user->ID );
}
Declaring WooCommerce support in themes(custom themes)
function mytheme_add_woocommerce_support() {
add_theme_support( 'woocommerce' );
}
add_action( 'after_setup_theme', 'mytheme_add_woocommerce_support' );
Passing Value from template file to header
STEP1:
// in template file
global $template_var;
$template_var = 'Test value'
get_header();
STEP2:
// in header.php
global $template_var;
echo $template_var; // 'Test value'
Hooks
There are two types of hooks: actions and filters.
- Actions allow you to add extra functionality at a specific point in the processing of the page—for example, you might want to add extra widgets or menus, or add a promotional message to your page.
- Filters allow you to intercept and modify data as it is processed—for example, you might want to insert another CSS class in a WordPress HTML element, or modify some of your pages blocks.
In brief: actions do stuff; filters change stuff.
*Actions:
1. add_action
2. do_action
3. remove_action
do_action : Registers an action hook while add_action : adds a callback function to the registered hook.
do_action :
do_action( ‘after_gill_arrives’ , $gill_has_keys = true , $gill_has_car = true );
This tells WordPress to create a hook called ‘after_gill_arrives’, run any actions that are attached to this hook, and pass the arguments $gill_has_keys and $gill_has_car to those actions (the 2 arguments we specified above).
*Filters:
1. add_filter
2. apply_filter
*Priority:
add_action('init', 'run_me_early', 9);
add_action('init', 'run_me_normal'); // default value of 10 is used since a priority wasn't specified
add_action('init', 'run_me_late', 11);
The first function to run will be run_me_early(), followed by run_me_normal(), and finally the last one to run will be run_me_late().
Reference: https://docs.presscustomizr.com/article/26-wordpress-actions-filters-and-hooks-a-guide-for-non-developers
Taxonomy
Taxonomy is a way to group things together.
SYNTAX: the_terms( $id, $taxonomy);
Eg: the_terms( $post->ID, 'category' );
This will display all the categories of the current post.
In WordPress, terms refers to the items in a taxonomy.
For example, a website has categories books, politics, and blogging in it. While category itself is a taxonomy the items inside it are called terms.
Default Taxonomies: Category, Tag, ....
Pagination
*echo paginate_links();
Output: « Prev 1 … 3 4 5 6 7 … 9 Next »
*previous_posts_link();
next_posts_link();
Custom Query with Pagination
$current_page = ( get_query_var('paged') ) ? get_query_var('paged') : 1; //get current page no from URL
$about_post = new WP_Query(array('category_name' => 'about',
'post_per_page' => 3,
'paged' => $current_page //get post from current page ));
//the above object will get all the post from the category "about" and displays 3 posts per page.
if($about_post -> have_posts()): //check if it has post
while($about_post -> have_posts()): //loop
$about_post -> the_post(); //we need to call "the_post" method to get details of each post
the_title(); // displays the title of each post
endwhile;
$max_pages = $about_post->max_num_pages; //total no of pages
next_posts_link('Next Page', $max_pages); //ordinary pagination
previous_posts_link(); //ordinary pagination
echo paginate_links(array('total' => $max_pages)); //numbered pagination
endif;
NOTE:
next_posts_link() and paginate_links() will not work as it is on custom query.
previous_posts_link() will work on custom query.
How to hide subcategory products from main category in Woocommerce?
Add the following lines of code at the end of your theme’s functions.php file.
function exclude_product_cat_children($wp_query) {
if ( isset ( $wp_query->query_vars['product_cat'] ) && $wp_query->is_main_query()) {
$wp_query->set('tax_query', array(
array (
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => $wp_query->query_vars['product_cat'],
'include_children' => false
)
)
);
}
}
add_filter('pre_get_posts', 'exclude_product_cat_children');
Programmatically login a user without a password:
$username = "admin";
$user = get_user_by('login', $username );
if ( !is_wp_error( $user ) && !is_user_logged_in())
{
wp_clear_auth_cookie();
wp_set_current_user ( $user->ID );
wp_set_auth_cookie ( $user->ID );
}
$queried_object = get_queried_object();
var_dump( $queried_object );
Ajax Cart Count Update on Cart Page
add_filter( 'woocommerce_add_to_cart_fragments', 'woocommerce_header_add_to_cart_fragment' );
function woocommerce_header_add_to_cart_fragment( $fragments ) {
global $woocommerce;
ob_start();
?>
CART (cart->cart_contents_count; ?>)
WordPress User Roles and Capabilities
A Role identifies a group of users who are allowed to execute the same tasks onto the website.
A Capability is the ability (or permission) to perform each single task assigned to a role.
function kinsta_add_caps(){
$student = get_role( 'student' );
$student->add_cap( 'read_student_project' );
$student->add_cap( 'edit_student_project' );
$student->add_cap( 'edit_student_projects' );
$student->add_cap( 'delete_student_project' );
$student->add_cap( 'delete_student_projects' );
}
add_action( 'admin_init', 'kinsta_add_caps');
Install wordpress in subdirectory
Fix Permalinks:
If you have a separate WordPress install in the root directory, then the .htaccess files of your subdirectory will cause conflict. This will result in 404 errors on your website.
To solve this, you need to edit the .htaccess file in your subdirectory WordPress install. Replace the code inside your .htaccess file with the following code:
# BEGIN WordPress
RewriteEngine On
RewriteBase /your-subdirectory/
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /your-subdirectory/index.php [L]
# END WordPress
Don’t forget to replace /your-subdirectory/ with your own subdirectory name.
Logging
public function generate_log( $msg )
{
$log_date = date('Y-m-d H:i:s');
$log_msg = '[' . $log_date . '] ' . $msg . PHP_EOL;
file_put_contents(plugin_dir_path(__FILE__).'/log/woo_offline_payment.log', $log_msg, FILE_APPEND);
}
How to Use Shortcodes in your WordPress Sidebar Widgets
By default, shortcodes are not allowed to be executed in a custom HTML widget. To change this, you will need to add the following code to your theme’s functions.php file
add_filter( 'widget_text', 'do_shortcode' );
add_action( 'init', 'process_post' );
Fires after WordPress has finished loading but before any headers are sent.
add_shortcode('gpbcridereg', 'gpbcridereg_shortcode');
add_filter('gform_pre_render_4', 'ridereg_pre_render_function');
add_shortcode('gpbc_clubrides', 'gpbcclubrides_shortcode');
function gpbcclubrides_shortcode($attr) {
ob_start(); //shortcodes should not output anything, but rather, return
$args = array(
'post_type' => array('ride', 'club_ride', 'archive_ride'),
'orderby' => 'wpcf-date-and-time',
'meta_key' => 'wpcf-date-and-time',
'posts_per_page' => -1,
'order' => 'ASC',
'meta_query' => array(
array(
'key' => 'wpcf-ride-type',
'value' => 'Club',
'compare' => 'LIKE',
),
),
);
$query = new WP_Query($args);
if ($query->have_posts()) {
?>
| Date |
Time |
Ride Description |
Leader |
Distance |
have_posts()) :
$query->the_post();
$mymeta = get_post_meta(get_the_ID());
$types = unserialize($mymeta['wpcf-ride-type'][0]);
$weekly = false;
foreach ($types as $t) {
if ($t[0] == 'Weekly') {
$weekly = true;
}
}
if ($weekly) {
$dayofweek = date('l', $mymeta['wpcf-date-and-time'][0]);
$today = date('l') + 5 60 60;
if ($today == $dayofweek) {
$nextride = time();
} else {
$nextride = strtotime('next ' . $dayofweek);
}
} else {
$nextride = $mymeta['wpcf-date-and-time'][0];
}
ob_start();
?>
|
|
= date('g:i a', $mymeta['wpcf-date-and-time'][0]);
?> |
= get_the_title() ?>
|
', $t);
}
?> |
= $mymeta['wpcf-distance'][0];
?> |
';
$k = array_keys($rides);
print_r($k);
echo '';
}
foreach ($rides as $r) {
echo $r;
}
wp_reset_query();
?>
//helper function to write log files to disk
function custom_log($x, $new = false, $show = false) {
if (!file_exists(ABSPATH . '/orderlog')) mkdir(ABSPATH . '/orderlog');
$lf = ABSPATH . '/orderlog/orderinfo' . date('Y_m_d') . '.log';
if ($new) {
file_put_contents($lf, '-----------' . date('m/d/Y H:i:s') . '-------------------------------------------', FILE_APPEND);
file_put_contents($lf, $x . "\n", FILE_APPEND);
} else {
file_put_contents($lf, $x . "\n", FILE_APPEND);
}
if ($show) {
var_dump($x);
}
}
Custom Theme Creation:
Style.css -
/*
Theme Name: Manzitto-V1
Template: twentysixteen
Version: 1
*/
Rename theme folder name to manzitto-v1
Child theme:
Create a folder for child theme and add the below in style.css
/*
Theme Name: Twenty Fifteen Child
Theme URI: http://example.com/twenty-fifteen-child/
Description: Twenty Fifteen Child Theme
Author: John Doe
Author URI: http://example.com
Template: twentyfifteen
Version: 1.0.0
License: GNU General Public License v2 or later
License URI: http://www.gnu.org/licenses/gpl-2.0.html
Tags: light, dark, two-columns, right-sidebar, responsive-layout, accessibility-ready
Text Domain: twentyfifteenchild
*/
template - parent theme directory
need to enque the parent theme css or import in the CSS
https://developer.wordpress.org/themes/advanced-topics/child-themes/
Theme - To make the theme in our controll(rename the theme folder name - it will make the theme in our controll & no theme update will be shown), the name on the style.css is just for displaying name on frontend.
Plugin - If we change the plugin folder or plugin name the update will be still thr, we need to write some function on the code to disable the update.
overwrite woocommerce widgets in theme
https://www.skyverge.com/blog/overriddin-woocommerce-widgets/
WooCommerce USPS Shipping by woocommerce - configure only USPS User ID, it will fetch automatically rates from their.
SHIPPING -
To set up shipping in WooCommerce, you first set up shipping zones, then add methods to those zones, and lastly, rates to your methods.
The shipping rate will be calculated based on the state, country, zip code entered on the checkout page.
If payment method needs to show only for particular shipping zone, set on the payment settings page.
Files for blog -
* index.php
*template parts/ content.php
// Load the Internet Explorer specific stylesheet.
wp_enqueue_style( 'twentysixteen-ie', get_template_directory_uri() . '/css/ie.css', array( 'twentysixteen-style' ), '20160816' );
wp_style_add_data( 'twentysixteen-ie', 'conditional', 'lt IE 10' );
// Load the Internet Explorer 8 specific stylesheet.
wp_enqueue_style( 'twentysixteen-ie8', get_template_directory_uri() . '/css/ie8.css', array( 'twentysixteen-style' ), '20160816' );
wp_style_add_data( 'twentysixteen-ie8', 'conditional', 'lt IE 9' );
// Load the Internet Explorer 7 specific stylesheet.
wp_enqueue_style( 'twentysixteen-ie7', get_template_directory_uri() . '/css/ie7.css', array( 'twentysixteen-style' ), '20160816' );
wp_style_add_data( 'twentysixteen-ie7', 'conditional', 'lt IE 8' );
mailchimp - audience | list