Here is what I have so far. I’m in no way a great programmer. Just a front end guy trying to get this to work. I have a website with different blog categories. For example I have a category called: foods, places, things. I’m trying to write a function where I can execute a shortcode like this:
[list_post mycat=”foods”]
Basically I want it to be flexible so whatever category I put inside of “mycat” it will display those blogs.
Again any help would be really appreciated. I know I need to pass a parameter, but I’m honestly unsure how. This is my best effort. Thanks for any hekp
$args = array(
//Pass parameter here
//Something like array (
//$mycat => 'slug';
//);
);
function list_post($mycat){
$query = new WP_Query(array('category_name' => $mycat));
if($query->have_posts()):
while($query->have_posts()):the_post();
the_title();
endwhile;
else:
echo "No posts found!";
endif;
wp_reset_postdata();
}
add_shortcode('list_post', 'list_post')
Your shortcode accepts 1 argument and it’s an array with values inside of it. So for this case,
$mycat
looks like this =>array('mycat' => 'foods');
, So for this instance, you should use the following to extract and compare:Its easier to use get_posts() to achieve this.
Note that it is better to return the output from your shortcode and not echo it.
Edit: Removed usage of
extract()
function as per @PieterGoosen’s advice.