A WP Query for Posts and Pages but only returns 1 posts/pages

I’m trying to create a wp query that goes through posts and pages and only returns one (the most recent, being a post or a page). So far, I have this:

$conteudo_complexo = new WP_Query(array(
   'post_type'        => array('post', 'page'),
   'posts_per_page'   => 1,
   'orderby'          => 'date',
   'order'            => 'DESC',
   'meta_key'         => 'tipo_de_destaque_homepage',
   'meta_value'       => 'topoeditorial'
));

This is returning multiple pages…

What I’m looking for is something like: go through posts and pages and return only one post or page with that meta_value, whichever is the most recent one.

Note: The meta_key and meta_value is for custom fields.

Using AJAX to show PHP-rendered pages in JS frontend app and integrate old MPA into SPA

I want to rewrite old PHP website using JS frontend framework. As the PHP web is very large, it is not possible to create APIs and rewrite all the UI at once. Therefore I want the new JS frontend app to provide basic app layout (menu, header etc.) with the possibility to show old PHP-rendered pages in the page content if necessary. (PHP pages would be naturally cut off menu, header etc., as these parts are in the JS app.)

Loading PHP-rendered content into an <iframe> is not a comfortable and secure solution. I rather want to load the HTML content directly into the page with AJAX.

What are the pitfalls of this approach? As for now, I am aware of these:

  1. JS app router should distinguish between pages already implemented in JS framework and other pages which are PHP-rendered. Navigating to PHP pages should invoke AJAX call to corresponding URL and rewrite content with returned HTML.
  2. When PHP page is loaded with AJAX, I should manually load any other resources it needs (JS scripts, CSS styles), for example with $.getScript(). The list of needed resources could even be returned in the AJAX call response.
  3. All links in the PHP-generated content would cause navigation to given URL, which is bad. Clicking on such link should instead invoke JS function, which in turn should call history.pushState() and load page content with AJAX. In the same manner I should rewrite programmatic navigation caused by location.href = '...'.
  4. Submitting a form in PHP-generated content would again cause navigation. I should add submit event handler for every page form. The handler should stop the submitting and send the data with AJAX instead (probably using this solution). HTML from AJAX response page should be displayed in the page content. I should also call history.pushState() in case that form’s action was different from the current request URI or AJAX call has redirected to different request URI.

This solution seems to be one of few possibilities how to integrate new frontend single-page app (SPA) with old backend multi-page app (MPA). Nevertheless, I wasn’t able to find any working recommendable example on the net. Is is better not to try to integrate at all?

(The question is largely framework-agnostic, but I use Vue.js with jQuery.)

Insert data from a mysql table into another with php, skipping the ones already present

Insert data from a mysql table into another with php, skipping the ones already present

Hi everyone, I can’t solve this problem of mine:

I have 2 table:

table_1 (id, cod.products, color, price, id_supplier)

table_2 (id_supplier, cod.products, color, price)

I would like to insert the data of table_2 into table_1 only if id_supplier of table_2 is not present in id_supplier of table1

I tried doing several queries:

with this

    INSERT INTO table_1 (cod.products, color, price, id_supplier) 
SELECT cod.products, color, price, id_supplier FROM table_2

I insert everything without taking into account the id_supplier …

trying where clause doesn’t work …

    INSERT INTO table_1 (cod.products, color, price, id_supplier) 
SELECT cod.products, color, price, id_supplier FROM table_2 
WHERE table_1.id_supplier <> table_1.id_supplier

JavaScript prevent button event on specified conditions

I have a webshop-like shopping cart function. It displayas the products that you have added. You can change the product quantity by clicking on the + and the - buttons.
On button click, an AJAX call will be sent to a PHP file that updates the database so you instantly save the actual quantity.
As you increase or decrease the selected quantity, a counter appears to indicate how many times the original product will be multiplied. You can increase or decrease the quantity between 1 and 30. As you reach for example 1, the counter stops, but the AJAX call will be sent regardless it shouldn’t go below 1.

Preview video

let subt = 30; // The value from PHP after you sent the AJAX call and reloaded the page
document.getElementById("plus").addEventListener("click", () => {
if (document.getElementById("inp").value < 30) {
    document.getElementById("inp").value = Number(document.getElementById("inp").value)+1;
}
    if (document.getElementById("inp").value > 1) {
    /*
        var bsi__data = new FormData(); bsi__data.append("pid", '(product id)'); bsi__data.append("quantity", document.getElementById("inp").value); bsi__data.append("price", "30");
        $.ajax({
            enctype: "multipart/form-data", type: "POST", url: "/assets/php/basket/q__up.php", data: bsi__data, dataType: "json", contentType: false, processData: false,
            success: function(data) { console.log(data); subt += Number('30'); document.getElementById("subtotal").textContent = formatter.format(subt); },
            error: function (data) { console.log("error"); console.log(data); }
        });
        */
        subt += Number('30'); document.getElementById("subtotal").textContent = subt;
        document.getElementById("ind").textContent = "x "+document.getElementById("inp").value;
    }
    if (document.getElementById("inp").value == 1) { document.getElementById("ind").textContent = ""; }
});
document.getElementById("min").addEventListener("click", function dicr () { 
    if (document.getElementById("inp").value > 1) { 
        document.getElementById("inp").value = Number(document.getElementById("inp").value)-1;
    }
    if (document.getElementById("inp").value >= 1) {
        /*
        var bsi__data = new FormData(); bsi__data.append("pid", "(product id)"); bsi__data.append("quantity", document.getElementById("inp").value);
        $.ajax({
            enctype: "multipart/form-data", type: "POST", url: "/assets/php/basket/q__up.php", data: bsi__data, dataType: "json", contentType: false, processData: false,
            success: function(data) { console.log("decr"); subt -= Number(30); document.getElementById("subtotal").textContent = formatter.format(subt); },
            error: function (data) { console.log("error"); console.log(data); }
        });
        */
        
        subt -= Number(30); document.getElementById("subtotal").textContent = subt;
        document.getElementById("ind").textContent = "x "+document.getElementById("inp").value;
    }
    if (document.getElementById("inp").value == 1) { document.getElementById("ind").textContent = ""; }
});
<div>
<span>Product name</span><span id="price">$30</span><span id="ind"></span>
<div>
<span id="plus">+</span>
<input type="number" id="inp" min="1" max="30" value="1" />
<span id="min">-</span><br><br>
<span>Subtotal: $</span>
<span id="subtotal">30</span>
</div>
</div>

I’m try to change the label

How to change the label based on condition?

live change the label if user select a category

        <div class="inside">
          <div class="enter">
            **<label for="price"><?php _e('Price', 'beta'); ?></label>**

            <div class="input-box">
              <?php ItemForm::price_input_text(); ?>
            </div>
          </div>

 $('body').on('click change', 'input[name="catId"], select#catId', function() {
      var cat_id = $(this).val();
      var url = '<?php echo osc_base_url(); ?>index.php';
      var cat = 31;
      var result = '';

if (cat == cat_id){
$(".price").text("Free");
}else{
$(".price").text("Price");
}

Random redirect with the help of PHP [closed]

i am trying to make random redirect using header refresh in PHP. for, some reason i cannot use header location.

The code placed in example.org

$url = array('https://example.com/','https://example.net/');
shuffle($url);
header("refresh: 0;url=$url");

This redirecting to example.org/Array instead of the urls

Laravel – Diference betwen static methods and static instance() method

I am seeing this practice in many Laravel applications, and I don’t know the diferences o the reasons to use this.

Instead of having public static methods in the class, many people code only one static function that retrieves an instance of a class an this instace call the function.

This classes have no properties or anything that is needed to make the functions work, so I do not understand why use this way to work. I think this make code more dificult to read, in many cases.

Example, I see this laravel implementantion:

class MyClass
{
    public static function instance()
    {
        return new MyClass();
    }

    public function myStuff()
    {
        //my stuff
    }
}

//Calling it
MyClass::instance()->myStuff();

I think it would be more readable and same result making all it with static functions, like:

class MyClass
{    
    public static function myStuff()
    {
        //my stuff
    }
}

//Calling it
MyClass::myStuff();

What do you think about this?

same id will show only one time not multiple

Here is my ‘index.blade.php’. I can show all id stored in my database. You can see it in the below image. Where id 1 has two times and id 2 have three times. But I want to keep all id in the database and the same id only once like id 1 will show one time but in the database will have two times and id 2 will show one time but in the database will have three times. How to do id.

enter image description here

I can view all id by doing this to my HomeController.php

public function index()
{
   $data = Score::all();
   return view('home', compact(
      'data'
   ));
}

This is my index.blade.php

@foreach ($data as $key => $row )
   <a class="btn btn-outline-info" >
            <div style="color: #1d2124">{{ $row->match_id }}</div>
   </a>
@endforeach

Get only specific data based on query – Laravel

I am new to Laravel.

I have a table ‘schedules’ with 4 data on it. You’ll notice that 3 out 4 data on the table have same event_staff_id which is id 6 but they have different event dates.
enter image description here

Now what I want to query is like this, if the user inputted 2022-05-29 in the front-end then the return data should be only 1 which is the event_staff_id 7 since that’s the only user without event date that matches to user’s input. Meaning event_staff_id 7 is available to the user.

Hope you can help me on this.
Note that I really don’t have any idea on how to query this that’s why I don’t have code to show to you guys.

Thanks

PHP Array index value

I have a simple question that needs to get an element when selecting that reference ID by an input form. I used the following code to do that.

$id2=$locationProducts[0]->inventory_update_stock_details_id;

But this code outs only the first element always. AS an exmple inventory_update_stock_details_id=36, inventory_update_stock_details_id=36, inventory_update_stock_details_id=36 and so on.

But I needs to select as inventory_update_stock_details_id=35, inventory_update_stock_details_id=345, inventory_update_stock_details_id=2 like that.

inventory_update_stock_details_id included ids as 1,2,3,4,5,……1000

The model as follows :

function getInventoryLocationProducts()
    {
        $this->db->select("*");
        $this->db->from('store_inventory_update_stock_details');
        $this->db->join('store_inventory_item', 'store_inventory_item.inventory_item_id=store_inventory_update_stock_details.inventory','left');
        $this->db->join('store_inventory_location_update', 'store_inventory_location_update.inventory_update_stock_id=store_inventory_update_stock_details.inventory_update_stock_id','left');
        $this->db->join('store_inventory_update_stock', 'store_inventory_update_stock.inventory_update_stock_id=store_inventory_location_update.inventory_update_stock_id','left');
        $this->db->where('store_inventory_item.status=1');
        $this->db->where('store_inventory_update_stock_details.serial_no NOT IN (select serial_no from store_inventory_location_update)');
        
        $q = $this->db->get_where();
        
        if ($q->num_rows() > 0) {
            return $q->result();
        }

        return FALSE;
    }

Controller

public function addInventoryLocation()
{
    $this->checkPermissions('add', 'inventoryLocation');
    $bc = array(array('link' => '#', 'page' => 'Inventory Locations'));
    $meta = array('page_title' => 'Inventory Locations', 'bc' => $bc);
    $this->data['branch'] = $this->Item_model->getBranch();
    $this->data['office'] = $this->Item_model->getOffice();
    $locationProducts = $this->Item_model->getInventoryLocationProducts();
    $this->data['locationProducts'] = $locationProducts;

    $this->data['auto_loc_no'] = $this->Item_model->generate_inv_loc_ref();

    $count = $this->input->post('i');
    
    $str = $this->input->post('auto_loc_no');
    $auto_loc = preg_replace("/[^0-9]{1,4}/", '', $str);
    $this->form_validation->set_rules('branch', 'Branch', 'required');
            
    if ($this->form_validation->run() == true) {
        
        $stock = array(
            
            'office_id' => $this->input->post('office'),
            'branch' => $this->input->post('branch'),
            'l_date' => $this->input->post('l_date'),
            'is_order_no' => $this->input->post('is_order_no'),               
            'loc_no' => $this->input->post('auto_loc_no'),
            'auto_loc_no' => $auto_loc,           
            'user' => ucfirst($this->session->userdata('name')),
            'order_status' => 'locate',
            'status' => 1
        );
        $id = $this->Item_model->addInventoryLocation($stock);
        
                   
    }
    $id2=$locationProducts[0]->inventory_update_stock_details_id;       
    dd($id2);

        if ($this->form_validation->run() == true && $id2 != 0) {
            $count = $this->input->post('i');
            for ($x = 0; $x <= $count; $x++) {
                $details[$x]['inventory_update_stock_id'] = $id2;                    
                $details[$x]['inventory'] = $this->input->post('inventory' . $x);                   
                $details[$x]['serial_no'] = $this->input->post('serial_no' . $x);
                $details[$x]['item_code'] = $this->input->post('item_code' . $x);
                $details[$x]['officer'] = $this->input->post('officer' . $x);
                $details[$x]['qty'] = 1;                    
                $details[$x]['status'] = 1;
                $details[$x]['branch'] = $this->input->post('branch');
            }

        if ($this->Item_model->addInventoryLocationDetails($details)) {
            echo("<meta http-equiv='refresh' content='1'>"); 
            $this->session->set_flashdata('message', 'Successfully Added ..!!');                              
            redirect('item/addInventoryLocation');
        }
    } else {
        
        $this->session->set_flashdata('error', validation_errors());
        $this->render('item/addInventoryLocation', $meta, $this->data);
    }

}

View

<td style="width: 30%">
                                <input type="hidden" name="i" id="i" value="0">
                                <select name="inventory0" id="inventory0" class="form-control select2 inventory-select" required>
                                    <option value=""></option>
                                    <?php
                                    if (!empty($locationProducts)) {
                                        foreach ($locationProducts as $row) {
                                                echo "<option value='".$row->inventory_update_stock_details_id."'> $row->inventory_update_stock_details_id - $row->inventory_item_name</option>";
                                            ?>
                                            
                                           
                                            <?php
                                        }
                                    }

                                    ?>
                                </select>
                            </td>

What can modify my code line to do that. Can anyone help me ?

Add a free product if it is already in WooCommerce cart

I use a code that adds a free product to the cart if the total is equal to or greater than 1500. If the total is less than 1500, then the product is removed.

add_action( 'woocommerce_before_calculate_totals', 'add_free_product_to_cart' );
function add_free_product_to_cart( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    // Settings
    $minimum_amount   = 1500;
    $free_product_id  = 290;

    // Initializing
    $cart_subtotal = 0;
    $cart_items    = $cart->get_cart();

    // Loop through cart items (first loop)
    foreach ( $cart_items as $cart_item_key => $cart_item ){
        // When free productis is cart
        if ( $cart_item['data']->get_id() == $free_product_id ) {
            $free_item_key = $cart_item_key; // Free product found (get its cart item key)

            $cart_item['data']->set_price(0);
        }
        // Get cart subtotal incl. tax and discounts (excluding free product)
        else {
            $cart_subtotal += $cart_item['line_total'] + $cart_item['line_tax'];
        }
    }

    // When cart total is up to the minimum amount, add the free product if not already there
    if ( $cart_subtotal >= $minimum_amount && ! isset($free_item_key) ) {
        $cart_item_key = $cart->add_to_cart( $free_product_id );

        // display notice after removal
        wc_add_notice( __("Thank you! Here's your free product."), 'notice' );
    }
    // if below the minimum, remove the free product
    elseif ( $cart_subtotal < $minimum_amount && isset( $free_item_key ) ) {

        $cart->remove_cart_item( $free_item_key );

        // display notice after removal
        wc_add_notice( sprintf(
           __("Your cart subtotal is less than %s and therefore, the free product was removed."), wc_price($cart_subtotal)
        ), 'notice' );
    }
}

The code works, just one problem. When this product is added to cart by a customer, this product is not added.

How can I make this product be added to cart and if the amount is 1500 or more, then the second free product is added to the first product?

I’ll be glad you helped!

Join elements in SimpleXML (PHP)

Any idea how can join and ID with another set of data and then print out certain information?
I want to print out The name and the country of a user. I am stuck already for a few hours and I would appreciate any help and suggestion!

XML:

<Project>
   <Partner>
      <PartnerRef>1</PartnerRef>
      <DaysNb>40</DaysNb>
   </Partner>
</Project>
<Partners>

 <Partner>
        <Id>1</Id>
        <Name>UNI1</Name>
        <Country>CH</Country>
    </Partner>
</Partners>

php code:

foreach($InfoSystem->xpath('//Project') as $project){
$projectId = $project->Id;
echo $projectId;
$selectedPartner = $project->xpath('//PartnerRef');
echo($selectedPartner);
echo "Title: " . $project->Submission->Title;
echo "<br>";
echo "Acronym: " . $project->Submission->Acronym;
echo "<br>";
echo "Abstract: " . $project->Submission->Abstract->Parag->Fragment;
echo "<br>";
echo $project->Submission->Abstract->List->asXML();
echo "<br>";

foreach($InfoSystem->xpath('//Partner') as $partner){

        if(in_array($partner, $selectedPartner, TRUE)){      
            echo 'Name: ' . $partner->Name;
            echo 'Country: ' . $partner->Country;
        }
   
    

    echo $partner->Id;
   
       
    
}

echo "<br><br>";

}

How do I set count using Mailchimp API PHP client library

I have installed the Mailchimp PHP client library on my web app and want to generate a list of all the tags I have used. The stock code works but seems to be limited to 10 responses. If I use curl instead the library functions I can set the count parameter and get all 25 tags. It doesn’t seem like the library function accepts the count as in input. How can I get more than 10 tags returned using the library?

My working, albeit limited, library code is:

require_once $_SERVER['DOCUMENT_ROOT'] .  '/includes/mailchimp/vendor/autoload.php';

$client = new MailchimpMarketingApiClient();
$client->setConfig([
    'apiKey' => $MC_apiKey,
    'server' => 'us17'
]);
$response = $client->lists->tagSearch($MC_listID);
var_dump($response);

I can get all 25 tags if I use curl url such as this:

$MC_url = 'https://' . $MC_dataCenter . '.api.mailchimp.com/3.0/lists/' . $MC_listID . '/tag-search?count=50';

Many thanks in advance!

Can’t receive email in .iceservers.net

In Email Deliverability I see Problems Exist (SPF、Reverse DNS)
When sending email to user -> recipient reflects spam
Also, I can’t receive emails from outside
My domain is provided by Godaddy
How to solve this error? Thank you