0

I want to get the latest titles with the_title() in an array so that I can loop through them in my javascript function.

How can I create this array?

Many thanks!

2

You can use the WordPress function wp_get_recent_posts(), with required args.

$output = array();

$args = array(
'numberposts' => 10,
'offset' => 0,
'category' => 0,
'orderby' => 'post_date',
'order' => 'DESC',
'include' => ,
'exclude' => ,
'meta_key' => ,
'meta_value' =>,
'post_type' => 'post',
'post_status' => 'draft, publish, future, pending, private',
'suppress_filters' => true );

$recent_posts = wp_get_recent_posts( $args, ARRAY_A );
foreach( $recent_posts as $post ) {
   $output[$post["ID"]]['title'] = $post["post_title"];
   $output[$post["ID"]]['title'] = get_permalink($post["ID"]);

}
add_action('wp_head', 'wpse158654_recent_posts');
function wpse158654_recent_posts() {?>
  <script type="text/javavscript">
   var recent_posts = <?php json_encode( $output ); ?>;
  </script>
}

Or you can use the wp_localize_script() function to print the variable for required js.

I haven't tested the code, be careful if you are using it on live site directly.

2

An example using wp_localize_script() which is a clean solution to insert JavaScript variables in the page.

// Attaching to the wp_enqueue_scripts hook because of wp_localize_script()
add_action( 'wp_enqueue_scripts', 'wpse158654_js_post_titles' );

function wpse158654_js_post_titles() {
    $args = array(
        'posts_per_page' => 3, // Number of posts to pick up
    );

    $wp_query = new WP_Query( $args );
    $post_titles = array();

    while ( $wp_query->have_posts() ) {
        $wp_query->the_post();
        $post_titles[] = get_the_title();
    }

    // Inject a JavaScript variable into the document
    // Note: you may want to change the script handle (first argument)
    wp_localize_script( 'jquery', 'post_titles', $post_titles );
}

And this should be the JavaScript variable, popping up right after the inclusion of jQuery in this case (depends on the script handle used).

<script type='text/javascript'>
/* <![CDATA[ */
var post_titles = ["Title 1","Title 2","Title 3"];
/* ]]> */
</script>
0

You could use get_posts to get the an array of posts objects, by default it returns the latest posts.

You should iterate over the array and do what you need with the titles.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.