0

I have a personal website which uses WordPress. for same changes on the theme, I can add manually codes on single.php. Or I can write a hook for it. for example, I want to add content on a specific single.php line.

// I made a action
function after_p(){
    do_action('after_p');
}

and then put it on single.php

             <?php after_p();?>

then I add some line and PHP files with add action on function.php

// Download Box
if (!function_exists('downloadbox')) :
    {
        function downloadbox()
        {
            if (function_exists('get_field'){
                 include('downloadbox.php');
            }
        }
    }
endif;
 add_action( 'after_p', 'tc_downloadbox' );

// adv
if (!function_exists('my_adv')) :
    {
        function my_adv()
        {
            echo '<div id="java-script-advs"></div>';
        }
    }
endif;
add_action( 'after_p', 'my_adv' );

As you guess I am a beginner I have a doubt this way is current? I mean does use the unnecessary hook have effects on page loading? because on my case I can simply add include('downloadbox.php') on single.php(on the line what I want). at the same for echo '<div id="java-script-advs"></div>';

3
  • 1
    The difference is that hooks allow third parties to hook into your code. I guess less lines is generally more efficient if you’re basically looking to do the same thing with both methods. Commented Dec 2, 2020 at 16:19
  • 1
    PHP runs on the server so you haven't added additional HTTP requests, extra DB queries or anything that would slow your site down a measurable amount. Less code is always better, however. A simpler approach would replace the do_action() call with a direct function call to dj_after_p() that called for the include file and echo'd the .java-script-advs div.
    – jdm2112
    Commented Dec 3, 2020 at 3:10
  • Instead of using after_p() which runs do_action('after_p'), you could just do <?php do_action('after_p');?>. Commented Jan 7 at 3:30

1 Answer 1

0

The cost of those hooks themselves is negligble and statistically insignificant. It would take great effort to measure such a change in performance, and would not take up more than a millionth of the total runtime. Unused hooks are not a performance concern.

The real concern here is that unnecessary complexity has been added that will show in the future as technical debt. I also notice you've wrapped all your functions in {} then again in a function exists check, both of which aren't necessary

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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