如何将自定义的HTML、CSS和Javascript代码添加到特定的WordPress文章中?

3
我试图在某些WordPress文章中添加自定义的HTML、CSS和JQuery代码,但我不知道自己是否使用了正确的方法,因为我只是直接将代码添加到文章中。由于以后可能还会有更多文章需要使用这些自定义代码,按照这个方法,我必须将相同的代码复制/粘贴并自定义到那些文章中。 也许有更好的方法吗? 我不太了解如何创建WordPress插件,但一个想法告诉我,插件是正确的方法。如果是这样,我该如何将其转换为WordPress插件呢?
以下是代码示例:
<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>
1个回答

2
编写插件很容易:创建一个包含以下内容的PHP文件:

Writing a Plugin


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

将它上传到你的wp-content/plugins文件夹中,它将出现在插件列表中。
而现在,有趣的事情来了,钩子wp_headwp_footer可以用于小型内联样式和脚本。查看条件标签以获取所有过滤可能性。
<?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
}

最佳实践是将所有样式和脚本作为单独文件使用操作钩子wp_enqueue_scripts进行排队。也可以使用条件标签。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接