Pregunta

I am attempting to call a template part via a shortcode. Ive read all about how to do this over and over on this site and yet after having tried a number of things still am unable to call a simple php echo time string. The file name is test-one.php .Here is what I've tried:

function test_2( $attr ) {
    ob_start();
    get_template_part( 'test', 'one' );
    return ob_get_clean();
}

add_shortcode('test2', 'test_2');

function test_2( $attr ) {
    ob_start();
    get_template_part( 'test-one' );
    return ob_get_clean();
}
add_shortcode('test2', 'test_2');

function test_2( $attr ) {
    ob_start();
    get_template_part( 'wp-content/themes/theme-name/template-parts/test-one' );
    return ob_get_clean();
}

add_shortcode('test2', 'test_2');

Template part code is

<?php

echo "Current as of <br>  ".date("m-d-Y h:i:sa");

Seems like it should work, no? Where am I going wrong?

¿Fue útil?

Solución

The get_template_part() function doesn't assume any directory name, you have to explicitly supply it. It's also relative to the active theme directory. So in many of your examples it was looking for the template in the root of your active theme. The correct format would be:

get_template_part( 'template-parts/test-one' );

If you wanted to, you could rename the folder to inc or includes - it's arbitrary. You just need to reflect this change in the function call.


On a side note, WordPress does allow you to pass a 2nd parameter and will look for files joined by a dash. For example, this will also work:

get_template_part( 'template-parts/test', 'one' );

The benefit of this is it allows you to have multiple "types" of a specific part. You may have a content-post.php file to output your post content and a content-page.php to output your page content. Then in your theme you could call your template by:

get_template_part( 'template-parts/content', $post->post_type );

Just allows it to be a bit more dynamic.


Another side note. Any time you have trouble with these kinds of functions you can always use:

add_action( 'init', function() {
    $template = locate_template( $template_string_here );
    printf( '<pre>%s</pre>', print_r( $template, 1 ) );
    die( 'end' );
} );

This will output the template path WordPress is trying to access the template by.

Licenciado bajo: CC-BY-SA con atribución
scroll top