How to add php code in wordpress page
There are several ways for adding php code in wordpress pages.
1. Plugins
You can use code snippets plugin in word press. I myself prefer to have more control on the code.So generally I used to avoid plugin and rather write some php code manually. Here I am going to show you both the options.
Go to plugins tab
add_shortcode('show_post', 'get_all_post');
function get_all_post(){
global $wpdb;
$tablename=$wpdb->prefix.''posts";
ob_start();
$posts= $wpdb->get_results( $wpdb->prepare("SELECT title FROM $tablename"));
?>
<?php
foreach( $posts as $post) {?>
<div class='show-title'>
<article><h1>
<?php echo $post->title;
?>
</h1></article>
</div>
<?php
}
return ob_get_clean();
}
In functions.php you can define above php function and return the output.
- wpdb is the global variable in wordpress to access the database
- wpdb-prefix is the prefix default db prefix. you can modify this prefix value also or you can mention your own prefix
- wpdb->get_results to fetch the results from db according to query you have mentioned
One thing to remember here is never echo or print any statement inside the shortcode function in wordpress. Always try to return the output. Shortcode function should always return the output as then only it will be shown on your website at expected location otherwise the function will print the output before the code gets executed completely.
In above function you can see we are also returning the HTML content from the function.
For returning html code from wordpress shortcode function.
- close the php code with ?> symbol and then start writing your html code
- use <?php for again starting php code in you function
Putting shortcode in your wordpress website page
[show_post]
This is how you can put the shortcode in any of your wordpress website page. Function mapped to this shortcode will get executed by itself. This shortcode an we used in multiple website pagesfunction get_all_post(){ global $wpdb; $tablename=$wpdb->prefix.''posts"; ob_start(); $posts= $wpdb->get_results( $wpdb->prepare("SELECT title FROM $tablename")); ?> <?php foreach( $posts as $post) {?> <div class='show-title'> <article><h1> <?php echo $post->title; ?> </h1></article> </div> <?php } return ob_get_clean(); } add_shortcode('show_post', 'get_all_post');
wp->results returning empty
custom submit form in wordpress
Comments
Post a Comment