• Resolved robinheymans

    (@robinheymans)


    Hi!

    I’m looking for a way to add a CSS snippet to the admin section only, or to add a CSS snippet to both the admin section and the frontend of the website. Is this possible?

    Kind regards,

    Robin

Viewing 3 replies - 1 through 3 (of 3 total)
  • Plugin Author Mircea Sandu

    (@gripgrip)

    Hi @robinheymans,

    Unfortunately, there’s no built-in way to add admin css at this time but you can use a custom PHP snippet set to “Admin Only” with the following code:

    add_action( 'admin_head', function() {
    
    // Add CSS code below.
    
    ?>
    
    <style>
          
       </style>
    
    <?php
    });
    Thread Starter robinheymans

    (@robinheymans)

    Hi @gripgrip

    Thanks for the reply. I’ve extended your script: this adds every WPCode snippet of type CSS with the tag “admin” to the head of the admin section.

    add_action('admin_head', 'wpcode_admin_css');
    
    function wpcode_admin_css() {
    	global $wpdb;
    	
    	$stylesheets = $wpdb->get_results("SELECT p.post_content, p.post_title FROM wp_posts p
    			JOIN wp_term_relationships tr_category ON tr_category.object_id = p.id
    			JOIN wp_term_taxonomy tt_category ON tr_category.term_taxonomy_id = tt_category.term_taxonomy_id
    			JOIN wp_terms t_category ON tt_category.term_id = t_category.term_id
    			JOIN wp_term_relationships tr_tag ON tr_tag.object_id = p.id
    			JOIN wp_term_taxonomy tt_tag ON tr_tag.term_taxonomy_id = tt_tag.term_taxonomy_id
    			JOIN wp_terms t_tag ON tt_tag.term_id = t_tag.term_id
    		 WHERE p.post_status != 'trash' AND p.post_type = 'wpcode'
    			AND tt_category.taxonomy = 'wpcode_type' AND t_category.name = 'css'
    			AND tt_tag.taxonomy = 'wpcode_tags' AND t_tag.name = 'admin'");
    	
    	$styleblock = "<style>";
    	foreach ($stylesheets as $stylesheet) {
    		$styleblock .= "/* " . $stylesheet->post_title . " */";
    		$styleblock .= $stylesheet->post_content;
    	}
    	$styleblock .= "</style>";
    	
    	echo $styleblock;
    }

    @robinheymans This is an absolutely incredible piece of code. Thank you. I believe I am noticing that this still adds the code snippet, even if they are “inactive.” Is that true? If so, can something be rewritten where it also checks if the snippet is active? Probably somewhere in that post_status line, but I am just starting to wrap my head around this stuff.

Viewing 3 replies - 1 through 3 (of 3 total)

The topic ‘Add CSS to admin section’ is closed to new replies.