These are just raw notes on WordPress. They aren’t necessarily organized in any specific way, this is more of a board to place things I learn about the platform. I used to have these unorganized within the notes app on my phone, but by placing them here I hope that someone else can use them too. If you have any questions on the notes or a question on a particular snippet feel free to reach out to me using the form at the bottom of this page.
The Settings Sidebar is displayed even when editing a block in HTML mode, so it should only contain block-level settings
View template name on front-end:
<?
add_filter( 'template_include', 'var_template_include', 1000 );
function var_template_include( $t ){
$GLOBALS['current_theme_template'] = basename($t);
return $t;
}
function get_current_template( $echo = false ) {
if( !isset( $GLOBALS['current_theme_template'] ) )
return false;
if( $echo )
echo $GLOBALS['current_theme_template'];
else
return $GLOBALS['current_theme_template'];
}
?>
Then the markup is:
<div>
<strong>Current template:</strong>
<?php get_current_template( true ); ?>
</div>
Get Terms
<?
$terms = get_the_terms($post->ID, 'category');
$count = count($terms);
if ( $count > 0 ){
foreach ( $terms as $term ) {
echo $term->name;
}
}
?>
Friendly String:
<?
function friendlyString($string) {
// lower case everything
$string = strtolower($string);
// make alphanumeric (removes all other characters)
$string = preg_replace("/[^a-z0-9_\s-]/", "", $string);
// clean up multiple dashes or whitespaces
$string = preg_replace("/[\s-]+/", " ", $string);
// convert whitespaces and underscore to dash
$string = preg_replace("/[\s_]/", "-", $string);
return $string;
}
?>
Move Yoast to bottom:
<?
function yoasttobottom() {
return 'low';
}
add_filter( 'wpseo_metabox_prio', 'yoasttobottom');
?>
Remove content editor for post type:
<?
add_action('init', 'remove_content_editor');
function remove_content_editor() {
remove_post_type_support( 'posttype', 'editor' );
}
?>
Check if a page is parent or child:
<?
function is_tree($pid) {
// $pid = The ID of the page we're looking for pages underneath
global $post; // load details about this page
if(is_page()&&($post->post_parent==$pid||is_page($pid)))
return true; // we're at the page or at a sub page
else
return false; // we're elsewhere
};
// usage
if ( $post->post_parent == '2' ) {
// do stuff
}
?>
Rename tables in MySQL to wp_
RENAME table `wpBalancePD_commentmeta` TO `wp_commentmeta`;
RENAME table `wpBalancePD_comments` TO `wp_comments`;
RENAME table `wpBalancePD_links` TO `wp_links`;
RENAME table `wpBalancePD_options` TO `wp_options`;
RENAME table `wpBalancePD_postmeta` TO `wp_postmeta`;
RENAME table `wpBalancePD_posts` TO `wp_posts`;
RENAME table `wpBalancePD_terms` TO `wp_terms`;
RENAME table `wpBalancePD_termmeta` TO `wp_termmeta`;
RENAME table `wpBalancePD_term_relationships` TO `wp_term_relationships`;
RENAME table `wpBalancePD_term_taxonomy` TO `wp_term_taxonomy`;
RENAME table `wpBalancePD_usermeta` TO `wp_usermeta`;
RENAME table `wpBalancePD_users` TO `wp_users`;
Create user in mySQL for WordPress as newadmin with password pass123
INSERT INTO `wp_users` (`user_login`, `user_pass`, `user_nicename`, `user_email`, `user_status`)
VALUES ('newadmin', MD5('pass123'), 'firstname lastname', 'email@example.com', '0');
INSERT INTO `wp_usermeta` (`umeta_id`, `user_id`, `meta_key`, `meta_value`)
VALUES (NULL, (Select max(id) FROM wp_users), 'wp_capabilities', 'a:1:{s:13:"administrator";s:1:"1";}');
INSERT INTO `wp_usermeta` (`umeta_id`, `user_id`, `meta_key`, `meta_value`)
VALUES (NULL, (Select max(id) FROM wp_users), 'wp_user_level', '10');
Extra security measures:
Moving the wp-config file out of the root WordPress directory is a good security measure, making it nearly impossible to potentially access this file from a web browser.
If you receive the error message âError establishing a database connectionâ, the first thing to do is verify that the DB_NAME, DB_USER, and DB_PASSWORD options are correctly set for your database server. Also verify that the DB_HOST name is set to the correct host for your server.
WordPress security can be strengthened by setting secret keys in your wp-config file. A secret key is a hashing salt, which makes your site harder to hack by adding random elements (the salt) to the password you set. To have secret keys auto-generated for you visit the link to WordPress.org for secret key generation in your wp-config file.
Another security feature included in wp-config is the ability to define the database table prefix for WordPress. By default, this option value is set to wp_. You can change this value by setting the $table _ prefix variable to any prefix like so: $table_prefix = âlecter_â;
You can also lock down your wp-admin directory. This means that only IP addresses you specify can access your admin dashboard URLs. This makes it much harder for anyone else to try to hack your WordPress back end. To accomplish this, create a separate .htaccess file in your wp-admin directory with the following code
AuthUserFile /dev/null AuthGroupFile /dev/null AuthName âAccess Controlâ WordPress Configuration | 39 AuthType Basic order deny, allow deny from all #IP address to whitelist allow from xxx.xxx.xxx.xxx
Add these three lines to the wp-config file and wordpress will no longer ask you for your password when using the automatic installer:
define( 'FTP_USER', 'username' );
define ( 'FTP_PASS', 'password' );
define( 'FTP_HOST', 'www.example.com' );
Deny anyone access to wp-config file by adding the following in the .htaccess file:
<files wp-config.php>
order allow,deny
deny from all
</files>
Perfect title tag script:
<title><?php if(function_exists('is_tag') && is_tag()) {echo 'Tag Archive for "'.$tag.'" - ';}elseif(is_archive()) {wp_title('');echo ' - ';}elseif(is_front_page()){echo '';}elseif(is_search()) {echo 'Search for "'.wp_specialchars($s).'" - ';}elseif(!(is_404()) && (is_single()) || (is_page())) {wp_title('');echo ' - ';}elseif(is_404()) {echo 'Not Found - ';}if(is_home()) {bloginfo('name'); echo ' - ';bloginfo('description');}else{bloginfo('name');}?></title>
For a customizable word count put this in the functions.php file:
function excerpt($limit) {
$excerpt = explode(' ', get_the_excerpt(), $limit);
if (count($excerpt)>=$limit) {
array_pop($excerpt);
$excerpt = implode(" ",$excerpt).'...';
} else {
$excerpt = implode(" ",$excerpt);
}
$excerpt = preg_replace('`\[[^\]]*\]`','',$excerpt);
return $excerpt;
}
function content($limit) {
$content = explode(' ', get_the_content(), $limit);
if (count($content)>=$limit) {
array_pop($content);
$content = implode(" ",$content).'...';
} else {
$content = implode(" ",$content);
}
$content = preg_replace('`\[[^\]]*\]`','',$content);
return $content;
}
Then in the template file put:
<?php echo excerpt(15); ?>
where 15 is the number of words allowed. You can then add the following afterwards.
<a href="<?php the_permalink(); ?>">More</a>
When using a custom loop, you should always reset the post data after the loop with either wp_reset_postdata() or wp_reset_query()
Register a custom post type:
$labelsNews = array (
'name' => 'News',
'singular_name' => 'News',
'add_new' => 'Add New',
'add_new_item' => 'Add New News',
'edit_item' => 'Edit News',
'new_item' => 'New News',
'all_items' => 'All News',
'view_item' => 'View News',
'search_items' => 'Search News',
'not_found' => 'No news found',
'not_found_in_trash' => 'No news found in Trash',
'parent_item_colon' => '',
'menu_name' => 'News'
);
$argsNews = array (
'labels' => $labelsNews,
'public' => true,
'publicly_queryable' => true,
'show_ui' => true,
'show_in_menu' => true,
'query_var' => true,
'rewrite' => array('slug' => 'news', 'with_front' => false),
'capability_type' => 'post',
'has_archive' => true, 'hierarchical' => true,
'supports' => array('title', 'editor', 'author', 'thumbnail')
);
register_post_type('news', $argsNews);
Get categories for a custom post type:
function the_simple_terms() {
global $post;
$terms = get_the_terms($post->ID,'news','',', ','');
$terms = array_map('_simple_cb', $terms);
return implode(', ', $terms);
}
function _simple_cb($t) {
return $t->name;
}
Create custom sidebar:
Add this to functions.php:
function about_full_width_sidebar_init() {
register_sidebar( array(
'name' => 'About Full Width Sidebar',
'id' => 'about_full_width_sidebar',
'before_widget' => '<div>',
'after_widget' => '</div>',
'before_title' => '<h2 class="rounded">',
'after_title' => '</h2>',
) );
}
add_action( 'widgets_init', 'about_full_width_sidebar_init' );
Add this to whatever sidebar.php file you are using:
<? if ( is_active_sidebar( 'home_right_1' ) ) : ?>
<div id="primary-sidebar" class="primary-sidebar widget-area" role="complementary">
<? dynamic_sidebar( 'home_right_1' ); ?>
</div>
<?endif; ?>
Add either of the following to the section you would like it to appear on the page:
<? get_sidebar(); ?>
// or
<? get_sidebar(âaboutâ); ?>
To Remove all chance of comments:
- Uncheck first three options on the Settings > Discussion Page and also check comments must be approved for moderation
- Uncheck allow comments on all previous posts and media attachments
- Add the following script:
function filter_media_comment_status( $open, $post_id ) {
$post = get_post( $post_id );
if( $post->post_type == 'attachment' ) {
return false;
}
return $open;
}
add_filter( 'comments_open', 'filter_media_comment_status', 10 , 2 );
Gravity forms add custom post type to select dropdown:
// Add custom post type "careers" as options of the select menu with the css class of "populate-with-posts"
function winwar_populate_dropdown_with_posts($form){
foreach($form['fields'] as &$field){
if($field[âinputTypeâ] == âselectâ && strpos($field[âcssClassâ], âpopulate-with-postsâ) === true)
continue;
$posts = get_posts('numberposts=-1&post_status=publish&post_type=careers');
$choices = array(array('text' => '', 'value' => ' '));
foreach($posts as $post){
$choices[] = array('text' => $post->post_title, 'value' => $post->ID);
}
$field['choices'] = $choices;
}
return $form;
}
add_filter('gform_pre_render',
'winwar_populate_dropdown_with_posts');
}
Get Content from page based on ID:
<? $id=108; $post = get_post($id); $content = apply_filters('the_content', $post->post_content); echo $content; ?>
For AJAX in WordPress:
Add this to functions.php file and change path of /js/car-alarm.js:
add_action( 'wp_enqueue_scripts', 'my_enqueue' );
function my_enqueue() {
wp_enqueue_script('like_post', get_template_directory_uri().'/js/car-alarm.js', '1.0', 1 );
wp_localize_script('like_post', 'ajax_var', array(
'url' => admin_url('admin-ajax.php'),
'nonce' => wp_create_nonce('ajaxnonce')
));
}
add_action( 'wp_ajax_my_post_like', 'my_post_like' );
add_action( 'wp_ajax_nopriv_my_post_like', 'my_post_like' );
Then create a js file and make sure itâs linked properly with this:
var $wk_jq=jQuery.noConflict();
(function($wk_jq){
$wk_jq(window).bind("load",function(){
$wk_jq("#reset-button").click(function(eve){
heart = $wk_jq(this);
post_id = heart.data("post_id");
$wk_jq.ajax({
type: "post",
url: ajax_var.url,
data: "action=my_post_like&nonce="+ajax_var.nonce+"&post_id="+post_id,
success: function(count){
//do stuff here
}
});
eve.preventDefault();
return false;
});
});
})($wk_jq);
Register Custom Taxonomy:
add_action( 'init', 'create_portfolio_taxonomies', 0 );
function create_portfolio_taxonomies() {
$labels = array(
'name' => _x( 'Categories', 'taxonomy general name' ),
'singular_name' => _x( 'Categories', 'taxonomy singular name' ),
'search_items' => __( 'Search Categories' ),
'all_items' => __( 'All Categories' ),
'parent_item' => __( 'Parent Category' ),
'parent_item_colon' => __( 'Parent Category:' ),
'edit_item' => __( 'Edit Category' ),
'update_item' => __( 'Update Category' ),
'add_new_item' => __( 'Add New Category' ),
'new_item_name' => __( 'New Category Name' ),
'menu_name' => __( 'Categories' ),
);
$args = array(
'hierarchical' => true,
'labels' => $labels,
'show_ui' => true,
'show_admin_column' => true,
'query_var' => true,
'show_in_nav_menus' => true,
'rewrite' => array( 'slug' => 'products' )
);
register_taxonomy( 'cats', array( 'products' ), $args );
}
Loop through posts with a certain category in custom taxonomy:
<? $args = array(
'post_type' => âproductsâ,
'tax_query' => array(
array(
'taxonomy' => 'cats',
'field' => 'slug',
'terms' => âslug-goes-hereâ,
)
)
);
$loop = new WP_Query( $args ); while ( $loop->have_posts() ) : $loop->the_post(); ?>
@joekotlan on X