PHP-API (WordPress): verschil tussen versies

Uit De Vliegende Brigade
Ga naar: navigatie, zoeken
(apply_filters())
(media_image_sideload (function))
 
Regel 258: Regel 258:
 
* [[Afbeeldingen & automatisering (WordPress)]]
 
* [[Afbeeldingen & automatisering (WordPress)]]
  
== media_image_sideload (function) ==
+
== media_sideload_image() ==
  
 
Download an image from the specified URL and attach it to a post.
 
Download an image from the specified URL and attach it to a post.

Huidige versie van 8 jun 2019 om 09:14

  • Dit artikel is een naslagwerk voor alles, gerelateerd aan de PHP-API. Daarom zijn bronnen in de hoofdstukken zelf toegevoegd, en niet aan het eind van het artikel
  • Inclusief API-gerelateerde zaken van plugins (bv. WooCommerce): Te veel werk om dat gescheiden te houden.

add_action()

Hooks a function on to a specific action.

Description

[1]:

Actions are the hooks that the WordPress core launches at specific points during execution, or when specific events occur. Plugins can specify that one or more of its PHP functions are executed at these points, using the Action API.

Parameters

$tag: (string) (Required) The name of the action to which the $function_to_add is hooked.

$function_to_add: (callable) (Required) The name of the function you wish to be called.

$priority: (int) (Optional) Used to specify the order in which the functions associated with a particular action are executed. Lower numbers correspond with earlier execution, and functions with the same priority are executed in the order in which they were added to the action.

Default value: 10

$accepted_args: (int) (Optional) The number of arguments the function accepts.

Default value: 1

Return

(true) Will always return true.

apply_filters()

download_url()

get_categories

Voorbeeld - Ik snap alleen niet waarom in het laatste voorbeeld ('taxonomy' => 'product_cat') niet alle categorieën worden benoemd:

###############################################################
# List all categories
###############################################################
#
# Zonder argument
######################################
#
print("\n\nZonder argument:\n");
print_r(get_categories());


# Met 'orderby' & zonder 'parent'
######################################
#
print("\n\nMet alleen 'orderby' & 'parent':\n");

$cat_array=array
(
	'orderby'	=> 'name',
	'parent'	=> 0
);
print_r(get_categories($cat_array));


# Taxonomy = category
####################################################
#
print("\n\nTaxonomy = category\n");

$cat_array=array
(
	'taxonomy'	=> 'category'
);
print_r(get_categories($cat_array));


# Taxonomy = product_cat
####################################################
#
print("\n\nTaxonomy = product_cat\n");

$cat_array=array
(
	'taxonomy'	=> 'product_cat'
);
print_r(get_categories($cat_array));
Zonder argument:
Array
(
    [0] => WP_Term Object
        (
            [term_id] => 1
            [name] => Geen categorie
            [slug] => geen-categorie
            [term_group] => 0
            [term_taxonomy_id] => 1
            [taxonomy] => category
            [description] => 
            [parent] => 0
            [count] => 1
            [filter] => raw
            [cat_ID] => 1
            [category_count] => 1
            [category_description] => 
            [cat_name] => Geen categorie
            [category_nicename] => geen-categorie
            [category_parent] => 0
        )

)


Met alleen 'orderby' & 'parent':
Array
(
    [0] => WP_Term Object
        (
            [term_id] => 1
            [name] => Geen categorie
            [slug] => geen-categorie
            [term_group] => 0
            [term_taxonomy_id] => 1
            [taxonomy] => category
            [description] => 
            [parent] => 0
            [count] => 1
            [filter] => raw
            [cat_ID] => 1
            [category_count] => 1
            [category_description] => 
            [cat_name] => Geen categorie
            [category_nicename] => geen-categorie
            [category_parent] => 0
        )

)


Taxonomy = category
Array
(
    [0] => WP_Term Object
        (
            [term_id] => 1
            [name] => Geen categorie
            [slug] => geen-categorie
            [term_group] => 0
            [term_taxonomy_id] => 1
            [taxonomy] => category
            [description] => 
            [parent] => 0
            [count] => 1
            [filter] => raw
            [cat_ID] => 1
            [category_count] => 1
            [category_description] => 
            [cat_name] => Geen categorie
            [category_nicename] => geen-categorie
            [category_parent] => 0
        )

)


Taxonomy = product_cat
Array
(
    [6] => WP_Term Object
        (
            [term_id] => 29
            [name] => Bosch
            [slug] => bosch
            [term_group] => 0
            [term_taxonomy_id] => 29
            [taxonomy] => product_cat
            [description] => 
            [parent] => 0
            [count] => 29
            [filter] => raw
            [meta_value] => 
            [cat_ID] => 29
            [category_count] => 29
            [category_description] => 
            [cat_name] => Bosch
            [category_nicename] => bosch
            [category_parent] => 0
        )

    [57] => WP_Term Object
        (
            [term_id] => 15
            [name] => Uncategorized
            [slug] => uncategorized
            [term_group] => 0
            [term_taxonomy_id] => 15
            [taxonomy] => product_cat
            [description] => 
            [parent] => 0
            [count] => 672
            [filter] => raw
            [meta_value] => 
            [cat_ID] => 15
            [category_count] => 672
            [category_description] => 
            [cat_name] => Uncategorized
            [category_nicename] => uncategorized
            [category_parent] => 0
        )

)

get_term()

Let op: get_term retourneert een object, niet een array. Voorbeeld:

$blub = get_term_by('name', 'Merk', 'product_cat');
echo $blub -> term_id."\n";

Zelfde voorbeeld, nu in één statement:

echo get_term_by('name', 'Merk', 'product_cat') -> term_id;

And now we're playing with power:

wp_delete_term(get_term_by('name', 'Merk', 'product_cat') -> term_id, "product_cat");

media_handle_sideload (function)

[2]: Handle sideloads, which is the process of retrieving a media item from another server instead of a traditional media upload. This process involves sanitizing the filename, checking extensions for mime type, and moving the file to the appropriate directory within the uploads directory.

media_sideload_image()

Download an image from the specified URL and attach it to a post.

register_taxonomy (functie)

Dit is het gebruikelijke commando om een nieuwe taxonomie aan te maken. Het lijkt echter niet te werken voor WooCommerce Attribute-taxonomieën.

set_post_thumbnail (function)

update_post_meta (function)

update_post_meta wordt gebruikt om custom fields te updaten. Voorbeeld [3]:

update_post_meta( $new_post_id, '_stock_status',    'instock');
update_post_meta( $new_post_id, '_weight',          "0.06" );
update_post_meta( $new_post_id, '_sku',             "skutest1");
update_post_meta( $new_post_id, '_stock',           "100" );
update_post_meta( $new_post_id, '_visibility',      'visible' );

woocommerce_template_loop_add_to_cart

wpdb (klasse)

wpdb is een klasse met functies om te interacteren met de database. Het is een laag dieper dan de gebruikelijke PHP-functies.

wp_delete_category

wp_delete_term

Voorbeelden

Simpel:

wp_delete_term(get_term_by('name', 'Merk', 'product_cat') -> term_id, "product_cat");


Geavanceerd:

#####################################################
# Remove previously created term
#####################################################
#
# Remove "Merk"
###############################
#
$i = get_term_by('name', 'Merk', 'product_cat');

if ($i<>false)
{
	# Delete term
	#############
	#
	wp_delete_term(get_term_by('name', 'Merk', 'product_cat') -> term_id, "product_cat");
	echo("Taxon 'Merk' deleted\n");
}
else
{
        # Do nothing
        ############
        #
	echo("Taxon 'Merk' doesn't exit - Nothing deleted\n");
}

Bronnen

wp_insert_term

Gebruik wp_insert_term om een taxon toe te voegen aan een taxonomie. Bruikbaar voor in ieder geval alle catalog-taxonomieën, waaronder WooCommerce product_cat-taxonomieën en WooCommerce attribuut-taxonomieën.

Parameters & arguments

[4]:

wp_insert_term( $term, $taxonomy, $args = array() );

   $term

      * The term to be inserted or updated
      * Kan zowel een string als een integer zijn
      * Default: None

   $taxonomy

      * De naam van de betreffende taxonomie
      * String
      * Default: None

   $args = array()

      * Array of string
      * Default: None

        'alias_of'    (string, optional):  The slug of the taxon of which this is an alias
        'description' (string, optional):  Omschrijving van de taxon - Voor taxonpagina's?
        'parent'      (numeric, optional): term_id van de parent. '0' voor geen parent
        'slug'        (string, optional):  slug for this term.

If 'slug' argument exists then the slug will be checked to see if it is not a valid term. 
If that check succeeds (it is not a valid term), then it is added and the term id is given. 
If it fails, then a check is made to whether the taxonomy is hierarchical and the parent 
argument is not empty. If the second check succeeds, the term will be inserted and the term 
id will be given. If the slug argument is empty, then it will be calculated from the term 
name.

De velden die horen bij 'taxon-pagina's' aka 'taxon-archive-pages' worden niet verwerkt door deze functie. Als je ze toevoegt aan de array, worden ze genegeerd. Voorbeeld:

$term="Merk";
$taxonomy="product_cat";
$description="Om welk merk electrisch handgereedschap gaat het?";
$parent=0;
$slug="merk";
$array = array
(
   'description'  => $description, 
   'parent'       => $parent, 
   'slug'         => $slug,
   'blub'         => 'dit wordt genegeerd', # Niet-bestaande termen worden genegeerd
   'thumbnail'    => 'dit wordt genegeerd', # Niet-bestaande termen worden genegeerd
   'display_type' => 'dit wordt genegeerd'  # Niet-bestaande termen worden genegeerd
);

$term_id_merk = wp_insert_term($term, $taxonomy, $array)['term_id'];

echo("Taxon 'Merk' created with id $term_id_merk\n");

Return values

[5]:

(array|WP_Error) 
The Term ID and Term Taxonomy ID. (Example: array('term_id'=>12,'term_taxonomy_id'=>34))

Je kunt dus twee totaal verschillende soorten output verwachten:

  • Gelukt? → Array met term_id & term_taxonomy_id
  • Niet gelukt? Een string met een foutmelding.

Als je de output van deze functie verwerkt, is het daarom vaak noodzakelijk dat je eerste verifiëert of de output een array of een string is.

wp_set_object_terms

[6]:

  • Relates an object (post, link etc) to a term and taxonomy type (tag, category, etc)
  • It creates the term and taxonomy relationship if it doesn't already exist
  • A relationship means that the term is grouped in or belongs to the taxonomy. A term has no meaning until it is given context by defining which taxonomy it exists under.

Gebruik

wp_set_object_terms( $object_id, $terms, $taxonomy, $append );

Parameters

  • $object_id (integer) - The id of the object to relate
  • $terms (array, integer or string) - The slug or term_id of one or more taxons
  • $taxonomy (array or string) - Name of the taxonomy system, like category, product_cat, pa_brand, etc.
  • $append (boolean) - If true, the terms will be added to the taxonomy. If false, existing terms will be updated (default)

Output

Mixed:

  • (array) An array of the terms ( as term_taxonomy_ids ! ) affected if successful
  • (array) An empty array if the $terms argument was NULL or empty - successmessage for the removing of the term
  • (WP_Error) The WordPress Error object on invalid taxonomy ('invalid_taxonomy').
  • (string) The first offending term if a term given in the $terms parameter is named incorrectly. (Invalid term ids are accepted and inserted).

Zie ook

Bronnen

Zie ook

Bronnen