Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

Is there a plugin that supports calling custom functions that you've created?

Like,

page A -- I want to call function x

$(document).ready(function(){
    call_function_x()
});

page B -- I want to call function y

$(document).ready(function(){
    call_function_y()
});

I don't want to write the calls in the main input because of others editing and might delete them by misstake...

This is my current solution but not optimal in my eyes :)

footer.php:

    <?php
        /* Always have wp_footer() just before the closing </body>
         * tag of your theme, or you will break many plugins, which
         * generally use this hook to reference JavaScript files.
         */

        wp_footer();
        $js =  get_post_meta($post->ID, 'javascript', true);
            if ( $js != "" ) {
    ?>


<script type="text/javascript">
    $(document).ready(function(){
    <?php echo $js; ?>
});
<?php } ?>

then I added custom field "javascript" on the pages with their custom functions like this.

function_x(some_variable); function_y(some_var); function_foo(bar);
share|improve this question
    
Do you want to avoid using custom fields as well? –  kidakaka Nov 16 '12 at 12:16
    
@kidakaka yes I would like to but... maybe that's to much to ask for though...! –  Philip Nov 16 '12 at 12:58
add comment

1 Answer

up vote 1 down vote accepted

I would create a custom field containing the function to be called, for example called 'function_to_call'. In the templatefile add the code

$function_to_call = get_post_meta( get_the_ID(), 'function_to_call', true );
if ( $function_to_call != "" ) {
    echo '
          jQuery(document).ready(function($){
              ' . $function_to_call . '()
          });
    ';
}

Doing this only outputs the function if you set one in the Custom Fields. You could also make a list of available Functions to avoid Javascript errors.

share|improve this answer
    
@fish, yeah I did a solution like that but I don't really like it, see my edit. –  Philip Nov 16 '12 at 13:01
    
but maybe that's the easiest and most effective solution ... –  Philip Nov 16 '12 at 13:05
    
you have to store the values somewhere - so the custom field is your best option. maybe you could create a custom metabox not visible for the editors, containing all the usable functions. –  fischi Nov 16 '12 at 13:58
    
Yeah, as you say, I need to store them somewhere and I think custom fields will do it for now. Thanks! –  Philip Nov 16 '12 at 14:04
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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