将WP主题代码转换为独立插件

时间:2013-05-22 19:20:47

标签: php javascript jquery wordpress

我正在尝试开发一个在Wordpress网站上创建降雪效果的插件。我的代码如下:

<?php
/*
Plugin Name: tuhin 
Plugin URI: no plugin uri
Description: This plugin will add a Simple & lightweight responsive slider.
Author: tuhin
Author URI: no author uri
Version: 1.0
*/
/* Launch the plugin. */
add_action( 'plugins_loaded', 'wp_snowfall_plugins_loaded' );

/* Initializes the plugin and it's features. */
function wp_snowfall_plugins_loaded() {
    /* Set constant path to the members plugin directory. */
    define( 'WP_SNOWFALL_DIR', plugin_dir_path( __FILE__ ) );

    /* Set constant path to the members plugin directory. */
    define( 'WP_SNOWFALL_URL', plugin_dir_url( __FILE__ ) );

    /* Loads the snowfall. */
    add_action('wp_head', 'wp_snowfall_source');
    add_action('wp_head', 'wp_snowfall_effect');
}


function wp_snowfall_source() { 
    wp_enqueue_script( 'jquery.js' );
    wp_enqueue_script( 'snowfall', WP_SNOWFALL_URL.'snow.min.jquery.js' );
}

function wp_snowfall_effect() { ?>
<script type="text/javascript">
$(document).ready( function(){
    $.fn.snow();
});
</script>
<?php
}
?>

当我在我的主题中复制这个jQuery代码时它可以工作,但是当我尝试将它转换为插件时,它不起作用。怎么了?

2 个答案:

答案 0 :(得分:0)

尝试:add_action( 'init', 'wp_snowfall_plugins_loaded' );而不是

答案 1 :(得分:0)

你错误地使用了jQuery。

然后,使用以下noConflict模式启动jQuery命令:

jQuery(document).ready(function($) {   
    $.fn.snow();
});

我使用Snowfall version 1.4进行了测试,这是工作代码(注意jquery排队作为snowfall的依赖项。)

add_action( 'plugins_loaded', 'wp_snowfall_plugins_loaded' );

/* Initializes the plugin and it's features. */
function wp_snowfall_plugins_loaded() {
    /* Set constant path to the members plugin directory. */
    define( 'WP_SNOWFALL_DIR', plugin_dir_path( __FILE__ ) );

    /* Set constant path to the members plugin directory. */
    define( 'WP_SNOWFALL_URL', plugin_dir_url( __FILE__ ) );

    /* Loads the snowfall. */
    add_action('wp_head', 'wp_snowfall_source');

    /* Startup the snowfall. */
    add_action('wp_footer', 'wp_snowfall_effect', 999 );
}


function wp_snowfall_source() { 
    wp_enqueue_script( 'snowfall', WP_SNOWFALL_URL.'snowfall.min.jquery.js', array('jquery') );     
}

function wp_snowfall_effect() { 
    ?>
    <script type="text/javascript">
    jQuery(document).ready(function($) {   
        $(document).snowfall();
    });
    </script>
    <?php
}

查看Plugin Demo Class,它会升级你的基础插件。使用常数不是好习惯......

另外,研究WordPress Answers上的plugin-development标签,有很多有用的信息;)