PHP-API (WordPress): verschil tussen versies

Uit De Vliegende Brigade
Naar navigatie springen Naar zoeken springen
Regel 1: Regel 1:
 
* Dit artikel is een naslagwerk voor alles rondom de PHP-API. Daarom zijn bronnen in de hoofdstukken zelf toegevoegd, en niet aan het eind van het artikel
 
* Dit artikel is een naslagwerk voor alles rondom de PHP-API. Daarom zijn bronnen in de hoofdstukken zelf toegevoegd, en niet aan het eind van het artikel
* Inclusief plugins (bv. WooCommerce): Te veel werk om dat gescheiden te houden.
+
* Inclusief plugins (bv. WooCommerce): Te veel werk om dat gescheiden te houden
 +
* Inclusief functionaliteiten itt. functies - Ik heb geen zin om dat in een apart artikel onder te brengen.
  
 
== add_action() ==
 
== add_action() ==

Versie van 26 jul 2021 16:44

  • Dit artikel is een naslagwerk voor alles rondom de PHP-API. Daarom zijn bronnen in de hoofdstukken zelf toegevoegd, en niet aan het eind van het artikel
  • Inclusief plugins (bv. WooCommerce): Te veel werk om dat gescheiden te houden
  • Inclusief functionaliteiten itt. functies - Ik heb geen zin om dat in een apart artikel onder te brengen.

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_field() - ACF

Lees de waarde in het gegeven veld in de gegeven post (of anders de actieve post).

Voorbeeld (feb. 2020)

###############################################################
# Load libraries
###############################################################
#
echo "Load libraries...\n";
#
require_once($site_path . "/wp-load.php");

echo "Load libraries... Done\n";

###############################################################
# get_field - Read something
###############################################################
#
echo "get_field...\n";

$retour = get_field("brands_kind", 510);
print_r($retour);

echo "get_field... Done\n";

Opmerkingen:

  • Zonder post-id deed-ie 't niet
  • require_once($site_path . "/wp-load.php"); is voldoende. Je hoeft dus niet apart een ACF-bibliotheek aan te roepen ofzo.

Bronnen

get_field_objects() - ACF

Voorbeeld februari 2020: Data importeren in knoppenbalk:

###############################################################
# get_field_objects
###############################################################
#
$retour = get_field_objects(510);

echo '\n';
print_r($retour);
echo '\n';

met dit als een deel van de uitvoer:

Array
(
    [brands_kind] => Array
        (
            [ID] => 0
            [key] => field_5de8cba942c58
            [label] => Brands: kind
            [name] => brands_kind
            [prefix] => acf
            [type] => select
            [value] => show_more_block
            [menu_order] => 0
            [instructions] => 
            [required] => 0
            [id] => 
            [class] => 
            [conditional_logic] => 0
            [parent] => group_5d4d3d8d95baa
            [wrapper] => Array
                (
                    [width] => 
                    [class] => 
                    [id] => 
                )

            [choices] => Array
                (
                    [regular_block] => Regular block
                    [show_more_block] => Show more block
                )

            [default_value] => Array
                (
                    [0] => regular_block
                )

            [allow_null] => 0
            [multiple] => 0
            [ui] => 0
            [return_format] => value
            [ajax] => 0
            [placeholder] => 
            [_name] => brands_kind
            [_valid] => 1
        )

    [regular_block] => Array
        (
            [ID] => 0
            [key] => field_5de8cc2942c5a
            [label] => Regular block
            [name] => regular_block
            [prefix] => acf
            [type] => clone
            [value] => Array

get_field_object() - ACF

Voorbeeld (feb. 2020):

###############################################################
# Read something
###############################################################
#
echo "Read something...\n";

print_r(get_field("brands_kind", 510));
echo "\n";
print_r(get_field_object("brands_kind", 510));
echo "\n";
echo "\nRead something... Done\n";

Wellicht handig om de key te achterhalen (field_...-velden)

get_page_by_title()

Voorbeeld feb. 2020 - Automatiseren van button bar's:

echo "get_page_by_title...\n";

$retour = get_page_by_title("test-page_03");
echo "\n";
print_r($retour);
echo "\n";

echo "get_page_by_title... Done\n";

Output:

WP_Post Object
(
    [ID] => 700
    [post_author] => 2
    [post_date] => 2020-02-04 14:44:01
    [post_date_gmt] => 2020-02-04 14:44:01
    [post_content] => 
    [post_title] => test-page_03
    [post_excerpt] => 
    [post_status] => publish
    [comment_status] => closed
    [ping_status] => closed
    [post_password] => 
    [post_name] => test-page_03
    [to_ping] => 
    [pinged] => 
    [post_modified] => 2020-02-04 15:03:14
    [post_modified_gmt] => 2020-02-04 15:03:14
    [post_content_filtered] => 
    [post_parent] => 0
    [guid] => http://example.com/test-page_03/
    [menu_order] => 0
    [post_type] => page
    [post_mime_type] => 
    [comment_count] => 0
    [filter] => raw
)

get_posts()

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");

have_rows() - ACF

[2]:

This function checks to see if a parent field (such as Repeater or Flexible Content) has any rows of data to loop over. This is a boolean function, meaning it returns either true or false
This function is intended to be used in conjunction with the_row() to step through available values
Using have_rows() together with the_row() is intended to feel native much like the have_posts() and the_post() WordPress functions.

Gebruik bv. get_fields of get_field_objects om alle ACF-objecten van een post te achterhalen. Dan weet je wat de top-level-entiteit is

media_handle_sideload ()

[3]: 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()

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()

set_post_thumbnail( int|WP_Post $post, int $thumbnail_id )

waarbij:

  • int|WP_Post $post: Post-ID of post object (compleet oo-object?)
  • int $thumbnail_id: Attachment-ID
  • Return: (int|bool): true bij success en false bij mislukking.

Zie ook

Bronnen

term_id - Variabele & db-veld

term_id is precies wat het zegt: de id van een taxon. Alle taxons worden onder water in dezelfde tabel worden opgeslagen, dus term_id is globaal

Zie ook Categorieën (WordPress)#wp_terms.

term_taxonomy_id - Variabele & db-veld

term_taxonomy_id koppelt een taxon aan een taxonomie. Ik betwijfel of dit van groot practisch nut is.

Zie ook Categorieën (WordPress)#wp_term_taxonomy.

the_row() - Core

[4]: "This function will progress the global repeater or flexible content value one row"

Het wordt onder andere gebruikt rondom ACF, om door repeaters of flexible content te navigeren. Voorbeeld (feb. 2020):

while (have_rows('brands', 651)):
	the_row();

	while (have_rows('regular_block', 651)): 
		the_row();

		while (have_rows('brand_custom', 651)): 
			the_row();
			echo get_sub_field('title', 651),"\n";
		endwhile;
	endwhile;
endwhile;

Voorbeeld: ACF (feb. 2020)

Het gaat om een entiteit genaamd regular_block. Met get_fields krijg ik (vereenvoudigd) zoiets:

Array
(
   [brands_kind] => show_more_block
   [regular_block] => Array
   (
      [brand_repeater_kind] => custom
      [brand_taxonomy]      =>
      [brand_custom]        => Array(...)
   )

Met deze code itereer ik over deze drie 'hoofd field groups', lijkt me:

$i=0;
while (have_rows('regular_block', $aeg_id)): $row=the_row();

   $i++;
   echo "Teller: ".$i."\n";
   print_r($row);

endwhile;

Merk op dat the_row() een array retourneert (dus niet een object of weet-ik-veel-wat). Een impressie van die array:

Teller: 1
Array
(
    [field_5de8cc68c2a60] => custom
    [field_5de8cc9bc2a61] => Array()
    [field_5de8dec370252] => Array
        (
            [0] => Array
                (
                    [field_5de8dece70253] => Knabbelmachines
                    [field_5de8def570254] => 660
                    [field_5de8df0570255] => Array
                        (
                            [title] => AEG - Knabbelmachine
                            [url] => http://kbshop.s1/shop/aeg/knabbelmachine/
                            [target] => 
                        )
                )
            [1] => Array
                (
                    [field_5de8dece70253] => Boormachines
                    [field_5de8def570254] => 658
                    [field_5de8df0570255] => Array
                        (
                            [title] => AEG - Boormachine
                            [url] => http://kbshop.s1/shop/aeg/boormachine-aeg/
                            [target] => 
                        )
                )
        )
)

Merk verder op, dat er niets te itereren is: have_rows() vindt dat deze entiteit maar één regel bevat.

update_field() - ACF

  • Update de waarde van een ACF-veld
  • Als je een ongeldige waarde geeft, krijg je geen foutmelding. De oude waarde blijft gehandhaavd.

Voorbeeld (feb. 2020)

###############################################################
# Read something
###############################################################
#
echo "Read something...\n";

print_r(get_field("brands_kind", 510));
echo "\n";
// print_r(get_field_object("brands_kind", 510));
// echo "\n";
echo "\nRead something... Done\n";


###############################################################
# update_field
###############################################################
#
echo "update_field...\n";

$retour = update_field("brands_kind", "show_more_block", 510);
echo "\n";
print_r($retour);
echo "\n";

echo "update_field... Done\n";


###############################################################
# Read something
###############################################################
#
echo "Read something...\n";

print_r(get_field("brands_kind", 510));
echo "\n";
# print_r(get_field_object("brands_kind", 510));
echo "\n";
echo "\nRead something... Done\n";

update_post_meta()

update_post_meta is een generieke functie om records in tabel wp_postmeta te beheren. Het lijkt zo primitief, maar dat maakt het juist veelzijdig:

update_post_meta
(
   int $post_id,
   string $meta_key,
   mixed $meta_value,
   mixed $prev_value = ''
)
as (int|bool) Meta ID

Waarbij:

  • int $post_id: The post-id waar het meta-veld bij hoort
  • string $meta_key: De sleutel of naam van het meta-veld
  • mixed $meta_value: (mixed) (Required) Metadata value. Must be serializable if non-scalar
  • $prev_value: Snap ik niet: (mixed) (Optional) Previous value to check before updating. If specified, only update existing metadata entries with this value. Otherwise, update all entries. Default value: (lege string).

Return: (int|bool) Meta ID if the key didn't exist, true on successful update, false on failure or if the value passed to the function is the same as the one that is already in the database.

ACF

Custom fields worden bijgehouden in tabel wp_postmeta

update_post_meta kan gebruikt worden om custom fields te updaten. Voorbeeld Jafty.com:

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' );

Zie ook

Bronnen

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_post()

(WP_Post|false|null) = wp_delete_post( int $postid, bool $force_delete = false )

Bronnen

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_post

Voeg een post toe aan een site. Met post wordt hier een willekeurig WP-object bedoeld. Dus ook pages, en zeker WooCommerce-products - Daar heb ik deze functie veel voor gebruikt

Syntaxis

wp_insert_post( array $postarr, bool $wp_error = false )

Voorbeeld

###############################################################
# Create a page + stuff
###############################################################
#
echo "Create a page + stuff...\n";

# Create page
#########################
#
$post_data=array
(
	'post_title'	=> 'test-page_03',
	'post_type'	=> 'page',
	'post_status'	=> 'publish'
);
$post_id = wp_insert_post($post_data);
echo "\n";
print_r($post_id);
echo "\n";

# Klaar
###################3
#
echo "Create a page + stuff... Done\n";

Opmerkingen:

  • Als je bij post_type iets doet wat niet bestaat (bv. published), dan krijg je geen foutmelding, maar ook geen pagina
  • Als je deze code herhaalt, krijg je een additionele posting met dezelfde titel (maar met een ander post-id, uiteraard)

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.

Syntaxis

[5]:

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

Argumenten

$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

Array-velden:

  • '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.

Je kunt hiermee geen specifieke velden voor product_cat-taxonomieën van waarde voorzien. 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");

gebruik hiervoor de functie add_term_data.

Return values

[6]:

(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.

Voorbeeld van deze functie, waarbij de return values geverifiëerd worden:

# $l1_array is een tabel die is ingelezen in PHP
#
foreach ($l1_array as $l1_row)
{
	echo $l1_row['brand']."\n";

	$return_values = wp_insert_term
	(
		$l1_row['brand'],
		"product_cat",
		array
		(
			'description'	=>	$l1_row['description']
		)
	);

	# Check type of return_values
	#############################
	#
	if (is_array($return_values))
	{
		# Term-id & term_taxonomy-id are returned
		#########################################
		#
		# echo "Array\n";
		print_r($return_values);
	}
	else
	{
		echo "Not an array\n";
	};
}

Voorbeeld van de output:

Array
(
    [term_id] => 4956
    [term_taxonomy_id] => 4956
)

Performance

Naarmate er meer termen in het systeem zitten, wordt deze functie trager. Vanaf ca. 7.500 termen (in totaal), kost deze functie bijna een seconde. Vermoedelijk is een implementatie in SQL, veel sneller, maar dat kan toch redelijk complex zijn: Deze functie muteert niet alleen tabel wp_terms, maar vermoedelijk ook wp_term_taxonomy + controleert dat de slug wel uniek is, etc.

wp_set_object_terms

[7]:

  • Relates an object (post, link etc) to a term and taxonomy type (tag, category, etc) - Werkt voor alle taxonoomische systemen in WordPress
  • 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.

Syntaxis

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

Argumenten

  • $object_id (integer) - The id of the object to relate. Dit is ook de naam van het db-veld in tabel wp_term_relationships
  • $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)

Return values

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).

Voorbeelden

return_values = wp_set_object_terms(...)

Zie ook

Bronnen

Zie ook

Bronnen