How to make ajax call in wordpress in right way?

I am trying to using jquery ui tabs with ajax calls to run a function. Here is the code i am using:

function ajax_load_user_feed(){
    if(isset($_GET['type'])) $type = $_GET['type'];
    if(isset($_GET['userid'])) $userid = $_GET['userid'];

    if(!$type && !$userid){
        $type = 'error';
    } else {
        $user_info = get_userdata($userid);
        show_feed($type, $user_info);
add_action('wp_ajax_load_user_feed', 'ajax_load_user_feed');

function show_feed($type, $user){
    if($type == 'rss'){
      echo '<div>Show rss Feed</div>';

    } elseif($type == 'twitter'){
        echo '<div>Show twitter Feed</div>';

    } elseif($type == 'facebook'){
        echo '<div>Show Facebook Feed</div>';
    } elseif($type == 'error'){
        echo '<div class="feed_error">Something is wrong with the request!</div>';

The html for jqurey ui tabs:

<div class="tabs">

                        <ul id="social-media-activity-button" class="tabs">
                            <?php  if($author->feeds): ?>
                                    <li class="activity-blogs"><a title="activity_feed" href="<?php bloginfo('wpurl'); ?>/wp-admin/admin-ajax.php?action=load_user_feed&type=rss&userid=<?php echo $author->ID; ?>">Blogs</a></li>
                                <?php endif; if($author->twitter): ?>
                                <li class="activity-twitter"><a title="activity_feed" href="<?php bloginfo('wpurl'); ?>/wp-admin/admin-ajax.php?action=load_user_feed&type=twitter&userid=<?php echo $author->ID; ?>">Twitter</a></li>
                                <?php endif; if($author->facebook): ?>
                                <li class="activity-facebook"><a title="activity_feed" href="<?php bloginfo('wpurl'); ?>/wp-admin/admin-ajax.php?action=load_user_feed&type=facebook&userid=<?php echo $author->ID; ?>">Facebook</a></li>
                                <?php endif; ?>

                        <h2 class="dotted">Activity Feed</h2>

                        <div id="activity_feed">


What i am trying to do here is calling admin-ajax.php file to call the function load_user_feed(); function.

Now the code is works for logged in users only. I mean when users logged in the see the feeds but logged out users are seeing only -1 in output. Here is the page:

There must be some good way to call ajax with jquery ui tabs.

Waiting for your help. Thanks!

Answers 1

  • Your ajax hook

     add_action('wp_ajax_load_user_feed', 'ajax_load_user_feed');

    is for logged in users only, if you want none logged in users (guests or visitors) then add:

     add_action('wp_ajax_nopriv_load_user_feed', 'ajax_load_user_feed');

    and you should be fine.

Related Questions