Many developers hesitate to call WordPress a PHP development platform. I know what I am talking about, as I developed a platform of my own. PHP platforms normally only provide a skeleton and we need to
With WordPress you get most of this out-of-the-box, with some predefined structures.
Having a flexible administration backend in place makes it easy to concentrate on the things that matter for a project, which is designing a frontend experience.
And especially with the JSON REST API finding its way into the core slowly, you are completely free when it comes to using the stored data in your frontend designs.
Sure that was possible before, just with some more work on our side ;)
But WordPress embracing the „freeing of data“ through JSON, shows us where the ride is going.
There has not been a single project of mine in the past year, that has not used the REST API in some way. And all of this fits perfectly into the new single page app universe.
WordPress interfaces with your javascript framework setup (client side templating, DOM manipulation, data binding, routing …) and frees you from any design handcuffs.
It has become much easier and faster over the past 2 years to say „YES“ to many of my clients wishes.
Its nice to finally see data flow from the server to the client and back that easily.
If you are not exited about this … I am :)
In a current project I am using pages as templates, to load content into specific containers on the website. The website will be using up to 15 different languages.
The main language setup is done through WPML, which creates linked content per language. This helps, as some languages will fail terribly when translating them through a pure gettext setup, as the words setup is often completely different.
But there is always static stuff that can be translated directly through the language files. For that I use a simple shortcode that allows me to keep the native language as a basis in all linked content. Easier to move around, as I can actually read and understand it :)
Call the shortcode from the functions.php
1 |
add_shortcode('quick_trans','do_quick_trans'); |
The shortcode function itself. This loads the language textdomain from the specified location and translates the string.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
function do_quick_trans($atts, $content) { extract(shortcode_atts(array( 'location' => 'PATH_TO_LANG_FILE', 'lang' => 'LANG_TO_USE', 'textdomain' => 'TEXTDOMAIN' ), $atts)); load_textdomain($textdomain, $location.$lang.'.mo'); $content = __($content, $textdomain); return $content; } |
How to use it in your post or page content
1 2 3 4 5 6 7 8 |
German [quick_trans lang="de_DE"]Simple is nice![/quick_trans] Spanish [quick_trans lang="es_ES"]Simple is nice![/quick_trans] Spanish - Latin America / with a special path for the lang file location [quick_trans lang="es_LA" location="/wp-content/..."]Simple is nice![/quick_trans] |
1 2 3 |
header('Cache-Control: no-cache, must-revalidate'); header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); header('Content-type: application/json'); |
The first two headers prevent the browser from caching the response and the third sets the correct MIME type for JSON.
Than just output your JSON data
1 2 3 4 5 6 7 8 9 10 |
$data = array( "fire" => 1, "water" => 0, "earth" => 1, "air" => 1, ); echo json_encode($data); exit; |
Adding Metaboxes in WordPress to your admin areas normally involves 3 steps:
This can be done much easier using Custom Metaboxes and Fields for WordPress, which is a metabox, custom fields and forms library. The library provides a bunch of custom fields and also allows you to add your own easily. Much easier to build new Metaboxes fast!
List of field types included:
Simple example from the CMB2 Github page
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
if ( file_exists( __DIR__ . '/cmb2/init.php' ) ) { require_once __DIR__ . '/cmb2/init.php'; } elseif ( file_exists( __DIR__ . '/CMB2/init.php' ) ) { require_once __DIR__ . '/CMB2/init.php'; } add_action( 'cmb2_init', 'cmb2_sample_metaboxes' ); /** * Define the metabox and field configurations. */ function cmb2_sample_metaboxes() { // Start with an underscore to hide fields from custom fields list $prefix = '_yourprefix_'; /** * Initiate the metabox */ $cmb = new_cmb2_box( array( 'id' => 'test_metabox', 'title' => __( 'Test Metabox', 'cmb2' ), 'object_types' => array( 'page', ), // Post type 'context' => 'normal', 'priority' => 'high', 'show_names' => true, // Show field names on the left // 'cmb_styles' => false, // false to disable the CMB stylesheet // 'closed' => true, // Keep the metabox closed by default ) ); // Regular text field $cmb->add_field( array( 'name' => __( 'Test Text', 'cmb2' ), 'desc' => __( 'field description (optional)', 'cmb2' ), 'id' => $prefix . 'text', 'type' => 'text', 'show_on_cb' => 'cmb2_hide_if_no_cats', // function should return a bool value // 'sanitization_cb' => 'my_custom_sanitization', // custom sanitization callback parameter // 'escape_cb' => 'my_custom_escaping', // custom escaping callback parameter // 'on_front' => false, // Optionally designate a field to wp-admin only // 'repeatable' => true, ) ); } |
The current Google Analytics Dashboard for WordPress integrates no Opt-Out to disable tracking, which is required in Europe. Here is a workaround for that.
Paste this into your theme function.php.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
if ( !is_user_logged_in() && class_exists('GADWP_Manager') ) { add_action('wp_head', 'ga_optout_script', 1); } function ga_optout_script(){ // Read GA Dashboard Settings $options = (array) json_decode(get_option('gadash_options')); // Get GA Dashboard profiles foreach($options['ga_dash_profile_list'] as $profile){ $ga_ua_profile[$profile[1]] = $profile[2]; } // Get active Analytics profile for the current website $active = $options['ga_dash_tableid_jail']; $activeUA = $ga_ua_profile[$active]; // Add opt-out script + active UA echo "<script> var gaProperty = '".$activeUA."'; var disableStr = 'ga-disable-' + gaProperty; if (document.cookie.indexOf(disableStr + '=true') > -1) { window[disableStr] = true; } function gaOptout() { document.cookie = disableStr + '=true; expires=Thu, 31 Dec 2099 23:59:59 UTC; path=/'; window[disableStr] = true; } </script>"; } |
Then add this to your data privacy document:
1 |
<a href="javascript:gaOptout()">Disable Google Analytics tracking</a> |
Will be adding some basic information about using the current Google API with the PHP SDK, this includes Google+, Youtube and other services. For setting up the actual API access see the Google documentation and Google Developer Console
1 2 3 4 5 6 7 8 9 10 11 12 |
require _DIR_TO_AUTOLOAD_SDK_.'/google_sdk/autoload.php'; // Required Information // OAuth 2.0 $google_client_id = _GOOGLE_CLIENT_ID_; $google_client_secret = _GOOGLE_CLIENT_SECRET_; // Public API-Access $google_redirect_url = 'http://yourdomain.com/google_login/?option=do_login'; // API-key for a server application! $google_developer_key = _GOOGLE_DEVELOPER_KEY_; |
1 2 3 4 5 6 7 |
$gClient = new Google_Client(); $gClient->setAccessType('offline'); $gClient->setApplicationName('Application Name'); $gClient->setClientId($google_client_id); $gClient->setClientSecret($google_client_secret); $gClient->setRedirectUri($google_redirect_url); $gClient->setDeveloperKey($google_developer_key); |
1 2 3 4 5 6 7 8 9 10 |
$gClient->setScopes(array( 'https://www.googleapis.com/auth/plus.me', 'https://www.googleapis.com/auth/plus.login', 'https://www.googleapis.com/auth/userinfo.email', 'https://www.googleapis.com/auth/userinfo.profile', 'https://gdata.youtube.com', 'https://www.googleapis.com/auth/youtube.readonly', 'https://www.googleapis.com/auth/youtubepartner' ) ); |
1 |
$plus = new Google_Service_Plus($gClient); |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
session_start(); // A simple check for the login to get a fresh token if($_GET['option'] == "do_login" && empty($_SESSION['google_token'])){ // Check for redirect from Google & Auth if (empty($_GET['code'])) { // Create Auth redirect header('Location: '.$gClient->createAuthUrl()); } else { $gClient->authenticate($_GET['code']); $access_token = $gClient->getAccessToken(); //Store the token in a session or your database for later use $_SESSION['google_token'] = $access_token; } } // You have already logged in if(!empty($_SESSION['google_token'])){ $gClient->setAccessToken($_SESSION['google_token']); } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
// Making sure we have a valid access token if($gClient->getAccessToken()) { try{ // Get your activities $optParams = array('maxResults' => 100); $activities = $plus->activities->listActivities('me', 'public', $optParams); print_r($activities); } } catch (Google_ServiceException $e) { $htmlBody .= sprintf('<p>A service error occurred: <code>%s</code></p>', htmlspecialchars($e->getMessage())); } catch (Google_Exception $e) { $htmlBody .= sprintf('<p>An client error occurred: <code>%s</code></p>', htmlspecialchars($e->getMessage())); } |
Will be adding some basic information about using the current Facebook API with the PHP SDK. Have been updating a lot of old API integrations over the past 2 months and finally solved many badly documented areas of the new API. Will be updating this in the future, as I dive deeper into the latest API changes.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
require_once _DIR_TO_AUTOLOAD.'/facebook_sdk/autoload.php'; use Facebook\FacebookSession; use Facebook\FacebookRedirectLoginHelper; use Facebook\FacebookRequest; use Facebook\FacebookResponse; use Facebook\FacebookSDKException; use Facebook\FacebookRequestException; use Facebook\FacebookAuthorizationException; use Facebook\GraphObject; use Facebook\Entities\AccessToken; use Facebook\HttpClients\FacebookCurlHttpClient; use Facebook\HttpClients\FacebookHttpable; |
Depending on what you want to do with the API, the above needs to be adjusted. Check the Facebook API documentation for more details.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 |
// Session should be started after all files have been included session_start(); // init app with app id and secret FacebookSession::setDefaultApplication( _FB_APP_ID_, _FB_APP_SECRET_ ); // login helper with redirect_uri $helper = new FacebookRedirectLoginHelper( 'http://yourdomain.com/FB_LOGIN/'); // Check for Facebook redirect & retrieve session try { $session = $helper->getSessionFromRedirect(); } catch( FacebookRequestException $ex ) { // When Facebook returns an error } catch( Exception $ex ) { // When validation fails or other local issues } if ( isset( $session ) ) { /* Store the session for later reuse, in this case even getting a long lived session. You should store this in your database. The session can be reused with: $session = new FacebookSession($_SESSION['long']->getToken()); */ if(empty($_SESSION['long'] )){ $_SESSION['long'] = $session->getLongLivedSession(); } // graph api request for user data try { $user_profile = (new FacebookRequest( $session, 'GET', '/me' ))->execute()->getGraphObject(GraphUser::className()); echo "Name: " . $user_profile->getName(); } catch(FacebookRequestException $e) { echo "Exception occured, code: " . $e->getCode(); echo " with message: " . $e->getMessage(); } } else { // show login url if no session available // request special permissions, optional. $params = array( 'manage_pages', 'publish_pages','publish_actions','user_videos' ); echo '<a href="' . $helper->getLoginUrl($params ) . '">Login</a>'; } |
1 |
$average_of_myfoos = array_sum($myfoos) / count($myfoos); |
1 2 |
var sum = myfoos.reduce(function(a, b) { return a + b; }); var avg = sum / myfoos.length; |
As part of our complete network upgrade, portalZINE.TV gets a complete facelift as well. The whole website has been streamlined in preparation for the new season.
htmLawed is a PHP lib that:
Take a look here