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

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?

Read More

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>

Related posts

Leave a Reply

1 comment

  1. 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.