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.

Currently, in my plugin Contextual Related Posts, I have an option to automatically add the related posts to the content using

add_filter('the_content,'ald_crp')

I know I can change the priority of the filter by adding a number greater than 10 (which is WordPress default).

add_filter('the_content,'ald_crp',20)

However, what I would like to do is let the user set the priority of the filter from within the options page which I can use and set the_content filter accordingly.

The plugin already has its own settings page.

My plugins doesn't use classes. It uses functions.

Any suggestions / code samples for this?

share|improve this question

1 Answer 1

up vote 0 down vote accepted

Save the priority in your options and pass that value to your add_filter:

add_action( 'template_redirect', 'wpse_81687_prepare_filter' );

function wpse_81687_prepare_filter()
{
    $my_options = get_option( 'my_options' );

    $priority = isset ( $my_options['content_filter_priority'] ) 
        ? $my_options['content_filter_priority'] 
        : 10;

    add_filter( 'the_content', 'ald_crp', $priority );
}

In my example I register the the_content filter during template_redirect because it is not needed earlier. You don’t need the filter in wp-admin or a login page.
You could even use the_post as hook instead of template_redirect. But then … another piece of code might call echo apply_filters('the_content', $some_text ); without calling setup_postdata() before.

share|improve this answer
    
Would my_options be global if I don't enclose the code above within a function and directly put it into the .php file? I've got a tonne of settings stored within my_options and I wouldn't like to make that a global variable since it would add unnecessary overhead on pages the related posts don't display –  Ajay Jan 15 '13 at 20:44
    
You can hide all this in a function or class method. I will update my answer with an example. –  toscho Jan 15 '13 at 21:22
    
Thanks. This sounds good. I'll implement the same. Could you please highlight a bit on the template_redirect action. The Codex page is very bare –  Ajay Jan 15 '13 at 21:26

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.