WordPress Snippets


Aug

20

Shortcodes Within a WordPress Template.

Posted by CodeMunkyX

While building this site and customizing some plugins, I came across a couple of instances where I needed to embed plugin shortcodes into my template files. If you are ever in a situation where you need to embed a WordPress shortcode within a template, here is a quick snippet that will do this for you.

<?php echo do_shortcode('[shortcodename]'); ?>

Aug

18

Remove dashboard widgets in WordPress

Posted by CodeMunkyX

We used to see lots of widgets on WordPress’s dashboard. By default there is an option called “Screen Option“, to hide them all. But how can we remove or disable them forever?. Here is the simple script for you. This script will remove dashboard widgets in WordPress.

Open your theme’s functions.php file located in your theme’s folder. Copy this script, paste it in your theme’s functions.php file and save it. Now goto the dashboard page. Wow, everything is gone. Right?.

<?php
function remove_dashboard_widgets() {
  global $wp_meta_boxes;
  // For right now information widget
  unset($wp_meta_boxes['dashboard']['normal']['core']['dashboard_right_now']);
  // For recent comments listing widget
  unset($wp_meta_boxes['dashboard']['normal']['core']['dashboard_recent_comments']);
  // For quick press widget
  unset($wp_meta_boxes['dashboard']['side']['core']['dashboard_quick_press']);
  // For recent drafts widget
  unset($wp_meta_boxes['dashboard']['side']['core']['dashboard_recent_drafts']);
  // For Plugin information widget
  unset($wp_meta_boxes['dashboard']['normal']['core']['dashboard_plugins']);
  // For incoming links information widget
  unset($wp_meta_boxes['dashboard']['normal']['core']['dashboard_incoming_links']);
  // For WordPress blog news widget
  unset($wp_meta_boxes['dashboard']['side']['core']['dashboard_primary']);
  // For other WordPress news widget
  unset($wp_meta_boxes['dashboard']['side']['core']['dashboard_secondary']);
}
add_action('wp_dashboard_setup', 'remove_dashboard_widgets' );
?>

Aug

15

Create / Assign Categories to WordPress Post

Posted by CodeMunkyX

If you plan on developing WordPress plugins, chances are you will eventually need to know how to create / assign categories to a WordPress post in your blog. The following snippet of code will show you how.

<?php
$post_id = 22;
$wpcatlist[] = "PHP";
$wpcatlist[] = "WordPress";

wp_create_categories($wpcatlist,$post_id);
?>

Aug

15

Add Custom Fields to WordPress Post

Posted by CodeMunkyX

This WordPress snippet will allow you to add custom fields and attach them to a post. This is great for extending WordPress themes and/or assigning useful data for a WordPress plugin to utilize.

<?php
add_post_meta(22, "mycustomcolumnname", "mycustomcolumnvalue", true);
?>

Also, elsewhere in your code you can use the following to retrieve any custom fields attached to a post by using the get_post_meta function.

<?php
$customfieldvalue = get_post_meta(22, 'mycustomcolumnname', true);
echo $customfieldvalue; // would display "mycustomcolumnvalue"
?>

Aug

15

Add Tags to WordPress Post

Posted by CodeMunkyX

The following snippet will add post tags to the WordPress database and associate them to the post id provided. This is usually utilized in a WordPress plugin.

<?php
$post_id = 22; // post id of the post you wish to add post tags for
$wptags  = "php,mysql,wordpress,css";

wp_set_post_tags($post_id,$wptags);
?>

The $wptags variable can either be a comma-delimited list of tags (above) or an array (below).

<?php
$post_id = 22; // post id of the post you wish to add post tags for
$wptags    = array();
$wptags[]  = "php";
$wptags[]  = "mysql";
$wptags[]  = "wordpress";
$wptags[]  = "css";

wp_set_post_tags($post_id,$wptags);
?>

Aug

14

Access WordPress and PHP Variables in Javascript

Posted by CodeMunkyX

If you have been coding plugins or just tinkering around with WordPress, you will undoubtedly come across the hurdle of easily accessing data in your PHP scripts from within your Javascript source files. Below is a great way of achieving this.

WordPress has made available the wp_localize_script function that is typically used for localizing strings, etc within your Javascript code. This can also be used to assign PHP / WordPress data to different Javascript variables that will be available inside the Javascript handle used in the wp_enqueue_script function.

The below example utilizes the admin_print_scripts action, which will obviously only run in the admin section of WordPress. You may change this based on your needs.

<?php
add_action('admin_print_scripts', 'adminScripts');
?>

Now, we must define our adminScripts function that will be called from the above add_action command. Note the use of the wp_localize_script and how we assign Javascript variables to PHP values available within our WordPress plugin. The first parameter refers to the handle of your JS file loaded in wp_enqueue_script, the second parameter refers to the Javascript Object that will be used to reference these variables, and the third parameter is an array of variable definitions.

<?php
function adminScripts() {
    wp_register_script( 'myJsFile', 'http://url/to/js/myJsFile.js', NULL;
    wp_enqueue_script( 'myJsFile' );

    $pluginurl   = WP_PLUGIN_URL . "/myplugindir/phpfile.php";
    $dataperpage = "20";

    wp_localize_script( 'myJsFile', 'myJsFileVars', array(
	    'pluginUrl'   => $pluginurl,
	    'dataPerPage' => $dataperpage
	    )
    );
}
?>

Finally, anywhere in your myJsFile.js you can reference these new Javascript variables in the following manner…

    alert(myJsFileVars.dataPerPage);
    alert(myJsFileVars.pluginUrl);

Aug

11

Utilize jQuery and AJAX in WordPress

Posted by CodeMunkyX

In the following snippets of code, we will show you how to implement the use of jQuery and AJAX in your WordPress installation (typically in your own custom plugin). The first bit of code you will need is to make sure that you load the jQuery library.

Since WordPress comes with jQuery and AJAX already bundled, you can make sure it is loaded by first setting up an action for WordPress to include the jQuery library. The below example utilizes the admin_print_scripts action, which will obviously only run in the admin section of WordPress. You may change this based on your needs.

<?php
add_action('admin_print_scripts', 'adminScripts');
?>

Now, we must define our adminScripts function that will be called from the above add_action command. Also, this is where you will add the wp_enqueue_script call to include the jQuery library.

<?php
function adminScripts() {
    wp_enqueue_script( 'jquery' );
}
?>

Next, you will want to register and load your own javascript file within WordPress and make it dependent on jQuery. You can go ahead and include these in the same function above (after the jquery library). See the updated code below.

<?php
function adminScripts() {
    wp_enqueue_script( 'jquery' );
    wp_register_script( 'myJsFile', 'http://url/to/js/myJsFile.js', array('jquery', "1.0" );
    wp_enqueue_script( 'myJsFile' );
}
?>

Next, open up your myJsFile.js and paste the following code. Obviously if you already have the declaration of jQuery(document).ready(function($), you will not need that piece and should only copy the content inside. The below code assumes you wish to fire off the AJAX call on a click event of #someElementId. NOTES: the action parameter below must ultimately match the function you wish to call in your plugin. Also, ajaxurl is already pre-defined for you in WordPress so you will want to keep that as it is.

jQuery(document).ready(function($) {

   $('#someElementId').live('click', function() {
		var dataRequest = ({action: "yourWordPressAjaxFunction",
				    someparam: somevalue,
				    seed: Math.random()});

		$.ajaxSetup ({
			cache: false,
			async: false
		});

		$("#preloader").html('<p><img src="loader.gif" alt="" /></p>');

		$.get(ajaxurl, dataRequest, function(data){

			if (data.returnError != "success") {
				divContent = '<p> + data.returnError + '</p>';
				$("#someDivId").empty().append( divContent );
			} else {
                        divContent  = '<p><strong>FINISHED</strong></p>';
                        divContent  += '<p><strong>VAR1: ' + data.someValue1 + '</strong></p>';
                        divContent  += '<p><strong>VAR2: ' + data.someValue2 + '</strong></p>';
                        $("#preloader").empty().append( divContent );
			}
		}, "json");
    });
});

Back in your WordPress Plugin code, you will want to accept the action parameter from the .get() jQuery function above. Also, this is where you will want to add your wp_ajax action as this is how WordPress knows which function to call.

<?php
if (isset($_REQUEST['action'])) {
	switch ( $_REQUEST['action'] ) {
                case 'yourWordPressAjaxFunction' :
                add_action('wp_ajax_yourWordPressAjaxFunction', 'yourWordPressAjaxFunction', 1, 1);
                break;
	}
}
?>

And lastly, you will need to define your function that will handle the JSON response to the AJAX call from above.

<?php
function yourWordPressAjaxFunction() {

	$jsonVARS = array();
	$jsonVARS['returnError'] = "success";

        // do some code and maybe set $jsonVARS['wppgError'] to some value to return any errors

	$jsonVARS['someValue1']  = "here is your someValue1";
	$jsonVARS['someValue2']  = "this is your someValue2";

	echo json_encode($jsonVARS);
	die();
}
?>

Important: The die(); statement above must exist there as the AJAX call will not function correctly if you remove it.

Aug

11

Display Authors Multiple Selection Box

Posted by CodeMunkyX

The below WordPress snippet is a bit of php code that will display a list of Authors from  your blog.

<?php
$selecthtml = wp_dropdown_users(array('echo' => '0', 'name' => 's_postAuthor[]', 'id' => 's_postAuthor', 'who' => 'authors'));
$selecthtml = str_replace('<select', '<select style=\'width:200px\' multiple=\'multiple\' tabindex=\'4\' size=\'5\'', $selecthtml);
echo $selecthtml;
?>

Note the use of the name attribute with value s_postAuthor[]. This will allow your php code to parse multiple selections in an array.

<?php
$authors = $_REQUEST['s_postAuthor'];

for ($i=0; $i < count($authors); $i++) {
    print $authors[$i];
}
?>

Aug

11

Add Mime Types to WordPress

Posted by CodeMunkyX

If you have ever tried to upload media that WordPress does not allow by default, you have probably gotten the dreaded mime types error. Below, we will show you a quick way to get any mime type (such as CSV files) supported by the Media Library.

You will need to add the following 2 code snippets into your functions.php file for your active theme.

<?php
add_filter('upload_mimes', 'addUploadMimes');
?>

The above code will utilize the add_filter function to inject upload_mimes with a return array from the internal function addUploadMimes.

<?php
function addUploadMimes($mimes) {
    $mimes = array_merge($mimes, array(
                'csv' => 'text/csv'
             ));
    return $mimes;
}
?>

The above function accepts the existing mime types in the $mimes input and merges your new mime type and returns it to the upload_mimes filter. Save the code to your functions.php file in your theme folder and you should now be able to upload CSV files to your WordPress Media Library.

Bonus Tip

If you have any reason to place the above code in a PHP class file… you will want to use the following add_filter code instead so that WordPress will know how to call the function correctly.

<?php
add_filter('upload_mimes', array(&$this, 'addUploadMimes'));
?>

featured wordpress themes