---
title: "WordPress, bouts de codes utiles"
id: "761"
type: "post"
slug: "wordpress-bouts-de-codes-utiles"
published_at: "2016-03-04T13:28:40+00:00"
modified_at: "2024-06-20T12:27:27+00:00"
url: "https://www.mistersize.com/divers/wordpress-bouts-de-codes-utiles/"
markdown_url: "https://www.mistersize.com/divers/wordpress-bouts-de-codes-utiles.md"
excerpt: "Voici quelques lignes de code pour modifier et améliorer WordPress. C’est un peu en vrac mais ça peut servir."
taxonomy_category:
  - "Divers"
taxonomy_post_tag:
  - "CF7"
  - "WordPress"
---

[j'aime](#partage)
[Commenter](#comments-list)
Taggué dans : [CF7](https://www.mistersize.com/tag/cf7/)
, [WordPress](https://www.mistersize.com/tag/wordpress/)

Voici quelques lignes de code pour modifier et [améliorer WordPress](http://www.mistersize.com/freelance-specialiste-wordpress/)
. C’est un peu en vrac mais ça peut servir.

## Afficher un contenu WordPress différent si l’article est dans une catégorie spécifique

1 – Si vous connaissez l’ID de la catégorie :

Besoin d’un spécialiste **WordPress** pour votre projet ? [Contactez-moi](https://www.mistersize.com/contact/)

```
if ( in_category( '1' ) ){ /* votre code */ }
```

2 – Pour récupérer l’ID de la catégorie grâce à son adresse (slug) :

```
$catslug = 'ma-categorie'; if ( in_category( get_category_by_slug($catslug)->term_id ) ){ /* votre code */ }
```

## Récupérer l’ID d’un article WordPress grâce à son adresse (slug)

```
function get_ID_by_slug($post_slug) {
    $post = get_post_by_path($post_slug);
    if ($post) {
        return $post->ID;
    } else {
        return null;
    }
}
```

## Pour récupérer l’ID d’une page WordPress grâce à son adresse (slug)

```
function get_id_by_slug($page_slug) {
  $page = get_page_by_path($page_slug);
  if ($page) {
    return $page->ID;
  } else {
    return null;
  }
}
```

## Récupérer le Slug (adresse) d’un article wordpress grâce à son ID

```
function get_the_slug( $id=null ){
  if( empty($id) ):
    global $post;
    if( empty($post) )
      return ''; // No global $post var available.
    $id = $post->ID;
  endif;

  $slug = basename( get_permalink($id) );
  return $slug;
}
function the_slug( $id=null ){
  echo apply_filters( 'the_slug', get_the_slug($id) );
}
```

## Fonction WordPress pour récupérer le lien d’une catégorie à partir de son url (slug)

```
function mrsize_cat_link_by_slug($slug = NULL, $class = NULL, $text = NULL){
	$cat_slug 	= $slug;
	$cat_id 	= get_category_by_slug($cat_slug);
	$cat_url 	= get_category_link($cat_id); 
	$cat_name 	= $cat_id->name;
	return ''. $text .' ' . $cat_name . '';
}
```

## Récupérer uniquement le contenu d’un article wordpress à partir de son ID

```
function content_by_id($id){
    $content_post = get_post($id);
    $content = $content_post->post_content;
    $content = apply_filters('the_content', $content);
    $content = str_replace(']]>', ']]>', $content);
    return $content;
}
```

## Modifier le lien « lire la suite » de WordPress

```
// Modify The Read More Link Text
add_filter( 'the_content_more_link', 'modify_read_more_link' );
function modify_read_more_link() {
return 'Lire la suite';
}
```

## Pré-définir le type de permalien de WordPress

```
function reset_permalinks() {
    global $wp_rewrite;
    $wp_rewrite->set_permalink_structure( '/%postname%/' );
}
add_action( 'init', 'reset_permalinks' );
```

## Ajouter une class CSS à la balise body de WordPress

### Pratique pour indiquer que la page n’est pas la page d’accueil :

```
add_filter( 'body_class','not_home_body_classes' );
function not_home_body_classes( $classes ) {

        global $post;
        
        if(is_home() || is_front_page()){
          $homeClass = 'home';
        } else {
          $homeClass = 'nothome';
        }
        
    $classes[] = $homeClass;
     
    return $classes;
     
} 
```

### Pratique pour customiser une page spécifique

Ici, on ajoute le slug de la page aux classes du body :

```
add_filter( 'body_class', 'tomorrow_pagename' );
if( ! function_exists('tomorrow_pagename')){

	function tomorrow_pagename($pagename) {

		if( ! isset($post)) global $post;

		$search_query = get_search_query();

		if( ! isset( $pagename )){
			if( $search_query != '' ){
				$pagename = 'search-results';
			} else {
				$pagename = $post->post_name;
			}
		}

		return $pagename; 
	}

	
	
} // end - if function not exist
```

## Ajouter une colonne avec l’image à la une dans l’administration wordpress

```
/* --- Start : Post Thumbnail in admin --- */
    // Add the posts and pages columns filter. They can both use the same function.
    add_filter('manage_posts_columns', 'tcb_add_post_thumbnail_column', 1);
    add_filter('manage_pages_columns', 'tcb_add_post_thumbnail_column', 1);

    // Add the column
    function tcb_add_post_thumbnail_column($cols){
      $cols['tcb_post_thumb'] = __('Image','sensa');
      return $cols;
    }

    // Hook into the posts an pages column managing. Sharing function callback again.
    add_action('manage_posts_custom_column', 'tcb_display_post_thumbnail_column', 1, 2);
    add_action('manage_pages_custom_column', 'tcb_display_post_thumbnail_column', 1, 2);

    // Grab featured-thumbnail size post thumbnail and display it.
    function tcb_display_post_thumbnail_column($col, $id){
      switch($col){
        case 'tcb_post_thumb':
          if( function_exists('the_post_thumbnail') )
            echo the_post_thumbnail( 'thumb' );
          else
            echo __( 'Not supported in theme','sensa' );
          break;
      }
    }
/* --- End : Post Thumbnail in admin --- */
```

## Sécurité : Bloquer l’admin de wordpress

```
// redirect non admin but allow ajax access
// source : https://codex.wordpress.org/Plugin_API/Action_Reference/admin_init
function restrict_admin() {
  if ( ! current_user_can( 'publish_posts' ) && ( ! defined( 'DOING_AJAX' ) || ! DOING_AJAX ) ) {
    wp_redirect( site_url() ); 
    exit;
  }
}
add_action( 'admin_init', 'restrict_admin', 1 );
```

## Sécurité : se proteger des requetes d’url malfaisantes

```
// Protect wordpress against malicious URL requests
// source : http://wp-snippet.com/protect-wordpress-against-malicious-url-requests/
global $user_ID; if($user_ID) {
    if(!current_user_can('administrator')) {
        if (strlen($_SERVER['REQUEST_URI']) > 255 ||
            stripos($_SERVER['REQUEST_URI'], "eval(") ||
            stripos($_SERVER['REQUEST_URI'], "CONCAT") ||
            stripos($_SERVER['REQUEST_URI'], "UNION+SELECT") ||
            stripos($_SERVER['REQUEST_URI'], "base64")) {
                @header("HTTP/1.1 414 Request-URI Too Long");
                @header("Status: 414 Request-URI Too Long");
                @header("Connection: Close");
                @exit;
        }
    }
}
```

## Optimisation : Booster la rapidité de son site wordpress en préchargeant les pages avec HTML5

```
add_action('wp_head', 'gkp_prefetch');
function gkp_prefetch() {
    ?>
    
    <link rel="prefetch" href="" />
    <link rel="prerender" href="" />
    <link rel="prefetch" href="/css-minify.php" />
    <link rel="prerender" href="/css-minify.php" />
   <?php
}
```

## Optimisation : Compressez le html de WordPress pour un rendu plus rapide

```
// Enable GZIP output compression
if(extension_loaded("zlib") && (ini_get("output_handler") != "ob_gzhandler"))
   add_action('wp', create_function('', '@ob_end_clean();@ini_set("zlib.output_compression", 1);'));

// ob_start = mise en tampon
add_action('get_header', 'gkp_html_minify_start');
function gkp_html_minify_start()  {
    ob_start( 'gkp_html_minyfy_finish' );
}

// Minifier les fichiers HTML d'un site WordPress sans plugin
if (!current_user_can('update_plugins')) { 
	function gkp_html_minyfy_finish( $html )  {

   // Suppression des commentaires HTML, 
   // sauf les commentaires conditionnels pour IE
   $html = preg_replace('/).)*-->/s', '', $html);
 
   // Suppression des espaces vides
   $html = str_replace(array("\r\n", "\r", "\n", "\t"), '', $html);
   while ( stristr($html, '  ')) 
       $html = str_replace('  ', ' ', $html);

   return $html;
	}	
}
```

## Sécuriser les adresses e-mails de WordPress

```
// How to automatically hide email adresses from spambots on your WordPress blog
function security_remove_emails($content) {
    $pattern = '/([a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4})/i';
    $fix = preg_replace_callback($pattern,"security_remove_emails_logic", $content);

    return $fix;
}
function security_remove_emails_logic($result) {
    return antispambot($result[1]);
}
add_filter( 'the_content', 'security_remove_emails', 20 );
add_filter( 'widget_text', 'security_remove_emails', 20 );
```

## Masquer les e-mails avec du javascript

```
// masque emails
function encodeEmail($email, $name = null) {
   $email = preg_replace("/\"/","\\\"",$email);
    if($name == null)
           $name = $email;
   $old = "document.write('$name')";
   $output = "";
   for ($i=0; $i < strlen($old); $i++) {
    $output = $output . '%' . bin2hex(substr($old,$i,1));
    }
   $output = 'eval(unescape(\''.$output.'\'))';
   $output .= 'Il faut javascript activé pour voir l\'email';
   return $output;
}
```

## Retirer les balises Meta de WordPress

```
// Remove meta generator
remove_action('wp_head', 'wp_generator');
```

## Site mobile (responsive), ajouter les balises meta

```
function tomorrow_add_responsive_meta_header() { 
  ?> 
  
  
  
  
  <meta name="apple-mobile-web-app-title" content="">
  
   
  <?php 
} 
add_action( 'wp_head', 'tomorrow_add_responsive_meta_header' );
```

## Ajouter une classe CSS à the_tags()

```
// Ajouter une classe html à chaque tag
add_filter('the_tags', 'add_class_get_the_tag_list');

function add_class_get_the_tag_list($list) {
    $list = str_replace('rel="tag">', 'rel="tag" class="tag">', $list);
    $list = str_replace('', '', $list);
    return $list;
}
```

## Ajouter une Classe CSS au menu wordpress

```
// add class to menu
  function special_nav_class($classes, $item){
          $classes[] = "w menu-item fl fadeInDown wow animated";
       return $classes;
  }
  add_filter('nav_menu_css_class' , 'special_nav_class' , 10 , 2);
```

## Ajouter un meta canonical

```
// canonical
// A copy of rel_canonical but to allow an override on a custom tag
function rel_canonical_with_custom_tag_override()
{
    if( !is_singular() )
        return;

    global $wp_the_query;
    if( !$id = $wp_the_query->get_queried_object_id() )
        return;

    // check whether the current post has content in the "canonical_url" custom field
    $canonical_url = get_post_meta( $id, 'canonical_url', true );
    if( '' != $canonical_url )
    {
        // trailing slash functions copied from http://core.trac.wordpress.org/attachment/ticket/18660/canonical.6.patch
        $link = user_trailingslashit( trailingslashit( $canonical_url ) );
    }
    else
    {
        $link = get_permalink( $id );
    }
    echo "\n";
}
// remove the default WordPress canonical URL function
if( function_exists( 'rel_canonical' ) )
{
    remove_action( 'wp_head', 'rel_canonical' );
}
// replace the default WordPress canonical URL function with your own
add_action( 'wp_head', 'rel_canonical_with_custom_tag_override' );
```

## Savoir si c’est une sous-page « if(is_subpage()){} »

```
// subpage
function is_subpage( $page = null )
{
    global $post;
    // is this even a page?
    if ( ! is_page() )
        return false;
    // does it have a parent?
    if ( ! isset( $post->post_parent ) OR $post->post_parent post_parent == $page )
                return true;
        } else if ( is_string( $page ) ) {
            // get ancestors
            $parent = get_ancestors( $post->ID, 'page' );
            // does it have ancestors?
            if ( empty( $parent ) )
                return false;
            // get the first ancestor
            $parent = get_post( $parent[0] );
            // compare the post_name
            if ( $parent->post_name == $page )
                return true;
        }
        return false;
    }
}
```

## Administration WordPress

### Afficher plus de pages dans votre administration ``` // display number of pages in admin add_filter( 'get_user_metadata', 'pages_per_page_wpse_23503', 10, 4 ); function pages_per_page_wpse_23503( $check, $object_id, $meta_key, $single ) { if( 'edit_page_per_page' == $meta_key ) return 2000; return $check; } ``` ### Masquer la barre d’administration sauf pour les administrateurs ``` // Disable Admin Bar for All Users Except for Administrators add_action('after_setup_theme', 'remove_admin_bar'); function remove_admin_bar() { if (!current_user_can('administrator') && !is_admin()) { show_admin_bar(false); } } ``` ### Modifier le texte dans le footer de l’admin ``` // custom footer text function remove_footer_admin () { echo 'Une question, besoin d\'aide ? Contactez thomas'; } add_filter('admin_footer_text', 'remove_footer_admin'); ``` ### Supprimer le lien vers les commentaires dans la barre d’administration WordPress ``` // Disable support for comments and trackbacks in post types function remove_admin_bar_links() { global $wp_admin_bar; $wp_admin_bar->remove_menu('comments'); } add_action( 'wp_before_admin_bar_render', 'remove_admin_bar_links' ); ``` ### Ajouter un lien vers dans la barre d’administration WordPress ``` function my_admin_bar_menu() { global $wp_admin_bar; if ( !is_super_admin() || !is_admin_bar_showing() ) return; $wp_admin_bar->add_menu( array( 'id' => 'custom_menu', 'title' => __( 'Page title'), 'href' => FALSE )); $wp_admin_bar->add_menu( array( 'parent' => 'custom_menu', 'title' => __( 'Theme Options'), 'href' => admin_url( 'themes.php?page=options-framework' )) ); } add_action('admin_bar_menu', 'my_admin_bar_menu'); ``` ### Forcer l’affichage en une colonne dans l’administration ``` // force 1 column on dashboard function so_screen_layout_columns( $columns ) { $columns['dashboard'] = 1; return $columns; } add_filter( 'screen_layout_columns', 'so_screen_layout_columns' ); function so_screen_layout_dashboard() { return 1; } add_filter( 'get_user_option_screen_layout_dashboard', 'so_screen_layout_dashboard' ); ``` ### Désactiver les notifications de mise à jour ``` // remove upgrade notification function my_remove_update_notifications() { global $current_user; get_currentuserinfo(); if($current_user->user_login != 'admin'){ add_action( 'admin_notices', 'update_nag', 3 ); add_action( 'init', create_function( '$a', "remove_action( 'init', 'wp_version_check' );" ), 2 ); add_filter( 'pre_option_update_core', create_function( '$a', "return null;" ) ); } } ``` ### Definir la couleur par défaut de l’admin WordPress ``` function set_default_admin_color($user_id) { $args = array( 'ID' => $user_id, 'admin_color' => 'sunrise' ); wp_update_user( $args ); } add_action('user_register', 'set_default_admin_color'); ``` ### Changer l’ordre du menu dans l’administration ``` // Move Pages above Media function mrsize_change_menu_order( $menu_order ) { return array( 'index.php', 'edit.php', 'edit.php?post_type=page', 'edit.php?post_type=mini_slide', 'edit.php?post_type=home_blocs', 'upload.php', ); } add_filter( 'custom_menu_order', '__return_true' ); add_filter( 'menu_order', 'mrsize_change_menu_order' ); ``` ### Retirer des menus ou enlever des sous-menus dans l’administration WordPress ``` function mrsize_remove_admin_menus(){ // Check that the built-in WordPress function remove_menu_page() exists in the current installation if ( function_exists('remove_menu_page') ) { remove_submenu_page( 'themes.php', 'widgets.php' ); remove_submenu_page( 'themes.php', 'customize.php' ); remove_submenu_page( 'themes.php', 'theme-editor.php' ); remove_menu_page( 'theme-editor.php' ); remove_submenu_page( 'plugins.php', 'plugin-editor.php' ); } } // Add our function to the admin_menu action add_action('admin_menu', 'mrsize_remove_admin_menus'); ``` ## Recupérer la liste des tags utilisés dans une categorie ``` function get_tags_in_use($category_ID, $type = 'name'){ // Set up the query for our posts $my_posts = new WP_Query(array( 'cat' => $category_ID, // Your category id 'posts_per_page' => -1 // All posts from that category )); // Initialize our tag arrays $tags_by_id = array(); $tags_by_name = array(); $tags_by_slug = array(); // If there are posts in this category, loop through them if ($my_posts->have_posts()): while ($my_posts->have_posts()): $my_posts->the_post(); // Get all tags of current post $post_tags = wp_get_post_tags($my_posts->post->ID); // Loop through each tag foreach ($post_tags as $tag): // Set up our tags by id, name, and/or slug $tag_id = $tag->term_id; $tag_name = $tag->name; $tag_slug = $tag->slug; // Push each tag into our main array if not already in it if (!in_array($tag_id, $tags_by_id)) array_push($tags_by_id, $tag_id); if (!in_array($tag_name, $tags_by_name)) array_push($tags_by_name, $tag_name); if (!in_array($tag_slug, $tags_by_slug)) array_push($tags_by_slug, $tag_slug); endforeach; endwhile; endif; // Return value specified if ($type == 'id') return $tags_by_id; if ($type == 'name') return $tags_by_name; if ($type == 'slug') return $tags_by_slug; } ``` ## Créer un nuage de tags, à partir des tags utilisés dans une categorie ``` function tag_cloud_by_category($category_ID){ // Get our tag array $tags = get_tags_in_use($category_ID, 'id'); // Start our output variable echo ''; // Cycle through each tag and set it up foreach ($tags as $tag): // Get our count $term = get_term_by('id', $tag, 'post_tag'); $count = $term->count; // Get tag name $tag_info = get_tag($tag); $tag_name = $tag_info->name; // Get tag link $tag_link = get_tag_link($tag); // Set up our font size based on count $size = 8 + $count; echo ''; echo ''.$tag_name.''; echo ' '; endforeach; echo ''; } ``` ## Ajouter une classe CSS au Excerpt ``` add_filter( "the_excerpt", "add_class_to_excerpt" ); function add_class_to_excerpt( $excerpt ) { return str_replace('<p', '<p class="excerpt"', $excerpt); } ``` ## Un excerpt personnalisé ``` // custom excerpt 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); $content = apply_filters('the_content', $content); $content = str_replace(']]>', ']]>', $content); return $content; } ``` ## Fonction de base WordPress : ajouter un textdomain

Utile pour rendre un site traduisible

```
add_action('after_setup_theme', 'my_theme_setup');
function my_theme_setup(){
    load_theme_textdomain('sensa', get_template_directory() . '/languages');
}
```

## Changer le permalien des auteurs WordPress

```
if ( ! function_exists('change_author_permalinks')){
  add_action('init','change_author_permalinks');  
  function change_author_permalinks()  
  {  
      global $wp_rewrite;  
      $wp_rewrite->author_base = 'u'; // Change 'member' to be the base URL you wish to use  
      $wp_rewrite->author_structure = '/' . $wp_rewrite->author_base. '/%author%';  
  }  
}
```

## Retirer les styles par defaut de wp-caption

```
add_shortcode('wp_caption', 'fixed_img_caption_shortcode');
add_shortcode('caption', 'fixed_img_caption_shortcode');
function fixed_img_caption_shortcode($attr, $content = null) {
	if ( ! isset( $attr['caption'] ) ) {
		if ( preg_match( '#((?:]+>\s*)?]+>(?:\s*)?)(.*)#is', $content, $matches ) ) {
			$content = $matches[1];
			$attr['caption'] = trim( $matches[2] );
		}
	}
	$output = apply_filters('img_caption_shortcode', '', $attr, $content);
	if ( $output != '' )
		return $output;
	extract(shortcode_atts(array(
		'id'	=> '',
		'align'	=> 'alignnone',
		'width'	=> '',
		'caption' => ''
	), $attr));
	if ( 1 > (int) $width || empty($caption) )
		return $content;
	if ( $id ) $id = 'id="' . esc_attr($id) . '" ';
	return '' . do_shortcode( $content ) . '' . $caption . '';
}
```

## Ajouter automatiquement target= »_blank » aux liens externes sur WordPress

```
function wpi_linktarget($content)
  {
    return preg_replace_callback('/]+/', 'wpi_linktarget_callback', $content);
  }
 
function wpi_linktarget_callback($matches)
  {
    $link = $matches[0];
    $site_link = get_bloginfo('url');

      if (strpos($link, 'target') === false)
      {
        $link = preg_replace("%(href=\S(?!$site_link))%i", 'target="_blank" $1', $link);
      }
    elseif (preg_match("%href=\S(?!$site_link)%i", $link))
      {
        $link = preg_replace('/target=S(?!_blank)\S*/i', 'target="_blank"', $link);
      }
    return $link;
  }
add_filter('the_content', 'wpi_linktarget');
```

## Inscrire automatiquement un nouvel e-mail dans une liste Wysija (Mailpoet) à l’envoi d’un e-mail avec CF7 (Contact Form 7)

```
function wysija_contactform7_subscribe($cfdata) {

        $formdata = $cfdata->posted_data;

        /* if you use different name/id attribute for CF7 - please change 'your-name' and 'your-email'*/

        $user_name = $formdata['your-name'];
        $user_email = $formdata['your-email'];

        /* change this according to your user list id you want this user to subscribe */

        $listID = array( '1', '3' );
        $userData=array(
            'email'     =>  $user_email,
            'firstname' =>  $user_name,
      'birth_date' =>  $birth_date
        );

        $data=array(
            'user'      =>  $userData,
            'user_list' =>  array( 'list_ids'=> $listID )
        );

        $userHelper=&WYSIJA::get('user','helper');
        $userHelper->addSubscriber($data);
    }

    add_action('wpcf7_mail_sent', 'wysija_contactform7_subscribe', 1);
```
