Correct way to add custom css and JS in child theme

I have custom css and custom JS that works in the customizer but I want to put this in child theme not in customizer. What is the correct way of adding custom CSS and JS in child so it takes precedence? Please advise. Thanks.

x-child/css/cg.css

/* chuparustom */
.chuparustom {
  display: none !important;
}
.logged-in .chuparustom {
  display: block !important;
}

/* khularustom */
.khularustom {
  display: none !important;
}
.cgloggedout .khularustom {
  display: block !important;
}

x-child/js/cg.js

var userisloggedin = false;

var data = {
  action: 'is_user_logged_in'
};

jQuery.post(ajaxurl, data, function(response) {
  if(response == 'yes') {
    userisloggedin = true; // user is logged in, do your stuff here
  } else {
    userisloggedin = false;  // user is not logged in, show login form here
  }
});

I tried to add this to x-child/functions.php but styles are not picking up.

function x_child_styles_scripts() {
  wp_register_style('x', get_template_directory_uri() . '/style.css', array());
  wp_register_style('x-child', get_stylesheet_directory_uri() . '/css/cg.css', array('x'));
  wp_enqueue_style('x-child');
}
add_action( 'wp_enqueue_scripts', 'x_child_styles_scripts' );

What am I missing?

Also, What is the right way to enqueue custom x-child/js/cg.js javascript file?

Hi there,

Please try to add this code in the functions.php:

/**
 * Enqueue scripts and styles.
 */

add_action( 'wp_enqueue_scripts', 'x_child_styles_scripts' ); 
 
function x_child_styles_scripts() {	

	wp_enqueue_style( 'x-child-css', get_stylesheet_directory_uri() . '/css/cg.css', array() );
	wp_enqueue_script( 'x-child-js', get_stylesheet_directory_uri() . '/js/cg.js ', array(), '1.0.0', true );
}

Hope this helps.

2 Likes