Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the correct approach to add custom HTML CSS Javascript code to certain wordpress post

Tags:

wordpress

I'm trying to add custom HTML, CSS and JQuery code to certain wordpress posts but I don't know if I'm using the right approach since I am just adding the code right into the post.Because there is going to be more posts which may need to use the custom code and with this approach I have to copy/past and customize the same code to those posts too. Is there maybe a better approach to do this?

I don't know much about creating wordpress plugins but an idea tells me plugins are the right way to go, If so how can I turn this to a plugin for wordpress?

Here is an example of the code:

<p style="text-align: left;">Post begins here and this is the text...
<div class="myDiv" >button</div>
<style type="text/css">
.myDiv{
    color: #800080;
    border: #000;
    border-radius: 20px;
    border-style: solid;
    width: 50px;
      }
</style>
<script type="text/javascript">
 <!--
 $(".farzn").on("click", function(){
  alert('its Working');
 });
 //--></script>
like image 383
Farzan Avatar asked Sep 10 '26 20:09

Farzan


1 Answers

Writing a Plugin is quite easy: create a PHP file with the following content:

<?php
/* Plugin Name: Empty Plugin */

Upload it to your wp-content/plugins folder and it will show up in the plugins list.

And now the fun, the hooks wp_head and wp_footer can be used for small inline styles and scripts. Check Conditional Tags for all filtering possibilities.

<?php
/* Plugin Name: Custom JS and CSS */

add_action( 'wp_head', 'my_custom_css' );
add_action( 'wp_footer', 'my_custom_js' );

function my_custom_css()
{
    if( is_home() )
    {   
        ?>
        <style type="text/css">
        body {display:none}
        </style>
        <?php
    }
    if( is_page( 'about' ) )
    {   
        ?>
        <style type="text/css">
        body {background-color:red}
        </style>
        <?php
    }
    if( is_category( 'uncategorized' ) || in_category( array( 1 ) ) )
    {   
        ?>
        <style type="text/css">
        #site-title {display:none}
        </style>
        <?php
    }
}

function my_custom_js()
{
    ?>
    <script type="text/javascript">
     <!--
     jQuery("#site-description").on("click", function(){
      alert('its Working');
     });
     //--></script>
    <?php
}

The best practice is to enqueue all your styles and scripts as separate files with the action hook wp_enqueue_scripts. Conditional Tags can also be used.

like image 73
brasofilo Avatar answered Sep 13 '26 19:09

brasofilo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!