Link background URL with a php call

I’m trying to rewrite the following php code with an element to a element:

Old:

if($attachments) $latest_topic['media'] = '<img class="topic-media-thumbnail odp-mr-2" src="' . wp_get_attachment_image_src($attachments[0]->ID, 'thumbnail')[0] . '" />';

New:

if($attachments) $latest_topic['media'] = '<div style="
                                                            background-image: url('<php wp_get_attachment_image_src($attachments[0]->ID ?>');
                                                            background-size: cover;
                                                            background-position: center;
                                                            background-repeat: no-repeat;
                                                            aspect-ratio: 1/1;">
                                                            </div>';

The problem is that the php tag is being shown as an undefined constant in the following code:
background-image: url(‘<php wp_get_attachment_image_src($attachments[0]->ID ?>’);

Trying to render the old style images into the new div.

What am I doing wrong?

Google AdWords API finally stopped working?

We use AdWords API which was deprecated in April 2022, but carried on working for us.

Well, as of the past few days, it seems to no longer be working.

Coincidentally, we recently updated PHP version on our server to 8.1.11.

I don’t know whether the API has stopped working due to the PHP upgrade or due to the API deprecation. I don’t fully understand the JSON return values we get from creating “new OAuth2TokenBuilder()” and “new AdWordsSessionBuilder()”, but there are lots of NULL values, which indicates a potential problem.

I know that longterm it makes sense to migrate from AdWords API to Ads API. But I’m wondering if there’s a quick fix to get it back working immediately.

Hide Unused Shipping Rates

Trying to emulate Woocommerce code for hiding each unused shipping rate during an order transaction.

WC themselves publish the following php code that hides other shipping rates when the cart subtotal qualifies for free shipping (ie local_pickup and flat_rate are hidden in the cart):

/**
 * Hide shipping rates when free shipping is available.
 * Updated to support WooCommerce 2.6 Shipping Zones.
 *
 * @param array $rates Array of rates found for the package.
 * @return array
 */
function my_hide_shipping_when_free_is_available( $rates ) {
    $free = array();
    foreach ( $rates as $rate_id => $rate ) {
        if ( 'free_shipping' === $rate->method_id ) {
            $free[ $rate_id ] = $rate;
            break;
        }
    }
    return ! empty( $free ) ? $free : $rates;
}
add_filter( 'woocommerce_package_rates', 'my_hide_shipping_when_free_is_available', 100 );

Replacing ‘free_shipping’ with ‘flat_rate’ or ‘local_pickup’ does not produce the same effect?

What am I doing wrong?

Many thanks in advance 🙂

Modifying a cookie to set its path value

Used the answer found here: https://stackoverflow.com/a/49305110/16898548 to help me activate a function if someone’s visited a page for the first time, but I need it to store the cookie path as / regardless of what page they land on, as I only want them to see the popup it generates once per X amount of time. Currently if they visit example.com/shoes, it will set the path to be shoes/, so if they then visit example.com/bags, it will display the popup again.

Full code (Currently learning PHP + JS so am aware there is probably an easier way to do this whole popup, but would like to get full functionality then I’ll look at optimising):

<script>

function setCookie(c_name,value,exdays){var exdate=new Date();exdate.setDate(exdate.getDate() + exdays);var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());document.cookie=c_name + "=" + c_value;}

function getCookie(c_name){var c_value = document.cookie;var c_start = c_value.indexOf(" " + c_name + "=");if (c_start == -1){c_start = c_value.indexOf(c_name + "=");}if (c_start == -1){c_value = null;}else{c_start = c_value.indexOf("=", c_start) + 1;var c_end = c_value.indexOf(";", c_start);if (c_end == -1){c_end = c_value.length;}c_value = unescape(c_value.substring(c_start,c_end));}return c_value;}

checkSession();

function checkSession(){
   var c = getCookie("visited");
   if (c !== "yes") {

        window.addEventListener('load', (event) => {
            var windowSize = $(window).width();
            if (windowSize >= 0) {
            document.getElementById('discountweb').click(); 
            setTimeout(popupstyle, 500); }
        })

    function popupstyle() {

        var list, index;
            list = document.getElementsByClassName("form-bottom");
            for (index = 0; index < list.length; ++index) {
        list[index].setAttribute('style', 'display:none');
        }

        var list, index;
            list = document.getElementsByClassName("form-item");
            for (index = 0; index < list.length; ++index) {
        list[index].setAttribute('style', 'margin-bottom: 0');
        }
        var list, index;
            list = document.getElementsByName("autoform_12");
            for (index = 0; index < list.length; ++index) {
        list[index].setAttribute('action', 'shoes/');
        }
        var list, index;
            list = document.getElementsByClassName("modal__wrap");
            for (index = 0; index < list.length; ++index) {
        list[index].setAttribute('style', 'padding: 0');
        }
      };
    }
   setCookie("visited", "yes", 14, "/", "https://s4.laceandf.netbizpreview.co.uk"); // expire in 1 year; or use null to never expire
}
    </script>
        <div class="discountweb">
    <button class="btn btn-default btn-sm" id="discountweb" data-modal-url="/_process/ajax_fetch_modal_content?type=discount" >
                    Discount Web
                </button>
    </div>
    <style>
            .discountmob {
                display: none;
            }

            .discountweb {
                display: none;
            }

            @media only screen and (max-width: 819px) {
                .popup-img {
                    display: none !important;
                }
                .popup-main {
                    margin: 0 auto !important;
                    width: 100% !important;
                }
                .popup-main img {
                    margin: 0 auto;
                }
                .popup-main h3 {
                    margin-bottom: 0 !important;
                }
            }

            form[name="autoform_10"] {
                margin: 45px 40px;
            }
    </style>

NOTE Noticed if they visit the home page first it will store the path value as / and i will have no issues for the rest of the site. Same for if they visit example.com/shoes then visit example.com, they will see the popup on those 2 pages, but then the cookie path value is stored as / and wont display the popup on the rest of the site (which is exactly what i need)

phpMyAdmin – MySQL import errors

I have a WordPress website (web A) and a staging site (web B) in which I’m working on updates and changes. On web A I receive comments from users, which I would like to export to web B. I understand the right way is through the comments database on phpMyAdmin.

I found this post from CMSMind, in which the process of exporting and then importing comments on phpMyAdmin is thoroughly explained. However, I’ve encountered a couple of issues when importing.

The original comments database originally had this line of code under the SQL tab and it worked fine:

SELECT * FROM `LzlcSCHMcomments` WHERE 1

I tried to do a test by importing a single comment, but some errors were found:

SELECT * FROM `LzlcSCHMcomments` WHERE 1

INSERT INTO `LzlcSCHMcomments` (`comment_ID`, `comment_post_ID`, `comment_author`, `comment_author_email`, `comment_author_url`, `comment_author_IP`, `comment_date`, `comment_date_gmt`, `comment_content`, `comment_karma`, `comment_approved`, `comment_agent`, `comment_type`, `comment_parent`, `user_id`) VALUES
(28814, 5900, 'AUTHOR', 'EMAIL', '', 'IP', '2022-10-18 06:34:30', '2022-10-18 05:34:30', 'COMMENT', 0, '0', 'Mozilla/5.0 (Windows NT 6.1; ) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.72 Safari/537.36', 'comment', 0, 0);

--
-- Índices para tablas volcadas
--

--
-- Indices de la tabla `LzlcSCHMcomments`
--
ALTER TABLE `LzlcSCHMcomments`
  ADD PRIMARY KEY (`comment_ID`),
  ADD KEY `comment_post_ID` (`comment_post_ID`),
  ADD KEY `comment_approved_date_gmt` (`comment_approved`,`comment_date_gmt`),
  ADD KEY `comment_date_gmt` (`comment_date_gmt`),
  ADD KEY `comment_parent` (`comment_parent`),
  ADD KEY `comment_author_email` (`comment_author_email`(10));

--
-- AUTO_INCREMENT de las tablas volcadas
--

--
-- AUTO_INCREMENT de la tabla `LzlcSCHMcomments`
--
ALTER TABLE `LzlcSCHMcomments`
  MODIFY `comment_ID` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=28817;
COMMIT;

/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;

ERROR 1 – Static analysis:

1 error found during analysis. Unexpected conditions order. (near “FROM” at position 9)

ERROR 2 – MySQL said:

#1064 – Something’s wrong in your syntax near ‘INSERT INTO LzlcSCHMcomments (comment_ID, comment_post_ID, `comment_aut…’ on line 3

ERROR 3 –
MODIFY `comment_ID` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=28817; COMMIT;

On this COMMIT there’s an error stating: No operations were started previously (near COMMIT).

This is the first time I work on my databases, so I really appreciate your help. Thanks a lot in advance!

check current route yii2

I just started migrating from laravel to yii2

In Laravel, I had a moment when I checked the current route, and if we are on this page, then we leave only the text, and if not, then we make this text a link

@if(Route::currentRouteName() === 'contact')
  <span class="contact-link active">contact</span>
@else
  <a href="{{ route('contact') }}" class="contact-link">contact</a>
@endif

Now I want to do exactly the same on yii2

With a regular link, everything is clear

<a href="<?= Url::to(['/contact']) ?>" class="contact-link">contact</a>

But how can you check the current page?

Cannot mock partial Log facade in Laravel

I’m trying to mock laravel Log. This is my code:

public function test_process_verify_card()
{
    Log::shouldReceive('error')->once();
    Log::makePartial();
    $class = new MyClass();
    $class->myFunction();
}

This is MyClass look like:

class MyClass
{
    public function __construct()
    {
        $this->logger = Logg::channel('test');
    }

    public function myFunction()
    {
        // ... some logic
        $this->loggger->error('Errror!!');
    }
}

When I run test this test case, it throw error

Call to a member function runningUnitTests() on null

  at vendor/laravel/framework/src/Illuminate/Log/LogManager.php:568

I tried to debug this error by putting dd() in LogManager class

    protected function parseDriver($driver)
    {
        $driver ??= $this->getDefaultDriver();
        dd($this->app()) // <--- This is my code
        if ($this->app->runningUnitTests()) {
            $driver ??= 'null';
        }

        return $driver;
    }

But it show that $this->app is not null.

I’ve tried mock facade Date before and it works fine.

I want to test that myFunction executes logging action. Is this correct way to do it?

Update

I also tried to mock it through partialMock() function:

    public function test_process_verify_card()
    {
        $this->partialMock(Logger::class, function (MockInterface $mock) {
            $mock->shouldReceive('error')->once();
        });
        $class = new MyClass();
        $class->myFunction();
    }

But it still not works, it shows error:

  Method error(<Any Arguments>) from Mockery_0_Illuminate_Log_Logger should be called
 exactly 1 times but called 0 times.

  at vendor/phpunit/phpunit/phpunit:98

Fix encoding from database

from my old project what need to get to new one i need same database records and there all are in latvian language, there is symbols what is not latvian:
Example:

Have NotekÅ«deņu sÅ«knis but need Notekūdeņu sūknis

In database all text that is in latvian is with this symbols, english letters is ok

HAVE  =  NEED
  Ä�  =  ā
  Ä“  =  ē
  Å«  =  ū
  Å   =  ņ
  Ä«  =  ī
  Ä£  =  ģ
  Å¡  =  š
  †Ä· =  ķ

Cant find any solution.
My PHP v8.0 use MySql MariaDB v10.9.3

Maybe only solution is to rewrite all DB records in latvian language or this will e mistake?

AttributeError: ‘str’ object has no attribute ‘qty’

I am trying to post data to api of website using this code:

$url = 'apiurl';
$http = Http::withHeaders(['Content-Type' => 'application/json','Authorization' => 'token mytoken','Accept' => 'application/json'])->post($url, [
            "doctype"=> "Sales",
            "customer"=> "Dummy",
            "docstatus" => 0,
            "title"=> "title",
            "contact_display"=> "Dummy",
            "currency"=> "PHP",
            "order_type"=> "Sales",
            "delivery_date"=> "2022-10-12",
            "items" => [
                "item_code"=> "it",
                "item_name"=> "item",
                "qty"=> 1,
                "rate"=> "10.00",
                "doctype"=> "Sales Item",
                "docstatus"=> "0"
                
            ],
        ]);

But I keep getting this error:

{"exception":"AttributeError: 'str' object has no attribute 'qty'","exc":"["Traceback (most recent call last):\n File \"apps/frappe/frappe/app.py\", 

How to eliminate a value from for loop result that exist in database in codeigniter

I am writing a script to eliminate a value from for loop which already exist in my database. Here’s the code I tried:

    $capacity;
    $builder = $this->db->table('tblcapacity');
    $builder->select('Capacity');
    $builder->WHERE('vesselID',$vessel)->WHERE('Seat_Type',$seats);
    $cap = $builder->get();
    foreach($cap->getResult() as $row)
    {
        $capacity = $row->Capacity;
    }
    $list = array();
    for($x=1;$x<=$capacity;$x++)
    {
        $seat = str_pad($x, 3, '0', STR_PAD_LEFT);
        $list[] = $seat;
    }
    $seat_num;$result;
    $builder = $this->db->table('tbltransaction');
    $builder->select('SeatNumber');
    $builder->WHERE('Seat_Type',$seat)->WHERE('ID',$depart)->WHERE('TrxnDate',$date);
    $datas = $builder->get();
    foreach($datas->getResult() as $row)
    {
        $seat_num = $row->SeatNumber;
    }
    $Obj = json_decode(json_encode($list));
    foreach($Obj as $objects)
    {
        echo "<option>".$objects."</option>";
    }

The script able to generate seat number depends to the capacity but unable to remove the existing seat value. Hope you could help me. Thanks in advance

syntax error, unexpected variable “$stmt” php sql query

This snippet works to secure SQL query and pass queries to the database, I have had this snippet work before but somehow it does not now. This part of the whole code I believe is self-contained so the error shouldn’t be outside of this area, I hope you can spot the error that I could not on the (userquery)$stmt = $conn ->prepare($sql);

if($location == 'names') {



                (userquery)$stmt = $conn->prepare($sql);



                $stmt->bind_param('ss', $n1,$n2);



                $result = $stmt->execute();



                $query = $stmt->get_result();



real_escape_string() Function

$name = mysqli_real_escape_string($con, $_POST['name']);





                include 'includes/userquery.php';



            }

Restricts which items can be added to cart based on whether a specific item in a category is already in the cart or being added to the cart

I would like to restrict other products from being added in the cart if a specific product in a category id 154 is already in the cart. How to change the product id to category id in the below code?


  function example_cart_filtering( $passed_validation, $product_id ) {

    // ID of the trial product
    // list of products
    
    $trial_product_id = 10383;
    //$category = '154';

    // If cart is empty, no need for additional validation.
    if ( WC()->cart->is_empty() ) {
        return $passed_validation;
    }

    // If trial product is being added to cart, existing products should be removed.
    if ( $trial_product_id === $product_id ) {
        $notice = sprintf(
            // Translators: Placeholder is for cart url.
            __( 'Hampers can not be purchased with other products. Please empty your <a href="%s">existing cart</a>.' ),
            esc_url( wc_get_cart_url() )
        );
        wc_add_notice( $notice, 'notice' );
        return false;
    }

    // If trial product is in cart, additional products should not be added.
    $products = WC()->cart->get_cart_contents();
    foreach ( $products as $product => $values ) {
        $product_id = $values['data']->get_id();
        if ( $trial_product_id === $product_id ) {
            $notice = sprintf(
                // Translators: Placeholder is for cart url.
                __( 'Hampers can not be ordered with other items.<br> Please remove the Hamper products from <a href="%s">your cart</a> if you wish to make other purchases.' ),
                esc_url( wc_get_cart_url() )
            );
            wc_add_notice( $notice, 'notice' );
            return false;
        }
    }

    // Trial Product is not in cart or being added.
    return $passed_validation;

}
add_filter( 'woocommerce_add_to_cart_validation', 'example_cart_filtering', 100, 2 );

laravel 8 relationship with nested query not working

Why when using an internal query for relationships it doesn’t work like this.

 Customer::where('contract_id',$request->contract_id)->with(
      [
          'claims'=> function ($q){
                $q->select('id');
            }
      ])->get();

, when you cancel the function, it works internally

 Customer::where('contract_id',$request->contract_id)->with( ['claims'])->get();