0

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!

1

I'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;
    });
}
| improve this answer | |
  • Duhh, totally forgot I can do that - Thanks Jacob! – SLE Jan 30 at 4:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.