Shortcodes are special tags that you can use in WordPress to execute specific functions or display dynamic content. They are typically enclosed in square brackets, like this: [shortcode]
To add a shortcode to a WordPress site, you will need to create a custom plugin or functions.php file in your theme. Here is an example of how you can create a simple shortcode that displays a "Hello, World!" message:
function hello_world_shortcode() { return 'Hello, World!'; } add_shortcode( 'hello_world', 'hello_world_shortcode' );
Save the changes to your plugin or functions.php file.
You can now use the shortcode in any post or page on your site by simply adding the shortcode tag to the content editor: [hello_world]
This shortcode will be replaced with the text "Hello, World!" when the post or page is displayed.
You can customize the shortcode to do more complex tasks by adding additional functionality to the shortcode function. For example, you could create a shortcode that displays a form or a list of posts from a specific category.
Here is an example of a more advanced shortcode that displays a list of posts from a specific category:
function posts_by_category_shortcode( $atts ) { // Extract the attributes extract( shortcode_atts( array( 'category' => '', ), $atts ) );
// Set up the query $query = new WP_Query( 'cat=' . $category ); // Start the output buffer ob_start(); // Check if there are any posts if ( $query->have_posts() ) { // Start the unordered list echo ' '; // Loop through the posts while ( $query->have_posts() ) { $query->the_post(); // Display the list item echo '- <a href="' . get_the_permalink() . '">' . get_the_title() . '</a> '; } // End the unordered list echo ' '; } else { // No posts found echo 'No posts found'; } // Reset the post data wp_reset_postdata(); // Get the contents of the output buffer $output = ob_get_clean(); // Return the output return $output; } add_shortcode( 'posts_by_category', 'posts_by_category_shortcode' );
This shortcode can be used like this: [posts_by_category category="news"]
This will display a list of posts from the "news" category.