PHP: How to access db the right way in plugin?
I thought I would find an answer to my question on the internet but I was
not able to. This is not a big question, but as it is my first plugin, I
want to make sure that everything is right before submitting.
What I am doing is adding a link to navigation menu depending on a value
that admin selects from a settings panel in dashboard. I am accessing db
in my custom javascript to add data to tables (in admin dashboard) and
then fetching that data in another php script using "wp_nav_menu_items"
filter.
I used
wp_localize_script( 'my-ajax-request', 'accessDB', array( 'ajaxurl' =>
admin_url( 'admin-ajax.php' ) ) );
to get hold of admin-ajax.php path. I then send my ajax calls to url
referred by accessDB.ajaxurl. This part is working fine. And I think this
is the right way to make ajax calls in Wordpress plugin. If not please
correct me.
The second part is where I have to get the value from db. This is the
value I need in a wordpress filter hook wp_nav_menu_items. And this is how
it goes:
function add_custom_menu_link($items, $args) {
global $wpdb;
$row = $wpdb->get_row("SELECT * FROM " . $wpdb->prefix . "custom_table");
if (count($row) > 0) {
return $items . "<li class='menu-item'><a href='" . $row->url . "'
target='_blank'>Custom Link</li>";
} else {
return $items;
}
}
add_filter('wp_nav_menu_items', 'add_custom_menu_link', 10, 2);
So my question is that, am I doing it the right way, or do I have to use
cURL to get the data by using admin-ajax.php? Or is there any other way
that I am missing?
Regards
No comments:
Post a Comment