1

Hi I am building a jquery accordion which works fine on my site.

However I am now trying to introduce conditionals to only enable it on posts and pages, however it doesn't work, it seems the conditionals don't detect that it's a page.

The code is here: http://pastebin.com/9anYAKa1

function faq_start_shortcode( $atts, $content = null ) {
   return '<div id="accordion">';
}

function faq_question_shortcode( $atts, $content = null ) {
   return '<div class="accordionButton">' . $content . '</div>';
}

function faq_answer_shortcode( $atts, $content = null ) {
   return '<div class="accordionContent">' . $content . '</div>';
}

function faq_end_shortcode( $atts, $content = null ) {
   return '</div>';
}


if ( is_single() || is_page() ) {
add_shortcode('faqstart', 'faq_start_shortcode');
add_shortcode('question', 'faq_question_shortcode');
add_shortcode('answer', 'faq_answer_shortcode');
add_shortcode('faqend', 'faq_end_shortcode');
}
  • Can you please post the code in your question, both for posterity and for those who (ahem) might not have access to Pastebin? – Chip Bennett May 7 '12 at 14:10
  • ok pasted it in question. – urok93 May 7 '12 at 14:13
5

The problem is that you're wrapping your add_action() calls inside of the conditionals, but at the point at which those add_action() calls are executed, neither the query nor the query conditionals are available yet.

Solution: put the conditionals inside the callbacks:

function faq_start_shortcode( $atts, $content = null ) {
    if ( is_single() || is_page() ) {
        return '<div id="accordion">';
    }
}

function faq_question_shortcode( $atts, $content = null ) {
    if ( is_single() || is_page() ) {
        return '<div class="accordionButton">' . $content . '</div>';
    }
}

function faq_answer_shortcode( $atts, $content = null ) {
    if ( is_single() || is_page() ) {
        return '<div class="accordionContent">' . $content . '</div>';
    }
}

function faq_end_shortcode( $atts, $content = null ) {
    if ( is_single() || is_page() ) {
        return '</div>';
    }
}


add_shortcode('faqstart', 'faq_start_shortcode');
add_shortcode('question', 'faq_question_shortcode');
add_shortcode('answer', 'faq_answer_shortcode');
add_shortcode('faqend', 'faq_end_shortcode');

(p.s. you can use is_singular() as a shorthand for ( is_single() || is_page() ).

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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