woocommerce offtopic – Hook that specifies an action code is only applied to a certain product category slug or product ID number

I have some code running globally on my website that places a notation between my product variation and the add to cart button, however, I do not want it to appear globally, but rather only applied to particular Product Category Slugs or Product ID’s.

I’ve tried what seems like a million different things to make it happen, but the code still appears on every product/category I have published.

The code is as follows:

add_action( 'woocommerce_before_add_to_cart_button' , 'aj_add_below_prod_var', 5 );
 
function aj_add_below_prod_var() {
    echo '<span style="font-weight:bold; color:red;"> Quantities are in HALF YARD increments. (1=1/2 Yard, 2=1 Yard, 3=1 1/2 Yards, etc.) </span>';
 }

Can anyone help? I only want it to appear on the products that are in the
category slug ‘pre-order-fabrics’

Thanks so much for any assistance! I posted over in the WordPress.org/support/plugin/woocommerce group and they referred me over here.

loop – Adding $args to wp_schedule_event() causes hook to add infinitely to WP Cron

I’m working on calling my function from server cron instead of using WP Cron. The problem I occured is simple. When I add $args to wp_schedule_event() method, and check for the successfull addition in plugin called WPCrontrol, i see that on every page refresh the same hook is added over and over again.

I have a function called generateXlsxFile() to whom I need to pass one variable boolean(true).

Steps I tried so far:

1) if (!wp_next_scheduled('generateXlsxFile')){ wp_schedule_event(time(), 'daily', 'generateXlsxFile', array(true); }
2)add_action('generateXlsxFile', 'generateXlsxFile', 10 , 1);

If I don’t use array(true) in wp_schedule_event(), everything works as intended. If I addarray(true), it starts looping on adding hook over and over again. I have no idea what is causing this, because without arguments another wp_schedule_event() method is working fine.

Any lead would be appreciated. Thanks!

React Native useState Hook actualizar estados entre 2 distintos archivos

Tengo un hook que en teoria permite la actualización de un estado en dos distintos archivos para mostrar distintas pantallas, pero cuando lo utilizo no funciona.

Mi código cuenta en 3 archivos:

useChangeScreen

en este archivo declaro los useState para poder definir que pantalla se muestra:

export const useChangeScreen = () => {
    ...
      const (homeActivo, setHomeActivo) = useState(false);
      const (searchActivo, setSearchActivo) = useState(true);
      const (profileActivo, setProfileActivo) = useState(false);
    ...
      const irAHome = () => {
        setHomeActivo(true);
        setSearchActivo(false);
        setProfileActivo(false);
      };
      const irASearch = () => {
        setHomeActivo(false);
        setSearchActivo(true);
        setProfileActivo(false);
      };
      const irAProfile = () => {
        setHomeActivo(false);
        setSearchActivo(false);
        setProfileActivo(true);
      };
    ...
    return  {
      homeActivo,
      searchActivo,
      profileActivo,
      irAHome,
      irASearch,
      irAProfile
    }
}
navigation

En este archivo cree el componente que en teoria permite el pasar de una pagina a otra:

export const Nav = () => {
      const {
        irAHome,
        irANotifi,
        irAProfile,
        irASearch
      } = useChangeScreen();
    ...
    return (
    ...
    <TouchableOpacity onPress={irAHome}>
    ...
    <TouchableOpacity onPress={irASearch}>
    ...
    <TouchableOpacity onPress={irAProfile}>
    ...
    )
    }

y por ultimo el archivo :

ScreenController

donde llamo las pantallas para que se muestren segun el estado de las variables en useChangeScreen

export const ScreenController =() => {
  const {
    homeActivo,
    searchActivo,
    profileActivo,
  } = useChangeScreen();
...
return(
...
      {homeActivo ? (
        <HomeScreen />
      ) : searchActivo ? (
        <SearchShopsScreen />
      ) : profileActivo ? null : null}
...
)
}

reactjs – How to fix missing dependency warning when using non-existent value as a parameter with useEffect React Hook?

Using React 17.0.2, I get this error when trying to make universal fetch(snapshot) function

React Hook useEffect has a missing dependency: 'id'. Either include it or remove the dependency 
array  react-hooks/exhaustive-deps

My code

const useSnapshot = (collection, id) => {
...
useEffect(() => {
    ...
        id ? setData((items(id))) : setData(items);
    });
}, (collection, id));
return { data, isPending, error };
};

As I’m concern the problem is covered in fact that id sometimes can be undefined
It’s neccessary to get access not only to the list, but also to each element forwarding id.

Please, help me solve this problem 🙏

8 – How do I add a class to a row in a hook?

I am building a view on my website that lists all currently pending user registrations. (They need to be approved by administrators). I also have a taxonomy that lists ‘banned’ names. The view lists the users username, email, discord name and twitch handle. I am trying to build a feature that takes any of those fields, and compares them to the ‘banned’ names list, and if a match is found on any or all of the fields, it adds a special class to the views row.

I can’t find the appropriate hook to tie into that allows me to check these values, but also set a new style/class on the row if a match is found. I already have a function that takes the appropriate value and compares it to the taxonomy and returns a result, but I am not sure what hook to place this function in so that I can do if, for example:

MatchFound() goes through each provided value in the array, and if a match is found returns TRUE, or FALSE if not found at all.

$search = ('name','email','discord','twitch');

if (MatchFound($search)) {
  'return flagged style for row'
}

Is there anybody that could help me?

javascript – How to refactor current context into useCallback hook

I have done with ModalPicker component functionality but I want to avoid unnecessary re-renders in my current code. For the sake of simplicity, I removed some irrelevant code.

// app/components/Home.js

import ModalPicker from './ModalPicker';
import FloatingButton from './FloatingButton';

const Home = () => {
  const (modalVisible, setModalVisible) = useState(false);
  const changeModalVisibility = (bool) => {
    setModalVisible(bool);
  };

  return (
    <SafeAreaView>  
      <FloatingButton
        icon='funnel-outline'
        color='white'
        onPress={() => changeModalVisibility(true)}
      />
      <Modal
        transparent={true}
        animationType='fade'
        visible={modalVisible}
        onRequestClose={() => changeModalVisibility(false)}
      >
        <ModalPicker
          changeModalVisibility={changeModalVisibility}
          setData={setData}
        />
      </Modal>
    </SafeAreaView>
  );
};

export default Home;

The complete version can be found here: Home.js

How can I refactor changeModalVisibility into useCallback hook?

enter image description here

Custom hook after user successfully verifies email

Can anyone help me creating a function that I could use for the following scenario:

Basically I am trying to create a register form that has a hidden custom field with value of a post ID and store it under user custom field “abc”.

Now after user has successfully registered and completes email verification I want to run a code which transfer post (using that id) to his new account. (Change of owner of that post)

For better understanding, we have a bunch of companies listed on our website which we want to allow owners of that companies to claim their company listing.

We have successfully able to create hidden custom field and its saving the post id to user custom field abc. Now can anyone help us moving that post using post id to new owner?

Plugins we are using here are:

Advanced custom fields
WP user frontend

Thanks!

entities – Can not access compound field value with insert hook

I want to store some of my compound_field values to custom table with insert/update hook. The insert, and updating without the compund field works, but for unknown reason the compound field value is not fetched with insert or update hook.

field code field machine name field_compound

public static function propertyDefinitions(StorageDefinition $storage) {

    $properties = ();

    $properties('description') = DataDefinition::create('string')
      ->setLabel(t('Description'));

    $properties('sidebar_title') = DataDefinition::create('string')
      ->setLabel(t('Sidebar Title'));     
      
    $properties('thumb_url') = DataDefinition::create('string')
      ->setLabel(t('Thumb Url'));  
    
    $properties('article_url') = DataDefinition::create('string')
      ->setLabel(t('Article Url'));
    
    return $properties;
  }

The insert hook code

<?php
use DrupalnodeNodeInterface;
use DrupalCoreDatabaseDatabase;
/**
 * Implements hook_node_insert().
 */

function stackrecom18_node_insert(NodeInterface $node){
  
  $node_id = $node->id();
  $node_title = $node->getTitle();
  $sidebar_title = $node->get('field_compound')->getValue()(1)('value');
  
  if($node->getType() == 'article'){

    $values = Drupal::database()->select('node_detail')
                ->fields('node_detail')
                ->condition('nid', $node_id)
                ->execute()
                ->fetchField();
                                
    $node_exists = !empty($values);

    if($node_exists == FALSE){
      Drupal::service('database')->insert('node_detail')
        ->fields(array('nid' => $node_id, 'title' => $node_title, 'side_title' => $sidebar_title))
        ->execute();
      Drupal::logger('stackrecom18')->notice('inserted'); 
        
    } 
  }
}

The only problem here is, compound field(machine name: field_compound) 2nd value can not accessed, so when the insert query is run with node save, I get a error, upon inspection from(admin/reports/dblog it shows :db_insert_placeholder_2) => or third item has no value or blank(or NULL).

Which signifies, the $sidebar_title is getting NULL or getting no values returned from the compound field.

Please do not delete/close this, I am searhcing all over internet, but
still can not find anything. If I find anything suitable answer, I
will delete this question.

entities – can not get compound field value for insert hook

I am trying to insert my compound field(named compound as well, machine name: field_compound), it has multiple fields inside it.

However, I want to get one of the value, when node is inserted with hook_node_insert, but I am not able to get compound field value.

$sidebar_title = $node->get('field_compound')(1)->value;

For one of the value(2nd value of the compound field, I am using the above code).

My Full insert hook code :

<?php
use DrupalnodeNodeInterface;
use DrupalCoreDatabaseDatabase;
/**
 * Implements hook_node_insert().
 */

function stackrecom14_node_insert(NodeInterface $node){
  if($node->getType() == 'article'){

    $node_id = $node->id();
    $node_title = $node->getTitle();
    $sidebar_title = $node->get('field_compound')(1)->value;
    $connection = DrupalCoreDatabaseDatabase::getConnection();
    
    $values = Drupal::database()->select('node_detail')
                ->fields('node_detail')
                ->condition('nid', $node_id)
                ->execute()
                ->fetchField();
                                
    $node_exists = !empty($values);

    if($node_exists == FALSE){
      $connection->insert('node_detail')        
        ->fields(array('nid' => $node_id, 'title' => $node_title, 'side_title' => $sidebar_title))
        ->execute();
      Drupal::logger('stackrecom14')->notice('inserted'); 
        
    } 
  }
}

source code

  1. the compound field minimal example module GitHub link
  2. the hook_node_insert module minimal example module GitHub link

functions – Access category within rss2_head hook?

Can I access the current category of a category feed with the rss2_head hook to add for example itunes tags?

Lets say I have wordpress.com/catx/feed I want to get acf field elements associated with this specific category.

Here is what I am trying to accomplish:

function itunes_head() {
        $category = get_the_category();
        $categories = get_category();
        global $post;
        var_dump($categories);
        echo print_r($post);
        echo $categories;
        echo $category;
}
add_filter( 'rss2_head', 'itunes_head' );

I am assuming that I somehow can retrieve the catx category here?