Skip to content

Instantly share code, notes, and snippets.

@wvfitzgerald
Last active May 12, 2021 19:31
Show Gist options
  • Select an option

  • Save wvfitzgerald/237c0822d1973ad378ac27c6f415ecbb to your computer and use it in GitHub Desktop.

Select an option

Save wvfitzgerald/237c0822d1973ad378ac27c6f415ecbb to your computer and use it in GitHub Desktop.

Revisions

  1. wvfitzgerald revised this gist May 12, 2021. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion wp-ajax-get-post.php
    Original file line number Diff line number Diff line change
    @@ -1,5 +1,5 @@
    <?php
    /*---We can add this bit to to our theme's fuction.php or a cusotm pluging-----*/
    /*---We can add this bit to to our theme's fuction.php or a custom plugin-----*/
    function get_wp_posts() {
    // Arguments: see docs for get_post @ https://developer.wordpress.org/reference/functions/get_posts/
    $args = array(
  2. wvfitzgerald created this gist Oct 19, 2020.
    47 changes: 47 additions & 0 deletions wp-ajax-get-post.php
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,47 @@
    <?php
    /*---We can add this bit to to our theme's fuction.php or a cusotm pluging-----*/
    function get_wp_posts() {
    // Arguments: see docs for get_post @ https://developer.wordpress.org/reference/functions/get_posts/
    $args = array(
    'post_type' => 'post',
    'post_status' => 'publish',
    'numberposts' => 5,
    );

    // Get the Post
    $wpajaxposts = get_posts( $args );

    echo json_encode( $wpajaxposts );

    exit;
    }

    /*---- The important part-AJAX action hooks for both logged in and non-logged in users,
    notice that the firstparmaeted is our function ame prepended wiht wp_ajax_ and
    wp_ajax_nopriv_ ,
    -----*/
    add_action('wp_ajax_get_wp_posts', 'get_wp_posts');
    add_action('wp_ajax_nopriv_get_wp_posts', 'get_wp_posts');

    /* Where our ajax magic happens, for this I am using wp_footer to add my js but we can add the js to a page template,
    widget etc. */
    function get_ajax_post_js(){ ?>
    /*----Handle this as usual with the " data: { action : 'get_wp_posts' }" bit refferncing our above funciton-------*/
    <script>
    jQuery.ajax({
    type: 'POST',
    url: '<?php echo admin_url('admin-ajax.php');?>',
    dataType: "json", // add data type
    data: { action : 'get_wp_posts' },
    success: function( response ) {
    jQuery.each( response, function( key, value ) {
    console.log( value.post_title ); // the posts titles.
    // console.log( key, value ); //Uncomment to see all of the past data
    } );
    }
    });

    </script>
    <?php
    }
    add_action('wp_footer' , 'get_ajax_post_js');