最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How to render an element, that was saved as a template, using a hook?

programmeradmin3浏览0评论

My goal is to render one identical element on every page. At the moment this element is manually added to 50+ pages. I saved it as a template named 'reusable' and then i want to call it from functions.php using a hook. Is that possible (is this a valid use case) and if so, how? My code, at the very end of functions.php, would look like:

add_action('get_footer', 'render_reusable');
function render_reusable() {
    return how_can_i_load_template_component_named('reusable');
}

My goal is to render one identical element on every page. At the moment this element is manually added to 50+ pages. I saved it as a template named 'reusable' and then i want to call it from functions.php using a hook. Is that possible (is this a valid use case) and if so, how? My code, at the very end of functions.php, would look like:

add_action('get_footer', 'render_reusable');
function render_reusable() {
    return how_can_i_load_template_component_named('reusable');
}
Share Improve this question edited Feb 1, 2020 at 3:00 VilleLipponen asked Feb 1, 2020 at 2:55 VilleLipponenVilleLipponen 1033 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 1

You can create a template tag in your functions.php file like so:

if ( ! function_exists( 'mytheme_reusable' ) ) :
     function mytheme_reusable() { 
           //put your HTML or whatever code you need here
     }
endif;

You can then simply apply the template tag in any template exactly where you need it:

<?php mytheme_reusable(); ?>

Alternatively you can also then apply it via add_action, like so:

add_action( 'wp_footer', 'render_reusable', 1 );
function render_reusable() {
    mytheme_reusable();
}

get_footer(); is intended to include your footer.php content. I set the priority as 1 assuming you wanted it to load before the scripts. Question though, if you're loading this on tons of pages then you may just want to put your template tag directly into the footer.php file and then if necessary write some conditions to prevent it from loading on some pages.

发布评论

评论列表(0)

  1. 暂无评论