2

I would like to use arrows to dynamically change which posts appear in a div by cycling through an array of say 5 posts. How would i approach this issue?

I have made the array that the get posts function is assigned to a global variable, but that's the only thing i have done so far, as I am kind of stumped. I tried using the debug log to print the array to get some sense of how to use it, but it doesn't make any sense at all.

Would this have something to do with wp_localize_script()? Also I'm looking to have three of these on my front page so, if I use wp_localize_script() can i use this three times? To pass three separate arrays of posts?

  • Sounds like you want a Carousel or Slider (they go by many names), which are usually used to cycle through a group of photos using arrows. I'd suggest you find a plugin that works and looks like you want, then replace the content with your posts. – scott Mar 28 '17 at 17:03
  • Not at all, I'm looking to make something like a carousel but I don't want to use a ready made plugin I want to make something that works for me. – Stefanos Vorkas Mar 28 '17 at 18:13
2

Yep, you're looking for wp_localize_script(). Do away with the global.

add_action( 'wp_enqueue_scripts', 'wpse_enqueue_scripts' );
function wpse_enqueue_scripts() {
    wp_enqueue_script( 'wpse-main', get_template_directory_uri() . '/path/to/script.js', array(), false, true );
    wp_localize_script( 'wpse-main', 'wpseVars', array(
        'postsLoop1' => json_encode( /* first post array */ ),
        'postsLoop2' => json_encode( /* second post array */ ),
        'postsLoop3' => json_encode( /* third post array */ )
    ) );
}

Then in your script, you can access the variables by grabbing wpseVars.postsLoop1, wpseVars.postsLoop2, etc.

| improve this answer | |
  • Can this pass three separate arrays though? – Stefanos Vorkas Mar 28 '17 at 21:17
  • @StefanosVorkas Sure. If you have different sets of posts, just create an array key/value pair for each. For example, you could do postLoop1, postLoop2 and then access them in your script with wpseVars.postLoop1, etc... – brianjohnhanna Mar 28 '17 at 21:20
  • You're talking about the posts=>json_encode bit? have postLoop1=>json_encode etc? – Stefanos Vorkas Mar 28 '17 at 21:23
  • @StefanosVorkas exactly. check my updated answer – brianjohnhanna Mar 28 '17 at 21:27

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.