1
<?php wp_dropdown_categories(); ?> 

→ This is how we can populate the categories in a drop-down.

N.B. We are dealing with WordPress.

This is how we generate a query in Wordpress:

    <?php
    // the query
        $the_query = new WP_Query( array(
        'post_type' => 'post',
        'posts_per_page' => 10,
        'post_status' => 'publish',
        'category_name' => 'staff'
        )  );
    ?>

I need some help in php here →

'category_name' => 'staff'

staff is a category, for example, here. How can we write in terms of PHP or Ajax so that whatever category is chosen from the populated category from the drop-down should come above dynamically based on the selection from the drop-down?

Means → 'staff' This should come up dynamically from the drop down. I am normal in PHP and ajax If someone can guide me than help will be highly appreciated.

WordCent
  • 725
  • 3
  • 18

1 Answers1

1

As we can see in the documentation of wp_dropdown_categories the input name is cat (or you can change it to anything you like and does not affect other parts of your code).

So in your PHP file do sth liek the following:

<?php
    // the query
        $the_query = new WP_Query( array(
        'post_type' => 'post',
        'posts_per_page' => 10,
        'post_status' => 'publish',
        'category_name' => $_POST['cat'] // or $_GET['cat'] or $_REQUEST['cat']
        )  );
    ?>

Make sure to validate and sanitize your POST/GET input to avoid problems

[UPDATE] If you use ajax then you have one php file that handles the ajax request using an action (for example take a look here). Then in your web facing php page use jquery or similar to post (or get) the ajax request and return the categories or posts using WP_Query like shown above. Read the article mentioned to have an idea how to implement ajax in Wordpress.

If you have further questions with the implementation please provide specific information so it can be helpful.

Nikos M.
  • 8,033
  • 4
  • 36
  • 43
  • Hi there, Thanks for the Input. I have tried that before also, but it didn't work. [see here](https://www.screencast.com/t/3wjjxs6YG) – WordCent May 19 '18 at 19:19
  • 1
    try to use `$_REQUEST` and try to see if it set at first before using it. I dont know and it is not mentioned how the form data are passed along (POST or GET) – Nikos M. May 19 '18 at 19:29
  • @somethingnow, the link you mention is for ajax, you do not have ajax in your example. You use php in the same page. Else try to refine your question – Nikos M. May 19 '18 at 19:37
  • Question refined. Please check! – WordCent May 20 '18 at 01:02
  • 1
    @somethingnow, i have updated the answer with an article link which explains ajax in wordpress, you can find more. I cannot provide more information untill you make a specific question after you start implementation. Your question is vague as it is now – Nikos M. May 20 '18 at 18:23