class Filter {
constructor() {
this.init();
}
async init() {
try {
const response = await fetch('http://validity.local/wp-json/wp/v2/posts');
const posts = await response.json();
this.renderPosts(posts);
} catch (error) {
console.error('Error fetching posts:', error);
}
}
renderPosts(posts) {
const outputDiv = document.getElementById('filter-output');
outputDiv.innerHTML = '';
posts.forEach((post) => {
const postTitle = document.createElement('h2');
postTitle.innerHTML = post.title.rendered;
outputDiv.appendChild(postTitle);
});
}
}
export default Filter;
Free
Global Margins in Block Theme
Heading
{
"version": 2,
"settings": {
"spacing": {
"margin": true,
"padding": true
}
},
...
"styles": {
"elements": {
"h2": {
"spacing": {
"margin": {
"bottom": "30px"
}
}
}
}
}
}
Paragraph
"blocks": {
"core/paragraph": {
"spacing": {
"margin": {
"bottom": "20px"
}
}
}
}
ToggleControl – Block Editor
import { useState } from 'react'; import { ToggleControl } from '@wordpress/components';
const [isHeroImageRight, setHeroImageRight] = useState(false);
<InspectorControls> <PanelBody> <ToggleControl label="Image Position" help={isHeroImageRight ? "Image Right." : "Image Left."} checked={isHeroImageRight} onChange={(newValue) => { setHeroImageRight(newValue); if (newValue) { console.log("ImageRight"); } else { console.log("ImageLeft"); } }} /> </PanelBody> </InspectorControls>
<div className={isHeroImageRight ? "hero-img-right" : "hero-img-left"}>
Custom Logo to WordPress Block
icon.js
const icon = (Add Font Awesome to WordPress Block Theme
npm install --save @fortawesome/fontawesome-free
function enqueue_font_awesome() { wp_enqueue_style( 'font-awesome', get_template_directory_uri() . '/node_modules/@fortawesome/fontawesome-free/css/all.min.css' ); } add_action('wp_enqueue_scripts', 'enqueue_font_awesome');
<i class="fas fa-user"></i>
Google Consent Mode V2
Step #1
Step #2
Add extra charges to specific shipping method in WooComerce
// ========================================================================= // ADD EXTRA FEE TO SPECIFIC SHIPPING METHOD // ========================================================================= add_action('woocommerce_cart_calculate_fees', 'add_handling_fee_for_specific_shipping_method', 10, 1); function add_handling_fee_for_specific_shipping_method($cart) { if (is_admin() && !defined('DOING_AJAX')) return; $chosen_methods = WC()->session->get('chosen_shipping_methods'); $chosen_shipping = $chosen_methods[0]; if ($chosen_shipping === 'flat_rate:5') { $fee = 500; // Kezelési költség mértéke $cart->add_fee(__('Kezelési költség postai kézbesítés esetén', 'woocommerce'), $fee); } }
Add notification to specific shipping method in WooComerce
// ========================================================================= // ADD NOTIFICATION TO SPECIFIC SHIPPING METHOD // ========================================================================= add_action('woocommerce_review_order_before_payment', function () { ?> <div id="mpl-warning" style="display:none;"> Figyelem! Amennyiben postával rendelne, 500 Ft kezelési költséget számítunk fel és a kiszállítási időt csak 20 napon belül tudjuk vállalni. </div> <script type="text/javascript"> jQuery(function($) { function updateHelloWorldVisibility() { var chosen_shipping = $('input[name^="shipping_method"]:checked').val(); if (chosen_shipping === 'flat_rate:5') { $("#mpl-warning").show(); } else { $("#mpl-warning").hide(); } } // Frissítjük a "Hello World" szöveg láthatóságát szállítási mód változásakor $(document.body).on('change', 'input[name^="shipping_method"]', updateHelloWorldVisibility); // Az oldal betöltésekor is ellenőrizzük a szállítási módot updateHelloWorldVisibility(); }); </script> <?php }, 10, 2);
How to use wp_kses in ACF?
functions.php
// ============================================================= // ALLOWED HTML IN ACF // ============================================================= function wpflames_allowed_html() { return array( 'a' => array( 'href' => array(), 'title' => array(), 'class' => array(), ), 'br' => array(), 'em' => array(), 'strong' => array(), ); }
<?php echo wp_kses(get_field('text'), wpflames_allowed_html()); ?>
Delete all WordPress posts from phpMyAdmin
DELETE FROM wp_posts WHERE post_type = 'post';
Create a Gutenberg Block
npx @wordpress/create-block static-block
npm install --save-dev style-loader css-loader sass-loader
Redirect home if user is not logged in
if (!is_user_logged_in()){ wp_redirect(esc_url(site_url('/'))); exit; }
wp_localize_script
function wpflames_localize_files() { wp_localize_script('main-js', 'wpflamesData', array( 'root_url' => get_site_url(), 'nonce' => wp_create_nonce('wp_rest') )); } add_action('wp_enqueue_scripts', 'wpflames_localize_files');
This code is a WordPress function named wpflames_localize_files
. Its purpose is to provide data to the scripts associated with a WordPress theme or plugin. Here’s a detailed explanation of what it does:
wp_localize_script
function: This function allows sending data from PHP to JavaScript scripts. In this case, the script named ‘main-js’ receives the data. ThewpflamesData
is an object that contains two pieces of data:
'root_url'
: Receives the result ofget_site_url()
, which returns the base URL of the WordPress installation.'nonce'
: A unique security token created by thewp_create_nonce('wp_rest')
function, which can be used in WordPress REST API calls to enhance the security of the site.
add_action
call: This is part of the WordPress hook system. Thewp_enqueue_scripts
is a specific event that WordPress triggers when loading scripts and stylesheets. We register ourwpflames_localize_files
function with this event, so the function runs on every page load.
In summary, this code can be used in a WordPress theme or plugin to make certain PHP-based data accessible to JavaScript, as well as to provide secure methods for using the WordPress REST API.
Webpack and @wordpress/scripts
Initialize package.json
npm init -y
Install wp-cli
npm install wp-cli --save-dev
Install WordPress Scripts for Webpack
npm install @wordpress/scripts --save-dev
Install Sass Loader
npm install sass-loader style-loader sass webpack --save-dev
webpack.config.js
const path = require('path'); module.exports = { entry: './assets/src/js/index.js', output: { filename: 'main.js', path: path.resolve(__dirname, 'assets/dist'), }, module: { rules: [ { test: /\.scss$/, use: [ 'style-loader', // injects CSS into the DOM 'css-loader', // translates CSS into CommonJS modules 'sass-loader' // compiles Sass to CSS ] } ] } };
package.json
"scripts": { "build": "wp-scripts build", "start": "wp-scripts start", "dev": "wp-scripts start", "devFast": "wp-scripts start", "test": "echo \"Error: no test specified\" && exit 1" },
Enqueue compiled JavaScript in WordPress
function enqueue_theme_scripts() { wp_enqueue_script('main-js', get_template_directory_uri() . '/assets/dist/main.js', array(), '1.0.0', true); } add_action('wp_enqueue_scripts', 'enqueue_theme_scripts');
Add Flag Icon to WordPress Nav Menu
// ========================================================================= // ADD FLAG ICON TO THE WORDPRESS NAV MENU // ========================================================================= function add_custom_menu_item ($items, $args) { ob_start(); $items .= '<li class="menu-item flag">'; $items .= '<a href="#" target="_blank"><img class="flag" src="'.THEME.'/assets/images/flags/flag-hu.svg" alt=""/></a>'; $items .= '</li>'; return $items; } add_filter( 'wp_nav_menu_items', 'add_custom_menu_item', 10, 2 );
flag-hu.svg
<svg version="1.1" id="flag-hu" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 50 34" style="enable-background:new 0 0 50 34;" xml:space="preserve"> <style type="text/css"> .st0{fill:#CE2939;} .st1{fill:#FFFFFF;} .st2{fill:#477050;} </style> <rect id="black_stripe" y="0" class="st0" width="50" height="34"/> <rect id="red_stripe" y="11.3" class="st1" width="50" height="22.7"/> <rect id="gold_stripe" y="22.7" class="st2" width="50" height="11.3"/> </svg>
flag-de.svg
<svg version="1.1" id="flag-de" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 50 34" style="enable-background:new 0 0 50 34;" xml:space="preserve"> <style type="text/css"> .st0{fill:#DD0000;} .st1{fill:#FFCE00;} </style> <rect id="black_stripe" y="0" width="50" height="34"/> <rect id="red_stripe" y="11.4" class="st0" width="50" height="22.6"/> <rect id="gold_stripe" y="22.6" class="st1" width="50" height="11.4"/> </svg>
Add chevron to nav menu has children
// ========================================================================= // Chevron to nav menu has children // ========================================================================= function parent_menu_dropdown( $item_output, $item, $depth, $args ) { if ( is_nav_menu( 'Header Menu' ) && ! empty( $item->classes ) && in_array( 'menu-item-has-children', $item->classes ) ) { return $item_output . '<svg class="chevron-down" fill="#ffffff" xmlns="http://www.w3.org/2000/svg" height="1em" viewBox="0 0 512 512"><path fill="#ffffff" d="M233.4 406.6c12.5 12.5 32.8 12.5 45.3 0l192-192c12.5-12.5 12.5-32.8 0-45.3s-32.8-12.5-45.3 0L256 338.7 86.6 169.4c-12.5-12.5-32.8-12.5-45.3 0s-12.5 32.8 0 45.3l192 192z"/></svg>'; } return $item_output; } add_filter( 'walker_nav_menu_start_el', 'parent_menu_dropdown', 10, 4 );
Nav Walker – custom sub-menu class
1st level sub menu
<ul class="sub-menu-1">
2nd level sub menu
<ul class="sub-menu-2">
<?php class Custom_Walker_Nav_Menu extends Walker_Nav_Menu { function start_lvl(&$output, $depth = 0, $args = array()) { $indent = str_repeat("\t", $depth); $submenu_class = 'sub-menu-' . ($depth + 1); $output .= "\n$indent<ul class=\"$submenu_class\">\n"; } } wp_nav_menu(array( 'theme_location' => 'desktop_menu', 'menu_class' => 'desktop-menu', 'walker' => new Custom_Walker_Nav_Menu(), )); <
GTM4WP
// Add Google Tag code which is supposed to be placed after opening body tag. function wpdoc_add_custom_body_open_code() { if ( function_exists( 'gtm4wp_the_gtm_tag' ) ) { gtm4wp_the_gtm_tag(); } } add_action( 'wp_body_open', 'wpdoc_add_custom_body_open_code' );
Masonry layout with SCSS
How to use Mailgun as SMTP without plugin
If You want to replace WP Mail SMTP plugin use this snippet.