¿Plantillas de tipo de publicación personalizadas de la carpeta de complementos?

48

Me gustaría ofrecer mi tipo de publicación personalizada como un complemento, para que la gente pueda usarlo sin tocar su carpeta de temas. Pero las plantillas de tipo de publicación personalizadas, como single-movies.php, residen en la carpeta del tema. ¿Hay alguna forma de que WP compruebe si hay un solo-movies.php en la carpeta del complemento? ¿Enganchar una función en la Jerarquía de archivadores ? O get_template_directory (); ?

    
pregunta nathanbweb 16.05.2011 - 15:16

4 respuestas

79

Puedes usar single_template filter hook.

/* Filter the single_template with our custom function*/
add_filter('single_template', 'my_custom_template');

function my_custom_template($single) {

    global $post;

    /* Checks for single template by post type */
    if ( $post->post_type == 'POST TYPE NAME' ) {
        if ( file_exists( PLUGIN_PATH . '/Custom_File.php' ) ) {
            return PLUGIN_PATH . '/Custom_File.php';
        }
    }

    return $single;

}
    
respondido por el Bainternet 16.05.2011 - 15:41
15

Respuesta actualizada

Versión más limpia y más corta.

function load_movie_template($template) {
    global $post;

    if ($post->post_type == "movie" && $template !== locate_template(array("single-movie.php"))){
        /* This is a "movie" post 
         * AND a 'single movie template' is not found on 
         * theme or child theme directories, so load it 
         * from our plugin directory
         */
        return plugin_dir_path( __FILE__ ) . "single-movie.php";
    }

    return $template;
}

add_filter('single_template', 'load_movie_template');

Respuesta anterior

Se agregó una verificación para una plantilla específica de tipo de publicación personalizada en la carpeta del tema para @Brainternet answer.

function load_cpt_template($template) {
    global $post;

    // Is this a "my-custom-post-type" post?
    if ($post->post_type == "my-custom-post-type"){

        //Your plugin path 
        $plugin_path = plugin_dir_path( __FILE__ );

        // The name of custom post type single template
        $template_name = 'single-my-custom-post-type.php';

        // A specific single template for my custom post type exists in theme folder? Or it also doesn't exist in my plugin?
        if($template === get_stylesheet_directory() . '/' . $template_name
            || !file_exists($plugin_path . $template_name)) {

            //Then return "single.php" or "single-my-custom-post-type.php" from theme directory.
            return $template;
        }

        // If not, return my plugin custom post type template.
        return $plugin_path . $template_name;
    }

    //This is not my custom post type, do nothing with $template
    return $template;
}
add_filter('single_template', 'load_cpt_template');

Ahora puede permitir que los usuarios del complemento copien la plantilla de su complemento a su tema para anularlo.

Con este ejemplo, las plantillas deben estar en el directorio raíz del complemento y del tema.

    
respondido por el campsjos 15.01.2016 - 10:45
2

Me gustaría señalar que cuando está utilizando el método de filtro para esto, es extremadamente importante priorizar el filtro de la siguiente manera:

add_filter('single_template', 'my_custom_template', 99);

Si no hace esto, a veces WP intentará volver a verificar después de este filtro. Me estaba sacando el pelo debido a esto por unas 2 horas.

    
respondido por el RBizzle 14.12.2016 - 17:33
-2

Lo anterior es una gran respuesta, pero la comprobación de la var $ single permite que la plantilla anule una plantilla si el tema es el tema / niño.

/* Filter the single_template with our custom function*/
add_filter('single_template', 'your_cpt_custom_template');

function your_cpt_custom_template( $single ) {
    global $wp_query, $post;
    /* Checks for single template by post type */
    if ( !$single && $post->post_type == 'cpt' ) {
        if( file_exists( plugin_dir_path( __FILE__ ) . 'single-cpt.php' ) )
            return plugin_dir_path( __FILE__ ) . 'single-cpt.php';
    }
    return $single;
}
    
respondido por el DigitalDesignDj 19.10.2015 - 18:47

Lea otras preguntas en las etiquetas