0

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?

1 Answer 1

0

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.

3
  • 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, 2013 at 20:44
  • You can hide all this in a function or class method. I will update my answer with an example.
    – fuxia
    Jan 15, 2013 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, 2013 at 21:26

Your Answer

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

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