WordPress – how to retrieve the ID from a given meta

Code sur écran d'ordinateur

With WordPress, it is common to use the get_post_meta($post, $meta_key) method in order to retrieve the value of a given meta. However for the ID, there is no ready-made method. The best solution I’ve found so far: $mid = $wpdb->get_var( $wpdb->prepare(“SELECT meta_id FROM $wpdb->postmeta WHERE post_id = %d AND meta_key = %s”, $post, $meta_key) );

Categories PHP

PHP – Protection of special characters of regular expressions

Code sur écran d'ordinateur

If you want to use a regular expression to, for example, search for a word in a paragraph, it is important to protect your variable. To do this, just use the following function: string preg_quote ( string $str [, string $delimiter = NULL ] ) For example: foreach ($aRequest[‘keywords’] as $sKeyword) { $sKeyword = preg_quote($sKeyword); … Read more

Categories PHP

PHP – mb_strlen: get the real length of a string

MacBook avec code sur un bureau

A lot of code uses strlen to get the size of a string. The problem: strlen returns the number of bytes, not the number of characters. As soon as a string contains accented letters or emojis, the result is wrong. The problem with strlen In UTF-8, a character such as “é” takes two bytes, so … Read more

Categories PHP

PHP – Replace accented characters with their unaccented equivalents

MacBook avec code sur un bureau

A small function to replace accented characters with their unaccented equivalent. function normalize_str($str) { $invalid = array(‘Š’=>’S’, ‘š’=>’s’, ‘Đ’=>’Dj’, ‘đ’=>’dj’, ‘Ž’=>’Z’, ‘ž’=>’z’, ‘Č’=>’C’, ‘č’=>’c’, ‘Ć’=>’C’, ‘ć’=>’c’, ‘À’=>’A’, ‘Á’=>’A’, ‘Â’=>’A’, ‘Ã’=>’A’, ‘Ä’=>’AE’, ‘Å’=>’A’, ‘Æ’=>’A’, ‘Ç’=>’C’, ‘È’=>’E’, ‘É’=>’E’, ‘Ê’=>’E’, ‘Ë’=>’E’, ‘Ì’=>’I’, ‘Í’=>’I’, ‘Î’=>’I’, ‘Ï’=>’I’, ‘Ñ’=>’N’, ‘Ò’=>’O’, ‘Ó’=>’O’, ‘Ô’=>’O’, ‘Õ’=>’O’, ‘Ö’=>’OE’, ‘Ø’=>’O’, ‘Ù’=>’U’, ‘Ú’=>’U’, ‘Û’=>’U’, ‘Ü’=>’UE’, ‘Ý’=>’Y’, ‘Þ’=>’B’, … Read more

Categories PHP

PHP – CURL Authentication

MacBook avec code sur un bureau

To authenticate a cURL request in PHP, the option to know is CURLOPT_USERPWD. It sends a username / password pair in the user:password format. Basic authentication $ch = curl_init(‘https://example.com/api’); curl_setopt($ch, CURLOPT_USERPWD, ‘user:password’); curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5); $response = curl_exec($ch); if ($response === false) { throw new RuntimeException(curl_error($ch)); } curl_close($ch); Setting … Read more

Categories PHP