tobiasg
tobiasg

Reputation: 1073

Updating posts from JavaScript in Wordpress

I've written the start of a script that is applied to the edit.php page on the admin area in Wordpress. The script collects information (id, title and a few ACF fields that are shown in the columns using a plugin) and uses this information to generate divs for each of the posts, and then creates a Muuri instance with these new divs.

The idea is that the post list on the front end should be rendered with Muuri, to create a masonry layout. In order to make it easier for the user to set the arrangement and size of each item in the masonry, I want the user to use Muuri with the drag and drop functionality in the admin area, so that they can drag and drop each post and set their positions. I then want to pass the order and the sizes of each post from the admin to the front end.

This is the script that I add to the edit.php page:

    var output = "<div class='grid'>";

    $(window).on("load", function(){
    $("#the-list").find("tr").each(function(index){
        var title = $(this).find(".title").find(".row-title").text();
        var sort = $(this).find(".column-order").text();
        var layout = $(this).find(".column-size").text();
        var id = $(this).attr("id");
        var link = $(this).find(".title").find(".row-title").attr("href");
        var select = "<select class='layout-changer' data-id='" + id +"' style='position:absolute;bottom:0;left:0;'>";
        select += "<option value='layout1'>Layout 1</option>";
        select += "<option value='layout2'>Layout 2</option>";
        select += "<option value='layout3'>Layout 3</option>";
        select += "</select>";
        output += "<div class='item " + layout + "' data-id='" + id +"' data-layout='" + layout + "' data-sort='" + sort + "'><div class='item-content'><div class='my-custom-content'>" + select + "<a href='" + link + "'>" + title + "</a></div></div></div>";
    });

    output += "</div><button class='submitGrid'>Save</button>";

    $(".wrap").append(output);

    var grid = new Muuri('.grid', {
        dragEnabled: true,
        layout: {
            fillGaps: true,
            rounding: false
        },
        sortData: {
            order: function (item, element) {
                return parseFloat(element.getAttribute('data-sort'));
            },
        }
    });

    grid.sort('order');

    $(".layout-changer").change(function(){
        var choice = $(this).find("option:selected").val();
        var parent = $(this).closest(".item");
        var parentEl = $(this).closest(".item")[0];

        parent.removeClass().addClass("item").addClass(choice);
        parent.attr("data-layout", choice);
        grid.refreshItems(parentEl).layout();
        grid.layout();
    })
});

My idea is that I then want to pass properties from the Muuri instance (the id, the order and the CSS class representing the size of each item) to some kind of PHP function that upon clicking a submit button updates each post's ACF fields in the database.

This is the function that I've begun to carve out:

$(document).on("click", ".submitGrid", function(){
        var allItems = grid.getItems();
        var payload = [];
        var item = {};
        for (i = 0; i < allItems.length; i++) {
            item = {
                order: i,
                layout: allItems[i]._element.dataset.layout,
                id: allItems[i]._element.dataset.id.replace(/\D/g,'')
            }
            payload.push(item);
        }
    })

It creates an array containing an object for each item/post in the Muuri grid, where the properties are set to the order of the item using the index of the for loop, and then sets id and layout using data fields that I'm setting on the element when initially loading the page or changing the layout of the grid.

How would I go about sending this information to a PHP function and then update each post in the database with the help of these objects?

Upvotes: 0

Views: 509

Answers (1)

Jamie_D
Jamie_D

Reputation: 999

Send via jQuery ajax function (since that is what you're using)

 $(document).on("click", ".submitGrid", function(){
        var allItems = grid.getItems();
        var payload = [];
        var item = {};
        for (i = 0; i < allItems.length; i++) {
            item = {
                order: i,
                layout: allItems[i]._element.dataset.layout,
                id: allItems[i]._element.dataset.id.replace(/\D/g,'')
            }
            payload.push(item);
        }

        var itemdata = JSON.stringify(payload);
        $.ajax({
            url: "/path/to/phpfile.php",
            type: "POST",
            data: {
              postitems: itemdata
            },
            beforeSend: function() {
            },
            success: function(response) {
              console.log(response);
            }
        });        
  });

POST params in PHP file :

$postitems = $_POST['postitems'];
$postArray = json_decode($postitems);
print_r($postArray);
exit();

Upvotes: 1

Related Questions