WORDPRESS, inject custom-fields into a custom HTML widget from a plugin


Though recommended, time and time again. I did not want to register a new widget, or muck about with a child-theme. Just want to inject some data from a posts custom-field into any custom HTML widget I wanted. I know, it would have been easier with a javascript request followed by an append, but I have this little plugin that I toy with you see, and would like to implement that ability there.

Could not find what I was looking for, when hunting for examples. Perhaps not asking the right questions, the likely reason, since my Wordpress-fu leaves a lot to be desired. Eventually came up with the following.

Embed an element in the custom html widget using your preferred identifier. In my case:

<span id="my-custom-post-field-1"></span>

Add a new filter to your plugins library, in my case it's a class:

add_filter('widget_text', array($this,'mycustompostthing'),10,3);

Add a new function to check the text for that identifier, then inject at will.


    function mycustompostthing( $text,$inst,$args ) {
        global $post;
        if( strpos($text, 'my-custom-post-field-1')){
            $upsell = $this->get_upsell ( $post, 'my-custom-post-field-1' );
            if($upsell){
                $text = $upsell .'<div class="newline"></div>'. $text;
            }          
        }
        return $text;
    }

And that's it. Not the best solution, but gets the job done.
Dump located here: https://github.com/dreaddymck/dump/blob/master/wordpress-inject-custom-fields-example

Popular posts from this blog

AH00534: apache2: Configuration error: No MPM loaded