0

I am trying to pass content to the 'google_dfp_ad_slot' filter. Can this be done within a shortcode funcion?

/**
     * Shortcode function to dynamically add google dfp ads to inline content and widgets
     *
     * [fopconnect_ad is_page="true" page="about"]
     *   {JS}googletag.defineSlot('/6111408/FOPC_All_LeaderBoard_728x90', [728, 90], 'div-gpt-ad-1398288352265-0').addService(googletag.pubads());{/JS}
     *   {HTML}<div id='div-gpt-ad-1342652501811-0' style='width:160px; height:600px;'><script type='text/javascript'>googletag.cmd.push(function() { googletag.display('div-gpt-ad-1342652501811-0'); });</script></div>{/HTML}
     * [/fopconnect_ad]
     *
     * @param  array $atts    shortcode attributes
     * @param  string $content
     * @return sting
     */



    add_shortcode( 'fopconnect_ad', 'fopconnect_ad_func' );
    function fopconnect_ad_func( $atts, $content ) {
        extract( shortcode_atts( array(
            'is_page' => false,
            'page' => '' // can be title, slug, or id
        ), $atts ) );

        preg_match("#\\{JS\\}(.*?)\\{/JS\\}#s", $content, $matches);
        $js = ( !empty( $matches[1] ) ? $matches[1] : '' );

        preg_match("#\\{HTML\\}(.*?)\\{/HTML\\}#s", $content, $matches);
        $content = ( !empty( $matches[1] ) ? $matches[1] : '' );

        if ( $is_page && is_page( explode(', ', $page) ) ) {
            add_filter( 'google_dfp_ad_slot', function( $js ) { return $js; } );
        }

        if ( $is_page && is_page( explode(', ', $page) ) ) {
            return $content;
        }

    }

1 Answer 1

0

It should be possible but you will have to be aware of timing issues. Your shortcode will have to execute before whatever hook you are hooking into.

That is, you can't hook into wp_enqueue_scripts or wp_head but you should be able to hook into later hooks like wp_footer. I suspect that timing is the problem.

3
  • Ok, that makes sense. The output of that filter is located in the wp_head action hook. see below: add_action('wp_head', 'fopconnect_head');function fopconnect_head() { apply_filters('google_dfp_ad_slot', '') } Commented Apr 25, 2014 at 17:03
  • wp_head runs well before your post content. You can't hook into that hook from a shortcode without doing something very server intensive like this
    – s_ha_dum
    Commented Apr 25, 2014 at 17:12
  • Thanks for the example, it appears that code would be called on every request. I've decided to hook into wp_footer. One of the problems I ran into was the $js variable was not scoped correctly. to fix that issue i used the Use keyword: if ( $is_page && is_page( explode(', ', $page) ) ) { add_filter('google_dfp_ad_slot', function() use($js) {return $js;}); } Commented Apr 25, 2014 at 20:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.