php – How to markup price in Magento2

I want to markup prices but Magento2 provide only discounted option (i don’t know how it is possible!). I’m trying to modify the expression in MagentoCatalogRuleModelIndexer ProductPriceCalculator


case ‘by_percent’:
$productPrice = $productPrice * (1 – $ruleData(‘action_amount’) / 100);

case ‘by_percent’:
$productPrice = $productPrice * (1 + $ruleData(‘action_amount’) / 100);

it should work because the math formula is correct but when i apply the rule in the frontend it show only the regular price. I suppose there is something other that limit the price to be not over the regular price but i’m not able to find and manage it.
the full code is this:



  • Copyright © Magento, Inc. All rights reserved.
  • See COPYING.txt for license details.

namespace MagentoCatalogRuleModelIndexer;


php – Cargar select con dato que viene por json

estoy trabajando con un modal y para cargar los datos lo estoy haciendo a con json, pero mi problema se gestiona en los siguiente, cuando quiero completar mi combobox NO SE COMO dejar marcado el dato que traigo seleccionado. Mi código es el siguiente, en mi blade tengo lo siguiente

    $('.revisar').click(function (event) {
                sit = $(this).attr('href');
                url="{{route('ver', ("id"=>"#REF#"))}}";
                url=url.replace("#REF#", $(this).attr('id'));
                $.getJSON(url, {}, function (data) {
                    $('#modal').attr('action', sit);


                        ar = '<select name="areas" id="areas">' +
                                    $nwarea = AppModelsArea::where('vigencia', '<', 3)->orderBy('id')->get();
                                        @foreach($nwarea as $nwareas)
                                    '<option value="{{$nwareas->id}}" @if(**COMO PONER EL DATO SELECCIONADO QUE TRAIGO EN EL (data.area)**==$nwareas->id) selected  @endif>{{$nwareas->area}}</option>' +


En mi Controlador, estos son los datos que traigo

public function getAspirantes($id){


            $seleccion = Postulante::where('id', '=', $id)->first();

                $commit = true;
                $nombre= $seleccion->nombre_completo;
                $email= $seleccion->email_postulante;
    return response()->json(array("Estado"=>$commit, "id"=>$id, "nombre"=>$nombre, "email"=>$email, "area"=>$area), 200, (), JSON_UNESCAPED_UNICODE);

A través de este dato $('#cbo_area').html(ar); paso a mi modal el combobox, lo cual me hace, pero no que no me trae es el area que tengo guardada en la base de datos y no se como realizar esto, quizas sea una bobada, pero no se me ocurre. También intente poner en mi modal el combobox, pero llego a lo mismo porque no se como seleccionar el area que corresponde, por fa, ayuda

php – How to prevent archive listings from custom taxonomy?

OK, it might seem a bit odd to want to do this but I do have a good reason which would take a while to explain!

Is this possible?

I am assuming the easy way is to hide some HTML via CSS but there must be a tidier method using functions.php?

I am thinking something along this idea:

/* Register template redirect action callback */
add_action('template_redirect', 'meks_remove_wp_archives');
/* Remove archives */
function meks_remove_wp_archives(){
  //If we are on category or tag or date or author archive
  if( is_category() || is_tag() || is_date() || is_author() ) {
    global $wp_query;
    $wp_query->set_404(); //set to 404 not found page

php – What is the common API endpoint architecture in backends?

Hey I always used to create some pretty messy endpoints and I decided that it’s about time to start writing cleaner code, I’ll provide an example of how would I design an endpoint and I’ll be thankful for any insights why is it good or bad practice to do it like this also I’d be more than happy if you provide your own tweaks with explanation why would you do it like that.
Scenario: user post endpoint
Pathname: /api/user
Method: POST

class UserPostEndpoint extends AbstractController
    private UserPostHandlerInterface $handler;
    private SerializerInterface $serializer;

    function __construct(UserPostHandlerInterface $handler, SerializerInterface $serializer)
        $this->handler = $handler;
        $this->serializer = $serializer;

    public function handleRequest(Request $request): Response
        try {
            $userPostRequestDTO = $this->serializer->unserialize($request->getContent(), UserPostRequestDTO::class);
            $response = $this->handler->handle($userPostRequestDTO); // <- ApiSuccessResponse(statusCode = 201)
        } catch(SerializationException $e) {
            $response = new ApiErrorResponse('Invalid request content provided', 400);
        } catch(ApiRequestContentValidationException $e) {
            $response = new ApiErrorReponse($e->getPlainMessage(), 400);
        } catch(Exception $e) {
            $response = new ApiErrorReponse('Internal server error', 500);
        } finally {
            return $response;

Handler would contain some basic things like: invoke createUser in UserFactory, persist the entity with repository.
ApiErrorReponse: message, statusCode
ApiSuccessReponse: UserPostResponseDTO, statusCode(201)
Would you add / change / remove something from the given example to make it more “correct”?
Thanks for the insights

php – Evitar Redondeo Automatico en SQL

Cuento realizo un insert a una tabla de mi base de datos los valores los redondea y quiero evitar eso, necesito que los valores sean guardados como son digitados , las columnas en esta de tipo float(18,2).
y el valor desde php lo paso por la funcion bcdiv para evitar rendondeo… que no estoy tomando en cuenta gracias

$datos = array("Rnc_Empresa_LD" => $Rnc_Empresa_606,
                "id_registro" => $id_registro606,
                "Rnc_Factura" => $Rnc_Factura_606,
                "NCF" => $NCF_606,
                "Nombre_Empresa" => $_POST("Nombre_Suplidor"),
                "NAsiento" => $_POST("NAsiento"),
                "id_grupo" => $idgrupo,
                "id_categoria" => $idcategoria,
                "id_generica" => $idgenerica,
                "id_cuenta" => $idcuenta,
                "Nombre_Cuenta" => $nombrecuenta,
                "Fecha_AnoMes_LD" => $_POST("FechaFacturames_606"),
                "Fecha_dia_LD" => $_POST("FechaFacturadia_606"),
                "id_Proyecto" => $idproyecto,
                "CodigoProyecto" => $codproyecto,
                "debito" => $debito,
                "credito" => $credito,
                "ObservacionesLD" => $ObservacionesLD,
                "Extraer_NAsiento" => $Extraer_NAsiento,
                "Tipo_Transaccion" => $Transaccion_606,
                "Fecha_AnoMes_Trans" => $_POST("FechaFacturames_606"),
                "Fecha_dia_Trans" => $_POST("FechaFacturadia_606"),
                "id_banco" => $id_banco,
                "referencia" => $_POST("Descripcion"),
                "Usuario_Creador" => $_POST("UsuarioLogueado"),
                "Accion" => $Accion);

$respuesta = ModeloDiario::mdllibrodiario($tabla, $datos);

static public function mdllibrodiario($tabla, $datos){

$stmt = Conexion::conectar()->prepare("INSERT INTO $tabla(Rnc_Empresa_LD, id_registro, Rnc_Factura, NCF, Nombre_Empresa, NAsiento, id_grupo, id_categoria, id_generica, id_cuenta, Nombre_Cuenta, Fecha_AnoMes_LD, Fecha_dia_LD, id_Proyecto, CodigoProyecto, debito, credito, ObservacionesLD, Extraer_NAsiento, Tipo_Transaccion, Fecha_AnoMes_Trans, Fecha_dia_Trans, id_banco, referencia, Usuario_Creador, Accion) VALUES (:Rnc_Empresa_LD, :id_registro, :Rnc_Factura, :NCF, :Nombre_Empresa, :NAsiento, :id_grupo, :id_categoria, :id_generica, :id_cuenta, :Nombre_Cuenta, :Fecha_AnoMes_LD, :Fecha_dia_LD, :id_Proyecto, :CodigoProyecto, :debito, :credito, :ObservacionesLD, :Extraer_NAsiento, :Tipo_Transaccion, :Fecha_AnoMes_Trans, :Fecha_dia_Trans, :id_banco, :referencia, :Usuario_Creador, :Accion)");

$stmt ->bindParam(":Rnc_Empresa_LD", $datos("Rnc_Empresa_LD"), PDO::PARAM_STR);
$stmt ->bindParam(":id_registro", $datos("id_registro"), PDO::PARAM_STR);
$stmt ->bindParam(":Rnc_Factura", $datos("Rnc_Factura"), PDO::PARAM_STR);
$stmt ->bindParam(":NCF", $datos("NCF"), PDO::PARAM_STR);
$stmt ->bindParam(":Nombre_Empresa", $datos("Nombre_Empresa"), PDO::PARAM_STR);
$stmt ->bindParam(":NAsiento", $datos("NAsiento"), PDO::PARAM_STR);
$stmt ->bindParam(":id_grupo", $datos("id_grupo"), PDO::PARAM_INT);
$stmt ->bindParam(":id_categoria", $datos("id_categoria"), PDO::PARAM_INT);
$stmt ->bindParam(":id_generica", $datos("id_generica"), PDO::PARAM_STR);
$stmt ->bindParam(":id_cuenta", $datos("id_cuenta"), PDO::PARAM_STR);
$stmt ->bindParam(":Nombre_Cuenta", $datos("Nombre_Cuenta"), PDO::PARAM_STR);
$stmt ->bindParam(":Fecha_AnoMes_LD", $datos("Fecha_AnoMes_LD"), PDO::PARAM_STR);
$stmt ->bindParam(":Fecha_dia_LD", $datos("Fecha_dia_LD"), PDO::PARAM_STR);
$stmt ->bindParam(":id_Proyecto", $datos("id_Proyecto"), PDO::PARAM_STR);
$stmt ->bindParam(":CodigoProyecto", $datos("CodigoProyecto"), PDO::PARAM_STR);
$stmt ->bindParam(":debito", $datos("debito"), PDO::PARAM_STR);
$stmt ->bindParam(":credito", $datos("credito"), PDO::PARAM_STR);
$stmt ->bindParam(":ObservacionesLD", $datos("ObservacionesLD"), PDO::PARAM_STR);
$stmt ->bindParam(":Extraer_NAsiento", $datos("Extraer_NAsiento"), PDO::PARAM_STR);
$stmt ->bindParam(":Tipo_Transaccion", $datos("Tipo_Transaccion"), PDO::PARAM_INT);
$stmt ->bindParam(":Fecha_AnoMes_Trans", $datos("Fecha_AnoMes_Trans"), PDO::PARAM_STR);
$stmt ->bindParam(":Fecha_dia_Trans", $datos("Fecha_dia_Trans"), PDO::PARAM_STR);
$stmt ->bindParam(":id_banco", $datos("id_banco"), PDO::PARAM_STR);
$stmt ->bindParam(":referencia", $datos("referencia"), PDO::PARAM_STR);
$stmt ->bindParam(":Usuario_Creador", $datos("Usuario_Creador"), PDO::PARAM_STR);
$stmt ->bindParam(":Accion", $datos("Accion"), PDO::PARAM_STR);

        return "ok";


        return "error";


    $stmt -> close();
    $stmt = null;

}/* CIERRE funcion*/

php – Erro no JS ao validar cadastro

Boa Tarde pessoal,

Tenho um JS em uma página em PHP que válida se o candidato já se inscreveu com o RG ou CEP, última vez que utilizei essa página foi o ano passado e estava tudo normal, só que agora ao realizar testes para colocar no ar novamente está dando a mensagem de erro que o candidato já se cadastrou mesmo não estando cadastrado, até zerei o Banco de Dados para não ter dúvidas que não está cadastrado, vou colocar a parte do código responsável por esse filtro, você poderiam me dar uma “LUZ”.

parte do JS

$(‘#formCadastro’).on(‘submit’, function (e) {
var formCadastro = $(this),
isValid = formValidate(formCadastro, e);


    if ($('#rg').val() && $('#cep').val() && isValid) {

            url: 'check-rg-cep.php',
            type: 'post',
            data: {
                rg: $('#rg').val(),
                cep: $('#cep').val()
        .done(function(result) {
            if (result == 0) {
            } else {
                alert('Atenção: este aluno já realizou uma inscrição, é permitido apenas uma inscrição por concurso de bolsas.');


Página em php que o JS chama



try {

    $prova1 = 'Bolsas 2021 - 19/09/2020';
    //$prova2 = 'Bolsas 2021 - 19/09/2020';
    //$prova3 = 'Bolsas 2021 - 19/09/2020';

    $conn = new PDO('mysql:host=localhost;dbname=#########', '###########', '#########', array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES "utf8"'));

    //$buscaCadastro = $conn->prepare('SELECT id, celularResponsavel, nascimento, nome, email, endereco, numero, complemento, bairro, cidade, estado FROM tbl_concurso_bolsas WHERE rg = :rg AND cep = :cep AND (prova = :prova1 || prova = :prova2 || prova = :prova3) AND (status LIKE "%PAID" OR status LIKE "%AVAILABLE")');

    $buscaCadastro = $conn->prepare('SELECT id, celularResponsavel, nascimento, nome, email, endereco, numero, complemento, bairro, cidade, estado FROM tbl_concurso_bolsas WHERE rg = :rg AND cep = :cep AND prova = :prova1');
    $buscaCadastro->bindParam(':rg', $rg);
    $buscaCadastro->bindParam(':cep', $cep);
    $buscaCadastro->bindParam(':prova1', $prova1);
    //$buscaCadastro->bindParam(':prova2', $prova2);
    //$buscaCadastro->bindParam(':prova3', $prova3);

    echo $buscaCadastro->rowCount();

} catch (PDOException $e) {
    echo 'ERROR: ' . $e->getMessage();


object oriented – Google People PHP best practise to get OOP

I need to log in users to web app in Javascript and PHP. So I have Javascript interface which send me accessToken to PHP which stores users data to DB and log user in. But the result code does not look like OOP but like a peace of garbage. May be I dont know how to write that code, so the question is if this peace of PHP code is ok or if it is possible to rewrite it to real OOP. Cause OOP exists because of people who use the code. It should make sense for humans. It seems this make sense only for authors of the code.

$code = $_POST('code');

    $client = new Google_Client();
    $client->setAuthConfig(__DIR__ . '/../model/JsonData/GoogleCredentials.json');
    $client->setRedirectUri( self::REDIRECT_URI );

    $accessToken = $client->fetchAccessTokenWithAuthCode( $code );

    $client->setAccessToken( $accessToken );

    $peopleService = new Google_Service_PeopleService( $client );
    $me = $peopleService->people->get('people/me', ('personFields' => 'emailAddresses,names,metadata,coverPhotos'));  // This is extra feature which does not accept spaces....

catch ( Exception $e )
    Debugger::log( $e );
    $this->sendJson( array( 'errCode' => 1, 'error' => 'Log in fails.' ) );

/** @var Google_Service_PeopleService_EmailAddress $email */
foreach ( $me->getEmailAddresses() as $email )
    if ( $email->getMetadata()->getPrimary() ) $user_email = $email->value;  // Oh really? I want to log in user....
/** @var Google_Service_PeopleService_Name $name */
foreach ( $me->getNames() as $name )
    if ( $email->getMetadata()->getPrimary() ) $user_name = $name->displayName;

if ( ! isset( $user_email ) ) $this->sendJson( array( 'errCode' => 0, 'error' => 'Email is required.' ) );
if ( ! isset( $user_name ) ) $this->sendJson( array( 'errCode' => 0, 'error' => 'Name is required' ) );

// Hello ID is missing. How to uniquely identify user?

May be I am wrong but is it possible to write it better way to get relevant data for log in? Where is ID which can uniquely identify user?

Look at this JS interface. This looks like OOP

php – End process for consume

i need help i need a bat or a program and it have to do the next
end a process with the same name but different consume and i cant use the pids ihave to finalize the process with more consume example trash 0,5mb/s
trash 30.2mb/s and i have to suspend this process

php – I would like content on the checkout page for Check Payments to also appear on the Order Received Page

I have created a checkout page with two payment options, Check Payments and Pay with Bitcoin. For the check payments option, I have added the “Pay to” name and address and it appears on the checkout page, when the Check Payment option is checked. When the “Place Order” button is clicked, we go to the Order Received page. I would like the “Pay to” name and address to also appear on the Order Received page as I can see someone clicking the Place Order button before writing down the information. Once clicked, you cannot go back to the checkout page and the “Pay to” information is frustratingly lost. I just don’t know which php file contains the code that renders the “Pay to” information, being a total novice at php and wordpress. Perhaps more importantly, I do not have a strategy for locating the php. Can anyone help?

php – Don’t show attribute image if there is no

I set a custom image role, after uploading and selecting the image as “auszeichnung_1” it will appear on the product page.

However if I do not select an image, I geht on frontend this error:

Fatal error: Uncaught Error: Call to a member function getValue() on null in /var/www/hifistudio/hsstage/app/design/frontend/TemplateMonster/theme007/Magento_Catalog/templates/product/view/auszeichnungen.phtml:13 Stack trace: #0 /var/www/hifistudio/hsstage/vendor/magento/framework/View/TemplateEngine/Php.php(59): include() #1 /var/www/hifistudio/hsstage/vendor/magento/framework/View/Element/Template.php(271): MagentoFrameworkViewTemplateEnginePhp->render(Object(MagentoCatalogBlockProductViewAttributes), '/var/www/hifist...', Array) #2 /var/www/hifistudio/hsstage/vendor/magento/framework/View/Element/Template.php(301): MagentoFrameworkViewElementTemplate->fetchView('/var/www/hifist...') #3 /var/www/hifistudio/hsstage/vendor/magento/framework/View/Element/AbstractBlock.php(668): MagentoFrameworkViewElementTemplate->_toHtml() #4 /var/www/hifistudio/hsstage/vendor/magento/framework/View/Layout.php(557): MagentoFrameworkViewElementAbstractBlock->toHtml() #5 /var/www/hifistudio/hsstage/vendor/magento/framew in /var/www/hifistudio/hsstage/app/design/frontend/TemplateMonster/theme007/Magento_Catalog/templates/product/view/auszeichnungen.phtml on line 13

Can someone help me with the right “if-clause”? I used this code in my phtml:

$_helper = $this->helper('MagentoCatalogHelperOutput');
$_product = $block->getProduct();
$productImageAttr = $_product->getCustomAttribute( 'auszeichnung_1' );
$productImage = $this->helper('MagentoCatalogHelperImage')
->init($_product, 'auszeichnung_1')
<img src="<?php echo $productImage->getUrl() ?>"width="50" alt="<?php echo $block->escapeHtml($productImage->getLabel()) ?>" />