Circumventing ACF’s get_field issue in wordpress functions.php

Technical topic ahoy!

But seriously, this issue has been bugging me all day. I’m using ACF Pro so I’m not sure if this issue also applies to the free version or not, but hey, I’m gonna lay it out anyway.

 

THE REQUIREMENT

I’d created a simple little checkbox in the options page of a WordPress installation so that, if checked as True, I would be able to display a second custom options page in the Dashboard menu. It was for a multisite installation where some sub-sites needed a special options page and some did not.

So far so simple? Not quite. Turns out that trying to use Advanced Custom Field’s native function to retrieve field values, ‘get_field()‘, wasn’t going to work in functions.php. At least, not in the way I wanted.

 

THE INITIAL SETUP

To add the options page, I call the following function inside my init class:

public static function add_options_page()
    {
        if( function_exists('acf_add_my_custom_options_page') ) {
            acf_add_options_page(array(
                'page_title' => 'Custom Options',
                'menu_title' => 'Custom Options',
                'menu_slug' => 'custom-options',
                'capability' => 'edit_posts',
                'redirect' => false
            ));
        }
    }

But, to ensure it only comes up for subsites that have the checkbox selected, I have to do an extra check. Initially, I had something that seems legit and like it should work:

if ( get_field('display_custom_options_page', 'options') == 1 ) {
    self::add_options_page();
    //we use self:: to reference the init class it's within
}

Simple. If the field equals true, call the function that adds the options page.

But this didn’t work. Or rather, it did display the new options page, however the checkbox on the first options page disappeared from view every time get_field was used in functions.php.

So wait, that means every time I decide a subsite needs to have this extra options page, my opportunity to reverse the decision is taken away? Bad user design, no thank you!

 

THE REASON

After some hunting around online, it turns out that ACF’s get_field() function doesn’t play too nicely with WordPress’s init() function if you want to use it before admin headers are set. It has to be called after init().

I could add it later on, sure, but while I could now retrieve the field, going on to add the custom options page still needed to be done in init.

 

THE FIRST (MESSY) SOLUTION

At first I just thought, well, can I just include the custom options page as normal, without the checkbox conditional, and then hide it after initialisation?

So I had:

class MyClass {
    public static function init()
    {
        self::add_options_page();
    }

    public static function add_options_page()
    {
        if( function_exists('acf_add_my_custom_options_page') ) {
            acf_add_options_page(array(
                'page_title' => 'Custom Options',
                'menu_title' => 'Custom Options',
                'menu_slug' => 'custom-options',
                'capability' => 'edit_posts',
                'redirect' => false
            ));
        }
    }
}
MyClass::init();

$is_custom = get_field('display_custom_options_page', 'options');

if ( $is_custom != 1 ) { // if is_custom ISN'T checked
    // a quick and cute function to remove the specified menu page
    function remove_menus(){
        remove_menu_page( 'custom-options.php' );
    }
    add_action( 'admin_menu', 'remove_menus', 999 );
}

This works. BUT this is roundabout, first adding the page then employing the get_field after to cross-check and then remove the page again.

 

THE FINAL SOLUTION

At this point I thought why not just talk to the database myself instead of using ACF’s functions? Everything ACF creates for options pages gets saved in the wp_options table in wordpress databases, so I simply ended up using the $wpdb class to write an SQL request, and grab the display_custom_options_page field from this, all within init() itself.

Here’s the final code:

class MyClass {

    public static function init()
    {
        self::add_options_page();
    }

    public static function add_options_page()
    {
        // retrieves ocustom options field
        // uses $wpdb sql query rather than ACF get_field

        //set global wpdb, get all from options table
        global $wpdb;
        $results = $wpdb->get_results( "SELECT * FROM $wpdb->options" );

        foreach ($results as $option) {
            // if option has correct name and value, add custom option page
            if ($option->option_name == 'display_custom_options_page' && $option->option_value == 1) {
                if( function_exists('acf_add_options_page') ) {
                    acf_add_options_page(array(
                        'page_title' => 'Custom Options',
                        'menu_title' => 'Custom Options',
                        'menu_slug' => 'custom-options',
                        'capability' => 'edit_posts',
                        'redirect' => false
                    ));
                }
            }
        }

    }
}
MyClass::init();

This is a very specific case – most custom options fields aren’t created as conditionals that govern the inclusion of other options pages. For the vast majority, it makes more sense to just use get_field(). But for those times when something needs to be initialised earlier, just sql it.

The space tech that fell to Earth – GBinSAR!

This is my piece for Accretionary Wedge #60 ‘Momentous Discoveries in Geology’. Enjoy!

GBinSAR? What is this all about?

I am going to talk about a very momentous discovery in geology, the development of a type of radar that helps in monitoring ground movements. It has a long name, you must be warned: ‘Ground-Based Interferometric Synthetic Aperture Radar.’ Or, GBinSAR for short. And it’s a pretty useful bit of kit – it can be used to monitor ground movements of anything from earthquakes and volcanoes, landslides and slope failures, and even glacier movement. So how did this space tech come down to land?

Image of interferometric scattering mapped onto a digital model
An image of the interferometric signal from a GBinSAR setup, mapped onto a digital model for ease of viewing. Reproduced from Leva et al, 2005.

First we need to know about Synthetic Aperture Radar!

Okay, so synthetic aperture radar uses microwaves to get a backscattered image of the environment – this basically means that microwaves bounce off whatever surfaces the instrument is aimed at, and returns a signal which is picked up by the same device. The resolution of a SAR instrument is very high, so it is easy to pick up tiny fluctuations that may suggest something has changed.

Now we can take it down to land! 

So normally SAR instruments operate from satellites in space, but they’re quite wide-range, and sometimes for a particular slope, volcano or glacier you need an even higher, more precise resolution. So we do something very simple – we bring the SAR instrument down to the ground, and set up a couple of stations around the target area, and the radar image can then be made by combining the signal from both instruments. This is exactly what Ground-Based Synthetic Aperture Radar does.

So we have GB SAR, what about the ‘in’?

When you combine two different signals, you’re calculating the interference between them to form the image. This is what’s known as interferometry, and it explains the ‘in’ part of GBinSAR. Interferometry is mega-cool; it was first used on Venus and the Moon! It’s a beautiful example of how space tech has ended up being useful for geohazard mitigation on Earth, so all opposers of blue sky science, take note!

All right, but who invented this stuff?

The original SAR was first conceived back in 1938, by Sir Watson-Watt, and was called the ‘Bedspring Antenna’. SAR technology did not actually come into proper use until 1978 when the SEASAT satellite was first put up.

The movement from space satellites to ground-based inSAR did not happen officially until 1999, when the EU’s Joint Research Centre did some dam experiments and published the first paper on the subject. Since then companies such as Ellegi-LiSA labs in Italy have worked towards creating saleable models. The LiSA model from this lab is currently the most widely used.

Okay, so tell me more about where it’s been used. I want some examples!

GBinSAR is used all over the world to monitor any geological surface that might be likely to start making a run for it. For instance, in Japan it is used to monitor landslides in unstable areas easily affected by typhoon rains, such as the Tottori prefecture, and this has led to some very successful evacuations recently.

On the island volcano of Stromboli, GBinSAR is used to constantly monitor minor changes on the main volcanic debris slope, so that landslide-tsunamis can be mitigated. It’s possibly the best tech to use here, as erecting monitoring equipment on an active debris slope is nigh on impossible, so having this multiple-receiver setup placed around the sides of the slope allows high-resolution data to be captured without causing too much damage to the hardware.

This technology is also used in civil engineering. It’s been used to monitor deformation of dams in Poland, and even structural deformation of bridges!

So this is an awesome piece of tech, and it’s really changed the world of hazard mitigation. I’d definitely say that the idea of converting space-based Synthetic Aperture Radar to a ground-based model is one of the greatest geological revelations ever, because it has helped save lives and provide early warning systems for disasters. Although it’s something that goes by unnoticed most of the time, let’s give some applause to the humble GBinSAR device and its space-age predecessor.


References:

1.) Guido Luzi, ‘Ground Based SAR Interferometry: a Novel Tool for Geoscience’, Geoscience and Remote Sensing New Achievements 2010

2.) Kazuo Ouchi, ‘Recent Trend and Advance of Synthetic Aperture Radar with Selected Topics’, Remote Sensing 5, 2013, pp. 716 – 807

3.) D. Tarchi, H. Rudolf, G. Luzi, L. Chiarantini, P. Coppo, A. J. Sieber, ‘SAR interferometry for structural changes detection: a demonstration on a dam,’ Proceedings of IGARSS’99 Hamburg pp 1522 – 1524

4.) D. Leva, C. Rivolta, I. Binda Rosetti, S, Kuzuoka, T. Mizuno, ‘Using a ground based interferometric synthetic aperture radar (GBinSAR) sensor to monitor a landslide in Japan’, Geoscience and Remote Sensing Symposium, 2005, Volume 6, 2005

5.) Teresa Nolesini, Federico Di Traglia, Chiara Del Ventisette, Sandro Moretti, Nicola Casagli, ‘Deformations and slope instability on Stromboli volcano: Integration of GBinSAR data and analog modelling’, Geomorphology 180 – 181, 2013, pp. 242 – 254

6.) Rafal Kocierz, Przemyslaw Kuras, Tomasz Owerko and Lukasz Ortyl, ‘Assessment of Usefulness of Radar Interferometer for Mesuring Displacements and Deformations of Dams’, Joint International Symposium on Deformation Monitoring, 2011

7.) Stefan Pradelok, P. Kuras, T.Owerko, L. Ortyl, R. Kocierz, O. Sukta, ‘Advantages of radar interferometry for assessment of dynamic deformation of bridge,’ Proceedings of Bridge Maintenance, Safety, Management, Resilience and Sustainability, Sixth International IAMBAS Conference, 2012

Fed up with ads in your Gmail inbox? Solution, thy name is Alternion.

I finally cracked over Google ads earlier this week. It was more the blatant lies than anything. I was looking up pictures of the aurora in a separate Chrome window, after which I returned to my Gmail inbox and proceeded to read a very uninteresting email on car insurance.

A Google ad popped up above my email. ‘See the Aurora now! Only £799!’ The ads had slowly been forcing me towards my tolerance limit over the past few months, and so this time, I decided to click on the ‘Why this ad?’ button next to it. I was taken to a page which firmly stated,

‘You have been shown this ad because it directly relates to the email you were just viewing.’

Oh, I think not. I complained, in full knowledge that one complaint was not going to make the ads stop coming, but nontheless I just wanted to vent my frustration at their lack of transparency.

My tipping point, which led me to choosing another email aggregator entirely, came when I started getting ads enticing me to join the Open University – while I was opening emails informing me of my recent Open University exam results.

I did some research, and am now happy, for I have found… ALTERNION.

Alternion is an alternative email and social network aggregator. God, I love aggregators. I admit I was actually using Gmail as an aggregator for my other email accounts, it’s much handier than logging in to each separate site.

So far I have only used Alternion to collate my email accounts together in one place, so I can’t comment on how it handles the social media side of things. But as for email, it does the job well, the interface is slick, and best of all THERE ARE NO ADVERTS! It’s all kinds of sweet. I’m actually able to concentrate on my emails properly again, without distraction.

Alternion automatically connects your accounts via IMAP, so you don’t lost email data on the original servers. This is based on my experience adding a couple of Gmail and Hotmail accounts though, so double-check it’s IMAP if and when you do it.

My only criticism of Alternion so far is that the website is not responsive – as a huge responsive design advocate, I like to be able to fluidly change the sizes of the browser windows I’m working in, I like to access my accounts on the go, via smartphone or tablet, I like to have maximum accessibility. There’s a very good reason why Alternion cannot do this yet – it is a very young project and is only in beta at the moment. I am very interested in seeing what comes next for it!

In closing, email providers should have more discretion when deciding to advertise. The algorithms should avoid certain triggering things, some obvious ones are cancer, terminal illness, death. Basically, algorithms determining which ads to show should always include a human factor, an emotive factor, otherwise they are doomed to fail, like the Facebook deceased friend recommendations debacle.