Chapitre 12.2 — Cheatsheets
Snippets copiables, alignés sur WordPress 6.x. À épingler pendant que vous codez. Chaque bloc renvoie au chapitre qui l’explique.
Hooks (Partie 5.2)
add_action( 'init', 'prefixe_cb' ); // faire qqch à un moment
add_filter( 'the_content', 'prefixe_cb' ); // transformer une valeur (RETOURNER !)
add_action( 'save_post_livre', 'cb', 10, 3 ); // priorité, nb d'args
remove_action( 'wp_head', 'wp_generator' ); // retirer (même priorité)
do_action( 'mon_hook', $arg ); // déclencher son action
$x = apply_filters( 'mon_filtre', $x ); // déclencher son filtrePattern de page/action sécurisée (Partie 7.7)
// Action mutante : nonce → capability → sanitize → agir
if ( ! isset( $_POST['n'] ) || ! wp_verify_nonce( $_POST['n'], 'action' ) ) { wp_die(); }
if ( ! current_user_can( 'edit_post', $id ) ) { wp_die(); }
$val = sanitize_text_field( wp_unslash( $_POST['val'] ) );
update_post_meta( $id, '_cle', $val );
// Affichage : TOUJOURS échapper
echo esc_html( $val ); // texte
echo esc_url( $url ); // href/src
echo esc_attr( $x ); // attributWP_Query (Partie 5.5)
$q = new WP_Query( array(
'post_type' => 'livre',
'post_status' => 'publish',
'posts_per_page' => 10,
'orderby' => 'date', 'order' => 'DESC',
'tax_query' => array( array( 'taxonomy' => 'genre', 'field' => 'slug', 'terms' => 'roman' ) ),
'meta_query' => array( array( 'key' => 'wpr_prix', 'value' => 20, 'compare' => '<=', 'type' => 'NUMERIC' ) ),
'no_found_rows' => true, // si pas de pagination
'fields' => 'ids', // si seulement les IDs
) );
if ( $q->have_posts() ) { while ( $q->have_posts() ) { $q->the_post(); /* … */ } wp_reset_postdata(); }$wpdb (Partie 5.6)
global $wpdb;
$wpdb->get_results( $wpdb->prepare( "SELECT * FROM {$wpdb->posts} WHERE post_status = %s", 'publish' ) );
$wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->posts}" );
$wpdb->insert( $wpdb->prefix.'table', array( 'col' => $v ), array( '%s' ) );
// jamais de concaténation d'entrée utilisateur ; toujours prepare() / formatsMeta, options, transients (Parties 5.7 / 7.4)
get_post_meta( $id, 'cle', true ); update_post_meta( $id, 'cle', $v );
get_option( 'cle', $defaut ); update_option( 'cle', $v );
add_option( 'grosse', $v, '', 'no' );// autoload = 'no'
set_transient( 'cle', $v, HOUR_IN_SECONDS ); get_transient( 'cle' ); // false si absent/expiré
register_post_meta( 'livre', 'wpr_isbn', array( 'type'=>'string','single'=>true,'show_in_rest'=>true ) );CPT & taxonomie (Partie 7.3)
register_post_type( 'livre', array(
'public' => true, 'has_archive' => true, 'show_in_rest' => true,
'supports' => array( 'title','editor','thumbnail','excerpt' ),
'rewrite' => array( 'slug' => 'livres' ),
) );
register_taxonomy( 'genre', array('livre'), array( 'hierarchical'=>true, 'show_in_rest'=>true ) );
// activation : flush_rewrite_rules(); (UNE fois)Enqueue (Partie 6.4)
add_action( 'wp_enqueue_scripts', function () {
wp_enqueue_style( 'h', get_stylesheet_directory_uri().'/main.css', array(), '1.0' );
wp_enqueue_script( 'h', get_stylesheet_directory_uri().'/app.js', array('jquery'), '1.0', true );
wp_localize_script( 'h', 'Data', array( 'rest' => esc_url_raw( rest_url() ), 'nonce' => wp_create_nonce('wp_rest') ) );
} );REST — endpoint custom (Partie 9.3)
add_action( 'rest_api_init', function () {
register_rest_route( 'wpr/v1', '/livres', array(
'methods' => 'GET',
'callback' => 'cb',
'permission_callback' => '__return_true', // ou current_user_can(...)
'args' => array( 'n' => array( 'default'=>10, 'sanitize_callback'=>'absint' ) ),
) );
} );REST — routes utiles (Partie 9.1)
/wp-json/wp/v2/posts?per_page=10&_fields=id,title,slug&_embed
/wp-json/wp/v2/livre?slug=dune # CPT
/wp-json/wc/store/v1/products # WooCommerce (public, front)
X-WP-Total / X-WP-TotalPages # en-têtes de paginationblock.json (Partie 8.2)
{ "apiVersion": 3, "name": "wpr/livre-une", "title": "Livre à la une",
"attributes": { "livreId": { "type": "number" } },
"supports": { "align": ["wide"], "color": { "background": true }, "spacing": { "padding": true } },
"editorScript": "file:./index.js", "render": "file:./render.php" }Bloc — edit/attributs (Partie 8.3)
export default function Edit({ attributes, setAttributes }) {
const bp = useBlockProps();
return <div {...bp}><RichText tagName="h3" value={attributes.titre}
onChange={(titre) => setAttributes({ titre })} /></div>;
}Data store (Partie 8.7)
const livres = useSelect((s) => s(coreStore).getEntityRecords('postType','livre',{per_page:20}), []);
const [meta, setMeta] = useEntityProp('postType','livre','meta'); // meta show_in_rest
await apiFetch({ path: '/wpr/v1/livres' }); // endpoint customWooCommerce (Partie 10)
$p = wc_get_product( $id ); $p->get_price(); $p->set_stock_quantity(5); $p->save();
$o = wc_get_order( $id ); $o->get_total(); $o->update_status('completed');
add_action( 'woocommerce_payment_complete', 'cb' ); // paiement OK
add_action( 'woocommerce_single_product_summary', 'cb', 25 ); // hook de template
// compat HPOS : FeaturesUtil::declare_compatibility('custom_order_tables', __FILE__, true);WP-CLI (Partie 4.3)
wp plugin install woocommerce --activate wp plugin update --all
wp user create bob b@ex.com --role=editor wp option get siteurl
wp db export sauv.sql wp db import sauv.sql
wp search-replace 'https://a.com' 'https://b.com' --dry-run --all-tables
wp cache flush wp rewrite flush wp cron event run --due-now
wp scaffold plugin mon-plugin wp i18n make-pot . languages/x.potDébogage (Partie 4.5) — wp-config.php
define( 'WP_DEBUG', true );
define( 'WP_DEBUG_LOG', true ); // → wp-content/debug.log
define( 'WP_DEBUG_DISPLAY', false );
define( 'SCRIPT_DEBUG', true );
error_log( print_r( $x, true ) ); // logguer une valeurChapitre suivant : Pièges courants & FAQ.