Search code examples
phpjquerywordpresscustom-post-typegenesis

Troubles with executing script in custom post type archive page


I have a custom post type archive page where I'd like to execute a specific script for the page. The script is loaded in the page with this function (in function.php):

function cpt_archive_enqueue_script() {
 if (is_post_type_archive('cpt-slug')) {
  wp_enqueue_script( 'cpt-archive-script', get_stylesheet_directory_uri() . '/js/cpt-archive-script.js', array( 'jquery' ), '1.0.0', true );
  };
}

add_action ('wp_enqueue_scripts', 'cpt_archive_enqueue_script'); 

As I can see with page inspector, the page loads the script but the loaded script is not executed ( the same script work f.e. if loaded in a category page).

Have anyone a suggestion to fix this? Thanks!

If can help here is the loaded script (it is a really simple script that opens the article content if the title is clicked).

jQuery(document).ready(function($) {

 $('article.post').each(function() {
   var $dropdown = $(this);

   $("div.entry-title", $dropdown).click(function(e) {
     e.preventDefault();
     $div = $("div.entry-content", $dropdown);
     $div.toggle();
     $("div.entry-content").not($div).hide();
     return false;
   });

});

 $('html').click(function(){
   $("div.entry-content").hide();
 });

});

Solution

  • Try with below code it must be work on each page.

    add_action('wp_head','callfunctioneverywhere');
    function callfunctioneverywhere()
    {
      echo '<script defer src="'.get_stylesheet_directory_uri() .'/js/cpt-archive-script.js" ></script>';
    }