Creating new Shortcodes using WP Query

//Creating new Shortcodes using WP Query

Creating new Shortcodes using WP Query

Recently, a friend reached out to me and communicated that he is working on a client project and wanted to do some customization around one of the plugins that they are using. My friend is not a php developer and was looking for some help in this area. The plugin he was using was the “Job Manager” plugin. If you are not already aware with the Job Manager plugin, its a nice piece of work written to create Job Boards in WordPress Websites.
The problem that my friend was looking to resolve is to list jobs in a column format by Categories and not in the default way that the plugin template does. I looked at all the options and I thought the most simplest option is to create a simple shortcode that will list the jobs given a category. In this post I will go over three important things if you are somewhat into WordPress codex and development and Coding. PRimarily I will go over the WP Query Class and secondly I will be going over about Creating new Shortcodes using the WP Query. My post will require you to add some code to your functions.php file, please be sure you have a child theme set up and back up your files properly before exploring anything in this area. If you want to learn more about Child Themes, here is the post for that.

Shortcodes using WP Query

Here is the sample code to create an empty function and add the shortcode:

// This is simply a function to output the jobs by category
// it takes 3 parameters per the wordpress codex
// The return value should be a string that will be displayed when shortcode is used
function getJobByCategory_func($atts, $content = null, $tag) {
   return 'Hello Jobs By Category';
}
add_shortcode('getJobByCategory', 'getJobByCategory_func');

Step 2: Add logic in your shortcode:

In my scenario I wanted to Query WordPress for a custom Post Type that is created by the Job Manager plugin and then filter the results based on some criteria. While going over this I would like to explain some of the important things while using WP Query in your code. First of all WP Query is a powerful way to use WordPress API. You can retrieve any key information regarding custom post types that exist in your system without explicitly querying the database. From a developer’s perspective they just call an API and the magic happens underneath automatically. An important concept is the “Post Loop” when you execute a query, setting your current post pointer and then Resetting WP Query to do the clean up when you are done. Not doing a reset will lead to unpredictable results and you will be left scratching your head for a long time. You are Welcome!
Here is the full code for my implementation:

// This is simply a function to output the jobs by category
// the category number will be passed as the content of this shortcode [getJobByCategory]75[/getJobByCategory]
// it takes 3 parameters per the wordpress codex
// The return value should be a string that will be displayed when shortcode is used
function getJobByCategory_func($atts, $content = null, $tag) {

    // get the Category IDs from the parameters
	// these are not used really but I left it in the code
    extract(shortcode_atts(array('categoryID' => '0'), $atts));
	
	//this is the return string for the shortcode
    $title = ' ';
    $foundjob = true;
	
    //we only need to display 10 jobs.
    $count = 0;

    //Create a WP Query object for post types = jobman_job
    $query = new WP_Query(array('post_type' => 'jobman_job'));

    //If there are jobs created in the system
    while ($query - > have_posts()) {

        //set the current job and get the id
        $query - > the_post();
        $post_id = get_the_ID();

        //find the job categories using the object terms
        $cats = get_the_terms($post_id, 'jobman_category');

        // if there were any categories then match them with the parameter
        if (count($cats) > 0) {
		    
			// loop through the returned posts
            for ($i = 0; $i < count($cats); $i++) { //match their category if ($cats[$i] - > term_id == (int) $content) {
                    if ($count < 11) {
                        $title = $title.
                        '
<ul class="job-ul">'; //try to get location $location = get_post_meta($post_id, 'data4', true); $strexp = get_post_meta($post_id, 'displayenddate', true); // make sure the job post is not expired if (strtotime($strexp) > time()) { // if a job location is defined display it otherwise do not output anything for location if (strlen($location) > 0) { $title = $title. '
 	<li class="job-li"><a class="job-li-a" href="'.get_page_link($post_id). '">'.get_the_title(). '</a> ('.$location. ')</li>
'; } else { $title = $title. '
 	<li class="job-li"><a class="job-li-a" href="'.get_page_link($post_id). '">'.get_the_title(). '</a></li>
'; } } //strtotime $title = $title. '</ul>';
                        $count = $count + 1;

                    } //count < 11
					
                } // match category
				
            } // for each category
			
        } // if count cats
		
    } //while have posts

    wp_reset_query();
    return $title;
}
add_shortcode('getJobByCategory', 'getJobByCategory_func');
By |2017-09-14T00:01:19+00:00September 13th, 2017|Blog|0 Comments