Skip to content

Instantly share code, notes, and snippets.

@regepan
Last active May 28, 2023 08:50
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save regepan/017213e3126228043884d5003a715227 to your computer and use it in GitHub Desktop.
Save regepan/017213e3126228043884d5003a715227 to your computer and use it in GitHub Desktop.

WordPress snippets

install WordPress by WP-CLI

# Download WordPress core
$ wp core download --locale=ja --version=6.0.3 --force

# Drop WordPress DB
$ wp db drop --yes

# Create DB & Install WordPress
$ wp db create && wp core install --url=https://192.168.56.10:4055 --title=Example --admin_user=yugo --admin_password=yugo --admin_email=a@a.com

# Import db.sql & Replace domain in DB
$ siteurl=`wp option get siteurl` && home=`wp option get home` && echo $siteurl && echo $home && wp db drop --yes && wp db create && wp db query < ./_db/db.sql && wp search-replace `wp option get siteurl` $siteurl && wp search-replace `wp option get home` $home

functions.php

https://gist.github.com/regepan/6d9767fd56339d4bdfe501aad14cfde3

This is "empty plugin" to avoid editing functions.php in theme.

https://github.com/woocommerce/theme-customisations

WordPress required basic plugins

Get attachment/upload local server full path from attachment id

https://developer.wordpress.org/reference/functions/get_attached_file/

Conditional Tags (is_page(), etc...)

https://codex.wordpress.org/Conditional_Tags

// can use array
is_page( array( 'page-name-a', 'page-name-b', 'page-name-c' ) )
is_singular( 'products' )

wordpress-popular-posts

https://wordpress.org/plugins/wordpress-popular-posts/

/**
 * Retrieves popular posts IDs.
 * https://wordpress.org/support/topic/get-popular-post-id-as-an-array-with-no-html/
 *
 * @param string $range
 * @param int $limit
 * @param string $post_type
 *
 * @return array
 */
function get_popular_posts_ids( $range = 'last7days', $limit = 10, $post_type = 'post' ) {
    $post_IDs = array();

    $query         = new \WordPressPopularPosts\Query( [
        'post_type' => $post_type,
        'range'     => $range,
        'limit'     => $limit,
    ] );
    $popular_posts = $query->get_posts();

    // Popular posts found, get their IDs
    if ( is_array( $popular_posts ) && ! empty( $popular_posts ) ) {
        foreach ( $popular_posts as $popular_post ) {
            $post_IDs[] = $popular_post->id;
        }
    }

    return $post_IDs;
}
global $post;

$post_ids = get_popular_posts_ids( 'last30days', 5 );

$posts = get_posts( array(
	'posts_per_page' => 5,
	'post_type'      => 'post',
	'include'        => $post_ids,
	'orderby'        => 'post__in',
) );

foreach ( $posts as $post ) {
	setup_postdata( $post );

	the_time( 'Y.m.d' );
	the_title();
}

wp_reset_postdata();

Ajax code on WordPress.

https://haniwaman.com/wordpress-ajax/

for debug

define( 'WP_DEBUG', false );

Can see how to use filter hook

http://hookr.io/filters/comment_notification_text/

wp_localize_script()

Pass values from PHP to JS.
https://developer.wordpress.org/reference/functions/wp_localize_script/

query_vars filter

function set_query_vars( $qvars ) {
    $qvars[] = 'xxx';

    return $qvars;
}

add_filter( 'query_vars', 'set_query_vars' );

Path

# include template
get_template_part( 'inc/parts', 'xxx' );

# image path
<img src="<?= esc_url( get_template_directory_uri() ); ?>/img/common/header/logo.png" alt="">

# /var/www/html/example/wp-content/themes/twentyten
get_template_directory()

Useful plugins

Advanced Custom Fields

intuitive-custom-post-order

https://github.com/hijiriworld/intuitive-custom-post-order

breadcrumb-navxt

https://wordpress.org/plugins/breadcrumb-navxt/
https://mtekk.us/code/breadcrumb-navxt/breadcrumb-navxt-doc/#Using bcn_display() and bcn_display_list()

<div class="breadcrumb" typeof="BreadcrumbList" vocab="https://schema.org/">
	<?php bcn_display(); ?>
</div>

ml slider

  • very simple

smart slider

  • many features
  • background + static front text. Slide only background image.

call via shortcode in php template.

do_shortcode('[jQueryArchiveList]');

get_post_type()

if ( get_post_type() === 'product' ) {
    // 'PRODUCT';
} else {
    // 'NEWS';
}
global $wp_query;
$postType = $wp_query->query['post_type'];
get_post_type_archive_link( get_post_type() );
get_post_type_archive_link( 'product' );

When you can not open WordPress top page.

  • Try to remove SSL redirect plugins. Redirect loop might be the reason for something error.
  • Try to access except TOP page.

Contact form 7

  1. Start mailcatcher
  2. If Japanese is used in radio button, it is needed to install https://eastcoder.com/code/wp-multibyte-patch/ , then set Japanese language for WordPress whole site language.
  3. "email" input field is needed input required.
  4. If it is needed, Enable rest api on .htaccess
# Enable rest api
SetEnvIf Request_URI ".*" AllowRestApi
  1. If xserver is trial period, Contact form 7 not working.
[contact-form-7 id="1234" title="Contact form 1" html_id="contact-form-1234" html_class="form-container"]

Change response message location

[response]

Stop autop

add_filter( 'wpcf7_autop_or_not', '__return_false' );

hook

https://qiita.com/matsumoto_sp/items/8613fc4a759f8a62da65

Contact Form 7 Multi-Step Forms

https://ja.wordpress.org/plugins/contact-form-7-multi-step-module/

Useful template_redirect action hook

https://the2g.com/347

Add URL by manually

https://firegoby.jp/archives/5309

wp_safe_redirect()

https://www.youfit.co.jp/archives/1485

Hide "Strict Standards" warning message PHP5.4 over

.php

ini_set('error_reporting', E_ALL | ~E_STRICT);

.htaccess

# <? ?> is allowed
php_flag short_open_tag On

Add page template name

/**
 * Template Name: Name
 */

Get link

<a href="<?= esc_url( home_url( 'xxx/' ) ); ?>">

Show new label only while 1 month

<?php

if ( date( 'U' ) - get_the_time( 'U', $post->ID ) < 24 * 60 * 60 * 30 ) {
?>
    <span class="label label-red">NEW</span>
<?php
}
?>

Template Hierarchy

https://developer.wordpress.org/themes/basics/template-hierarchy/

Visual Overview

https://developer.wordpress.org/files/2014/10/wp-hierarchy.png

Main loop

while ( have_posts() ) {
    the_post();

    the_title();
    the_content();
}

Access all post data

https://codex.wordpress.org/Template_Tags/get_posts#Access_all_post_data

<?php

global $post;

$last_posts = get_posts( array(
    'posts_per_page' => 3,
    'post_type'      => 'news',
) );

foreach ( $last_posts as $post ) {
    setup_postdata( $post );
    ?>
    <h2>
        <a href="<?php the_permalink(); ?>">
            <?php the_title(); ?>
        </a>
    </h2>
    
    <?php
    the_content();
}

wp_reset_postdata();
?>

wp_get_archives

https://developer.wordpress.org/reference/functions/wp_get_archives/

<?php

wp_get_archives( array(
    'post_type'       => 'post',
    'type'            => 'monthly',
    'show_post_count' => true,
) );

?>

Category(has child)

<ul>
    <?php
    wp_list_categories(array(
        "title_li" => "",
    ));
    ?>
</ul>

Get all Categories with link in single.php

the_category( ' ' );

Category + post count on sidebar

<div class="panel panel-default">
    <div class="panel-heading">
        <h3 class="panel-title">
            CATEGORIES
        </h3>
    </div>
    <div class="list-group">
        <?php
        $categories = get_categories();

        foreach ( $categories as $category ) {
            ?>
            <a href="<?= get_category_link( $category->term_id ); ?>" class="list-group-item <?= is_category( $category->name ) ? 'active' : ''; ?>">
                <?= $category->name; ?>
                
                <span class="badge">
                    <?= $category->category_count; ?>
                </span>
            </a>
            <?php
        }

        ?>
    </div>
</div>
/*
 *
---------------------------------------------------------*/
function my_excerpt_length( $length ) {
    return 80;
}

add_filter( 'excerpt_length', 'my_excerpt_length' );

jQuery in WordPress

jQuery(function ($) {
  $('.element').on('click', function() {
    $(this).hide();
  });
});

Display biz calendar widget

http://wpdocs.osdn.jp/%E3%83%86%E3%83%B3%E3%83%97%E3%83%AC%E3%83%BC%E3%83%88%E3%82%BF%E3%82%B0/the_widget

<?php the_widget( 'bizcalendarwidget' ); ?>

Get title

get_the_title( get_option('page_for_posts', true) );
post_type_archive_title();

Get category

// Category
$cat = get_the_category();
$catId = $cat[0]->cat_ID;
$catName = $cat[0]->name;
$catSlug = $cat[0]->category_nicename;
$link = get_category_link($catId);

// Custom post category(taxonomy)
$category = get_the_terms( $post->ID, 'product-category' );
$catName = $category[0]->name;

Stop adding auto p or br

https://setting-tool.net/wordpress-p-br-auto-format

Post_thumbnail

<?php
if ( get_the_post_thumbnail() ) {
    ?>
    <p>
	<?php
	the_post_thumbnail( 'post-thumbnail', array(
	    'class' => 'img-fluid',
	    'alt'   => get_the_title(),
	) );
	?>
    </p>
    <?php
}
?>

Truncate

// title
mb_strimwidth( get_the_title(), 0, 60, "...", "UTF-8" );

// content
$content = wp_strip_all_tags( get_the_content() );
nl2br( mb_strimwidth( $content, 0, 100, "...", "UTF-8" ) );

header & footer

<?php

get_header();// get header.php
get_footer();// get footer.php

wp_head();
wp_footer();

Active status implementation

$post_type = get_query_var( 'post_type' );// if custom post type.
var_dump( $post_type );

<ul class="nav navbar-nav">
    <li<?= (is_home()) ? ' class="active"' : ''; ?>>
        <a href="<?= esc_url(home_url('/')); ?>">
            TOP page
        </a>
    </li>
    <li class="<?= ( is_home() or is_singular( 'post' ) or is_category() ) ? 'active' : ''; ?>">
        <a href="<?= esc_url( home_url( 'news/' ) ) ?>">
          News
        </a>
    </li>
    <li class="<?= ( ( $post_type === 'products' ) or is_tax( 'product_category' ) ) ? 'active' : ''; ?>">
        <a href="<?= esc_url(home_url('products/')); ?>">

Short code in theme

do_shortcode( '[addtoany]' );

Unknown collation: 'utf8mb4_unicode_520_ci'

http://qiita.com/wonda/items/ee33ec26028e52cf9336

utf8mb4_unicode_520_ci
↓
utf8mb4_unicode_ci

Can use WordPress resources on outside WordPress directory.

require_once('../wp-blog-header.php');

WordPress get variaus path or url.

http://oxynotes.com/?p=8590

Can add "/" slash to editable permalink by Custom Permalinks plugin.

http://qiita.com/OJI3T/items/f3cd1219cb722b0c7eb8

md5 Hash Generator

http://www.miraclesalad.com/webtools/md5.php

md5

hoge
ea703e7aa1efda0064eaa507d9e8ab7e

Database Search and Replace Script in PHP

https://interconnectit.com/products/search-and-replace-for-wordpress-databases/ https://interconnectit.com/blog/2009/10/07/migrating-a-wordpresswpmubuddypress-website/

add_rewrite_rule()

https://nskw-style.com/2014/wordpress/wordpress-app-with-rewrite-api.html

ERROR 1813 (HY000) at line 24: Tablespace 'hoge.wp_commentmeta' exists.

After restore backup from Mac Time machine, MySQL show above error. https://cortyuming.hateblo.jp/entry/20120412/p1

Action Reference

https://codex.wordpress.org/Plugin_API/Action_Reference

Change WordPress table prefix by SQL

https://www.wpbeginner.com/wp-tutorials/how-to-change-the-wordpress-database-prefix-to-improve-security/

Multibyte functionality enhancement for the WordPress Japanese package.

https://wordpress.org/plugins/wp-multibyte-patch/

$ wp plugin install wp-multibyte-patch --activate

Anti-pattern(should not do this)

body class. should not add for component based CSS layout.

<body <?php body_class(); ?>>

Adds noindex to the robots meta tag.

https://developer.wordpress.org/reference/functions/wp_robots_no_robots/

add_filter( 'wp_robots', 'wp_robots_no_robots' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment