So I'm wanting to shorten my code down a bit and I would like some assistance.. How can I shorten the following methods into a single register method? They both have add_action
which is a WordPress hook, so I wasn't aware how that is possible but someone might be able to assist me.
Both functions used separately work great, just wanted to see if there was a more efficient way.
Here are the two methods:
/**
* Register template
*/
public static function register_templates() {
add_filter('single_template', function($single_template) {
global $post;
if ($post->post_type == 'profile') {
$single_template = '/Users/smajlovs/Sites/newsacfoodies/htdocs/wp-content/mu-plugins/sacfoodies/profile-template.php';
}
return $single_template;
});
}
/**
* Register Styles
*/
public static function register_styles()
{
add_action('wp_enqueue_scripts', function() {
global $post;
if (is_page('foodies')) {
wp_register_style('profile-style', content_url() . '/mu-plugins/sacfoodies/styles/profile-card.css');
wp_enqueue_style('profile-style');
}
return;
});
}
Thanks a bunch!
So I'm wanting to shorten my code down a bit and I would like some assistance.. How can I shorten the following methods into a single register method? They both have add_action
which is a WordPress hook, so I wasn't aware how that is possible but someone might be able to assist me.
Both functions used separately work great, just wanted to see if there was a more efficient way.
Here are the two methods:
/**
* Register template
*/
public static function register_templates() {
add_filter('single_template', function($single_template) {
global $post;
if ($post->post_type == 'profile') {
$single_template = '/Users/smajlovs/Sites/newsacfoodies/htdocs/wp-content/mu-plugins/sacfoodies/profile-template.php';
}
return $single_template;
});
}
/**
* Register Styles
*/
public static function register_styles()
{
add_action('wp_enqueue_scripts', function() {
global $post;
if (is_page('foodies')) {
wp_register_style('profile-style', content_url() . '/mu-plugins/sacfoodies/styles/profile-card.css');
wp_enqueue_style('profile-style');
}
return;
});
}
Thanks a bunch!
Share Improve this question asked Jan 30, 2020 at 2:52 user155484user1554841 Answer
Reset to default 0I'm not sure what you're hoping for, but all you can really do is just move the code from one function into the other. global $post
is also not doing anything, so removing that will save you a couple of lines:
/**
* Register template
*/
public static function register_styles_templates() {
add_filter('single_template', function($single_template) {
if ($post->post_type == 'profile') {
$single_template = '/Users/smajlovs/Sites/newsacfoodies/htdocs/wp-content/mu-plugins/sacfoodies/profile-template.php';
}
return $single_template;
});
add_action('wp_enqueue_scripts', function() {
if (is_page('foodies')) {
wp_register_style('profile-style', content_url() . '/mu-plugins/sacfoodies/styles/profile-card.css');
wp_enqueue_style('profile-style');
}
return;
});
}