• Resolved andrewbecks

    (@andrewbecks)


    Hello everyone! I’ve tried to piece together what I’m looking to do, but I’m not finding the detail in the WP documentation or from any Google/Stack Overflow searches that is helping me achieve my end goal, so I’m turning here for some guidance.

    Here’s the deal: I have the PHP below in my functions.php, which I use to load an alternate single.php when the querystring mode=test is present in the URL.

    function alt_add_query_vars($vars) { return array(‘mode’) + $vars; }
    add_filter(‘query_vars’, ‘alt_add_query_vars’);

    function alt_template($template) {
    global $wp;
    if ( ($wp->query_vars[‘mode’]==’test’) ) { return dirname( __FILE__ ) . ‘/single-test.php’; }
    else { return $template; }
    }
    add_filter(‘single_template’, ‘alt_template’);

    I’d like to adapt it so that it will ALSO load the alternate template if a [test] shortcode is present in the post (the shortcode is already registered in functions.php and works fine). I attempted to add an OR condition to the if, looking for either the querystring OR the shortcode, but it is not proving successful:

    strstr( $post->post_content, '[test' )

    If anyone has done something similar or has thoughts on how to achieve this, I’d be very interested in learning.

Viewing 1 replies (of 1 total)
  • Thread Starter andrewbecks

    (@andrewbecks)

    As is pretty much always how it goes, I figure it out moments after I ask for help. Anyway, in case anyone is interested, here’s my solution:

    Start with an additional function inside function.php

    function has_custom_shortcode($shortcode = '') {
        $post_to_check = get_post(get_the_ID());
        $found = false;
        if (!$shortcode) { return $found; }
        if ( stripos($post_to_check->post_content, '[' . $shortcode) !== false ) { $found = true; }
        return $found;
    }

    (Adapted from something I saw here.)

    Then, I was able to simply leverage the function in my OR condition:

    if (has_custom_shortcode('test') === true)

    That’s all it takes.

Viewing 1 replies (of 1 total)

The topic ‘Conditional template based on shortcode’ is closed to new replies.