I’m just getting started with wordpress development. I’m trying to create a simple plugin that show results from a db in a table. I can do this, but I’m having trouble with the plugin showing at the top of the admin pages. I’m not sure why it does this.
my plugin function:
add_action('init','hello_world');
function hello_world()
{
global $wpdb;
$query = "Select ID, post_title
From $wpdb->posts Limit 0, 10";
$results = $wpdb->get_results($query, ARRAY_A);
echo "<div class="datagrid"><table>";
echo "<thead><tr><th>header</th><th>header</th><th>header</th><th>header</th></tr></thead>";
echo "<tfoot>
<tr>
<td colspan="4">
<div id="paging">
<ul>
<li>
<a href="#"><span>Previous</span></a>
</li>
<li>
<a href="#" class="active"><span>1</span></a>
</li>
<li>
<a href="#"><span>2</span></a>
</li>
<li>
<a href="#"><span>3</span></a>
</li>
<li>
<a href="#"><span>4</span></a>
</li>
<li>
<a href="#"><span>5</span></a>
</li>
<li>
<a href="#"><span>Next</span></a>
</li>
</ul>
</div>
</tr>
</tfoot>";
echo "<tbody>";
$i = 0;
while($i < 10)
{
foreach ($results as $item)
{
$postID = $item['ID'];
$postTitle = $item['post_title'];
echo "<tr class="alt">";
echo "<td>" .$postID."</td>";
echo "<td>".$postTitle."</td>";
echo "</tr>";
$i++;
}
}
echo "</tbody>";
echo "</table></div>";
}
calling in index.php
<?php
if(is_admin())
{
}
else
{
if(function_exists('hello_world')) {
echo "<div>";
hello_world();
echo "</div>";
}
}
?>
how can I prevent this from showing in the admin section?
To complement @s_ha_dumâs answer: If you just want to offer a function to be used in a theme, make it a custom action.
Sample:
Now, in a theme, the author can call your function with â¦
⦠and the function will print its content only where the author needs it.
This has at least three advantages:
function_exists()
, which is always ⦠ugly.Here is a sample plugin:
Install, activate, and use the
do_action()
in a theme as often as you need it.You have hooked your function to
init
which runs on (I believe) every page load, front or back, and you are echoing data. Not to be harsh but what did you expect to happen?To solve this, remove the first line–
add_action('init','hello_world');
Your function will then only run when explicitly called from your code inindex.php
.