Po prvé, z hľadiska organizácie kódu by bolo lepšie vložiť všetku logiku kontroly do jedného alebo viacerých zahrnutých súborov a potom ju zahrnúť na stránky produktov:
Include("zahŕňa/recenzie.php");
Týmto spôsobom môžu stránky produktov zostať nefalšované a rovnaký kód recenzie možno jednoducho použiť alebo upraviť podľa potreby. Skript reviews.php by urobil niekoľko vecí:
- Ukážte formulár recenzie
- Spracujte kontrolný formulár
- Uveďte zoznam existujúcich recenzií
- Spracovanie sekundárnych akcií, ako je nahlásenie recenzií alebo komentárov ako nevhodných, označenie, že recenzie boli užitočné, pridávanie komentárov k recenziám, označenie, že komentáre sú užitočné atď.
Dúfajme, že ste už urobili veľa vývoja webu, takže viete, že formulár na pridávanie recenzií bude vyzerať takto:
Je jasné, že by ste chceli použiť nejaké CSS, aby to bolo pekné, ale to je základná myšlienka. Hlavným háčikom je, že ID produktu a typ produktu (alebo čokoľvek, čo musí mať databáza, aby bolo možné priradiť recenziu k položke), musia byť uložené v skrytých vstupoch. Mali by ste mať skript PHP, ktorý zobrazuje produkt, zapísať tieto hodnoty do vstupov.
Ak sa vyžaduje prihlásenie, môžete pridať (PHP) kód, ktorý zobrazí formulár iba prihláseným používateľom, alebo vytlačí komentár, ktorý hovorí, že používateľ sa musí prihlásiť, aby mohol skontrolovať produkt. Podobne, ak máte zavedený systém, ktorý zaručuje, že osoba skontroluje produkt iba raz, pred zobrazením tohto formulára by ste mali skontrolovať tento scenár v PHP.
Odoslanie formulára mohol prejsť na novú stránku, ale potom by používateľ musel kliknúť na tlačidlo Späť, aby sa vrátil na stránku produktu, čo nie je ideálne. Namiesto toho by som formulár odoslal späť na stránku produktu. Napríklad na každej dynamickej webovej stránke sa na zobrazenie celého obsahu konkrétneho typu používa rovnaký skript PHP. V mojom Bezproblémové elektronické obchodovanie s PHP a MySQL kniha, prvý príklad stránky používa skript page.php na zobrazenie ľubovoľnej stránky s obsahom. Atribút action formulára by ukazoval na rovnakú stránku.php . Môžete to dosiahnuť tak, že ponecháte atribút prázdny, alebo použijete PHP na dynamické nastavenie hodnoty.
Ak stránka PHP, na ktorej sú uvedené produkty, vyžaduje, aby bola v adrese URL odovzdaná hodnota identifikujúca produkt, potom bude musieť formulár uložiť aj túto hodnotu do skrytého vstupu. (To už môže byť prípad so vstupom product_id, v závislosti od toho, ako je stránka nastavená.) Sekundárne by bolo potrebné aktualizovať aj skript produktu, aby bolo možné získať hodnotu produktu prostredníctvom POST .
Aby skript reviews.php vedel, kedy má spracovať odoslanie formulára, môže skontrolovať, ako sa k skriptu pristupovalo:
If ($_SERVER["REQUEST_METHOD"] == "POST") ( // Spracovanie formulára.
Po odoslaní kontrolného formulára by sa mali údaje formulára overiť. Mali by ste tiež použiť strip_tags() na údaje, aby ste zabránili útokom Cross-Site Scripting (XSS) alebo inému zlému správaniu. A nečíselné hodnoty by sa spúšťali pomocou funkcie escapovania, ako je napríklad mysqli_real_escape_string() . Alebo môžete jednoducho použiť pripravené príkazy alebo uložené procedúry pre lepšiu bezpečnosť a výkon.
Ak k atribútu action formulára pridáte kotvu — action="page.php#reviews "— používateľ bude po odoslaní presmerovaný do sekcie recenzií na stránke, čo je pekné.
Ak skript reviews.php spracováva aj niektoré ďalšie akcie – nevhodné recenzie alebo komentáre, užitočné indikátory atď. – skript bude musieť sledovať aj tieto príspevky. Použil by som skryté vstupy s názvom „úloha“ na označenie, ktorá akcia sa vykonáva.
V samostatnom článku demonštrujem, ako používať Ajax pre jednoduchý systém hodnotenia. Podobný kód Ajax by sa dal použiť aj pre systém kontroly.
Jedného dňa ste sa rozhodli vytvoriť si vlastnú webovú stránku alebo blog a ako systém správy ste si vybrali WordPress... Postupom času sa vaša stránka stávala čitateľnejšou a potom ste si uvedomili, že pre ešte väčšiu popularitu je potrebné pridať funkcionalitu stránky alebo len zautomatizovať nejakú tú akciu.
Idete do „skladu“ pluginov pre wordpress a zistíte, že plugin, ktorý potrebujete, tam nie je. Čo robiť? Ako byť? Ak sa aspoň trochu orientuješ v základoch programovania v php, layoute, tak to nebude pre teba ťažké Napíšte si vlastný plugin pre WordPress.
A teraz poďme do „kuchyne“ pripraviť náš plugin.
P.s. Ak sa nevyznáte v php a rozložení... nehnevajte sa, požiadajte niekoho, aby vám napísal potrebnú funkcionalitu 🙂
Než začnete písať plugin, musíte si pozrieť dokumentáciu WordPress, ktorá popisuje základné princípy písania pluginov a niektoré príklady kódu.
Nebudem duplikovať tieto informácie, ale okamžite prejdem priamo k písaniu kódu.
Poďme si napísať jednoduchý plugin, ktorý vám umožní ukladať a zobrazovať recenzie o vašej stránke. Samozrejme, že už také pluginy existujú, ale napríklad to postačí.
Prvá vec, ktorú urobíme, je prísť s jedinečným názvom pre náš doplnok – “ AdvUserReviews«.
Ďalej vytvorte nový adresár s názvom „advuserreviews“ v adresári „/wp-content/plugins/“ vašej stránky. A v ňom vytvoríme súbor „advuserreviews.php“. Toto bude hlavný súbor, ktorý bude zodpovedný za všeobecnú inicializáciu. (Pre súbory používajte radšej kódovanie UTF-8).
Na samom začiatku súboru musíte zadať základné informácie o doplnku
Ak teraz prejdete na ovládací panel, môžete vidieť, že systém našiel nový doplnok a ponúka jeho aktiváciu. Na to je však ešte priskoro.
Náš nový plugin napíšeme v štýle OOP a všetko spracovanie dát bude v jednom súbore. Vytvorme hlavný rámec súboru.
// Zastavenie priameho volania if(preg_match("#" . basename(__FILE__) . "#", $_SERVER["PHP_SELF"])) ( die("Nemôžete volať túto stránku priamo."); ) ak (!class_exists("AdvUserReviews")) ( class AdvUserReviews ( // Ukladanie interných údajov verejne $data = array(); // Konštruktor objektu // Inicializácia funkcie hlavných premenných AdvUserReviews() ( ) ) ) global $price; $cena = new AdvUserReviews();
Teraz pridajte nasledujúci kód do konštruktora objektu:
Funkcia AdvUserReviews() ( global $wpdb; // Deklarujte konštantu inicializácie nášho pluginu DEFINE("AdvUserReviews", true); // Názov súboru nášho pluginu $this->plugin_name = plugin_basename(__FILE__); // URL pre náš plugin $ this->plugin_url = trailingslashit(WP_PLUGIN_URL."/".dirname(plugin_basename(__FILE__))); // Tabuľka na ukladanie našich recenzií // premenná $wpdb musí byť deklarovaná globálne $this->tbl_adv_reviews = $wpdb->prefix "adv_reviews"; // Funkcia, ktorá sa vykoná pri aktivácii pluginu register_activation_hook($this->plugin_name, array(&$this, "activate")); // Funkcia, ktorá sa vykoná, keď je doplnok deaktivovaný register_deactivation_hook($this ->plugin_name, array (&$this, "deactivate")); // Funkcia, ktorá sa vykoná po odinštalovaní doplnku register_uninstall_hook($this->plugin_name, array(&$this, "uninstall")); )
V konštruktore objektov používame 3 „háky“ alebo „háky“ (čo je to?): register_activation_hook, register_deactivation_hook A register_uninstall_hook- to sú funkcie, ktoré sa vykonávajú pri aktivácii, deaktivácii a odstránení pluginu.
Teraz poďme implementovať tieto funkcie priamo.
/** * Aktivácia pluginu */ function activate() ( global $wpdb; require_once(ABSPATH . "wp-admin/upgrade-functions.php"); $table = $this->tbl_adv_reviews; // Určenie verzie mysql, ak ( version_compare(mysql_get_server_info(), "4.1.0", ">=")) ( if (! empty($wpdb->charset)) $charset_collate = "PREDVOLENÁ MADA ZNAKOV $wpdb->charset"; if (! empty( $wpdb->collate)) $charset_collate .= " COLLATE $wpdb->collate"; ) // Štruktúra našej kontrolnej tabuľky $sql_table_adv_reviews = " CREATE TABLE `.$wpdb->prefix."adv_reviews` (`ID` INT(10) UNSIGNED NULL AUTO_INCREMENT, `review_title` VARCHAR(255) NOT NULL DEFAULT "0", `review_text` TEXT NOT NULL, `review_date` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, `LLNU`review_CHAR_name`us,0`review_user_name`0 VARCHAR(200) NULL, PRIMARY KEY (`ID`))".$charset_collate.";"; // Skontrolujte, či tabuľka existuje, ak ($wpdb->get_var("zobraziť tabuľky ako "".$table."" " ) != $table) ( dbDelta($sql_table_adv_reviews); ) ) /** * Deact vyvolanie pluginu */ function deactivate() ( return true; ) /** * Odstráňte doplnok */ function uninstall() ( global $wpdb; $wpdb->query("DROP TABLE IF EXISTS ($wpdb->prefix)adv_reviews"); )
Variabilné $wpdb je zodpovedný za dotazy do databázy. Funkcia dbDelta analyzuje aktuálnu štruktúru tabuľky, porovnáva ju s požadovanou štruktúrou tabuľky a podľa potreby tabuľku buď pridá alebo upraví.
Podľa toho sa pri aktivácii doplnku vytvorí tabuľková štruktúra na ukladanie recenzií. Keď je plugin deaktivovaný, nedôjde k žiadnej akcii, ale keď ho vymažeme, vymažeme našu tabuľku. Podrobnejšie akcie možno pochopiť zo zdrojového kódu.
Základná štruktúra nového pluginu je hotová. Teraz musíme začať písať funkčnú časť. Aby sme to dosiahli, musíme do konštruktora triedy pridať nasledujúce riadky kódu:
// Ak sme v admin. interface if (is_admin()) ( // Pridať štýly a skripty add_action("wp_print_scripts", array(&$this, "admin_load_scripts")); add_action("wp_print_styles", array(&$this, "admin_load_styles")); // Pridať ponuku pre doplnok add_action("admin_menu", array(&$this, "admin_generate_menu")); ) else ( // Pridať štýly a skripty add_action("wp_print_scripts", array(&$this, "site_load_scripts" )) ; add_action("wp_print_styles", array(&$this, "site_load_styles")); add_shortcode("show_reviews", array (&$this, "site_show_reviews")); )
Pozrime sa bližšie na túto časť kódu. Začnime panelom administrácie.
Funkcia " is_admin» skontroluje, v akom režime práve pracujeme – na stránke alebo v ovládacom paneli.
Ďalej sa používa niekoľko háčikov pre funkcie:
- wp_print_scripts- Pridajte požadované súbory javascript
- wp_print_styles- Pridajte potrebné štýly
- admin_menu- Pridajte novú ponuku do ovládacieho panela
Každý háčik zodpovedá metóde implementovanej v našej triede. v ktorých sa vykonávajú potrebné operácie.
Zvážte kód na prepojenie štýlov a skriptov
/** * Načítajte potrebné skripty pre stránku správy * na paneli admin */ funkcia admin_load_scripts() ( // Registrácia skriptov wp_register_script("advReviewsAdminJs", $this->plugin_url . "js/admin-scripts.js") ; wp_register_script( "jquery", $this->plugin_url . "js/jquery-1.4.2.min.js"); // Pridanie skriptov na stránku wp_enqueue_script("advReviewsAdminJs"); wp_enqueue_script("jquery"); ) /** * Načítavanie potrebných štýlov pre stránku správcu * na paneli správcu */ funkcia admin_load_styles() ( // Registrácia štýlov wp_register_style("advReviewsAdminCss", $this->plugin_url . "css/admin-style.css") ; // Pridať štýly wp_enqueue_style( "advReviewsAdminCss"); )
Používajú sa tu nasledujúce funkcie.
Každá akcia závisí od odovzdaného parametra „akcia“, respektíve „upraviť“ – úprava recenzie, „odoslať“ – uloženie upravenej recenzie a „vymazať“ – vymazanie recenzie.
Údaje sa vymieňajú so zobrazovanými stránkami prostredníctvom vlastnosti "data" objektu. Zdrojový kód týchto stránok bude zverejnený v archíve s týmto modulom na konci článku. Tu ich nebudem vkladať, pretože téma sa už ukázala ako dosť veľká.
Týmto sa ukončí administračný panel a prejde sa k zobrazovaniu a pridávaniu spätnej väzby od používateľov.
Aby sme wordpressu povedali, kedy máme zavolať náš plugin, musíme zaregistrovať „shortcode“, čo sme urobili v konštruktore našej triedy. Viac o tom.
Add_shortcode("show_reviews", pole (&$this, "site_show_reviews"));
Teraz môžete tento kód umiestniť na ktorúkoľvek stránku webu a ten prinúti vykonať funkciu, ktorú sme špecifikovali (zadanú ako druhý parameter). Nižšie je uvedený zdrojový kód tejto funkcie.
/** * Zoznam recenzií stránok */ verejná funkcia site_show_reviews($atts, $content=null) ( globálne $wpdb; if (isset($_POST["action")]) && $_POST["action"] == " add-review") ( $this->add_user_review(); ) // Vybrať všetky recenzie z databázy $this->data["reviews"] = $wpdb->get_results("SELECT * FROM `" . $this- >tbl_adv_reviews . "`", ARRAY_A); ## Zapnúť ukladanie do vyrovnávacej pamäte výstupu ob_start (); include_once("site_reviews.php"); ## Získať údaje $output = ob_get_contents (); ## Vypnúť ukladanie do vyrovnávacej pamäte ob_end_clean (); return $output ; ) súkromná funkcia add_user_review() ( globálne $wpdb; $inputData = array("review_title" => strip_tags($_POST["review_title"]), "review_text" => strip_tags($_POST["review_text"]) , " review_user_name" => strip_tags($_POST["review_user_name"]), "review_user_email" => strip_tags($_POST["review_user_email"]),); // Pridať novú recenziu na stránku $wpdb->insert( $this-> tbl_adv_reviews, $inputData); )
V zásade tu nie je nič zložité - na výber údajov sa vykoná dotaz SQL, ale ak sa odovzdá parameter „akcia“, najskôr sa pridá nová recenzia. Ale mali by ste venovať pozornosť výstupnej vyrovnávacej pamäti. Je to potrebné na získanie údajov vloženej stránky.
To je vlastne všetko. Teraz môžete vidieť, čo máme. ALE stiahnuť plugin a zdrojové kódy môžete tu.
Samozrejme, toto je len príklad vytvorenia pluginu, ale bude fungovať aj ako jednoduchá hosťovská izba, ak sa mierne upraví, napríklad pridá ochranu pred robotmi a stránkovanie. Šťastné kódovanie :)
Webový formulár:
Ovládací panel pluginu:
Skontrolovať úpravu:
Tiež by vás mohlo zaujímať:
Odpoveď
Na základe https://toster.ru/q/276441 Samozrejme, veľa závisí od projektu, takže tento príspevok by mal byť prispôsobený vášmu prípadu.
* Bezpečnosť:
- Každý argument metódy jednoduchého typu musí byť typovo skontrolovaný, ak sa používa proxy, a proti hraniciam, ak sa spracováva. Trochu to tak nie je – vyhodí sa výnimka. Ak metóda s niekoľkými argumentmi pozostáva z 80% overenia z argumentov, je to celkom normálne))
- Žiadna chyba trigger_error, iba výnimky.
- Výnimky MUSIA byť čitateľné pre človeka, používateľovi môžu byť udelené všetky druhy "Niečo sa pokazilo", ale do protokolu by sa mala dostať výnimka so sledovaním zásobníka a ľudsky čitateľným popisom toho, čo sa tam pokazilo.
- Každý argument (objekt) metódy musí byť typovo naznačený na túto triedu alebo rozhranie.
- Za eval spravidla tvrdé pokarhanie
- @ je povolené len v beznádejných situáciách, ako je kontrola json_last_error.
- Pred prácou s databázou - povinná kontrola údajov.
- Nie == a!=. So swtichom - jediná výnimka, podľa situácie.
- Ak metóda vracia nielen bool, ale aj niečo iné - vyžaduje sa tvrdá kontrola pomocou === alebo!==.
- Žiadne podmienky s úlohami vo vnútri. while($row = ...) je tiež neplatné.
- Magic getters/setters sú povolené len v beznádejných situáciách, inak sú zakázané.
- Reťazenia v sql - iba v beznádejných situáciách.
- Parametre v sql - LEN cez zástupné symboly.
- Žiadne globálne premenné.
- Dátumy ako reťazec sú povolené len v šablónach a v databáze, v PHP kóde sa to okamžite skonvertuje na \DateTimeImmutable (\DateTime je povolený v zúfalých situáciách)
- Samozrejme, závisí to od projektu, ale spravidla by mali existovať iba dva vstupné body: index.php pre web a konzola (alebo inak nazývaná) - pre konzolu.
* Codestyle PSR-2 + PSR-5 aspoň + veľa prísnejších požiadaviek (pre začiatočníkov všetko, čo je v PSR označené ako MAL by sa stať MUSÍM)
- V PhpStorm by nemal byť zvýraznený žiadny riadok (výnimkou je preklep, napríklad slovník nepozná žiadnu zo skratiek akceptovaných vo vašom projekte). Pre zúfalé situácie je povolené použiť /** @noinspection *** */.
- Ak niekto povie, že píše v inom editore a nie je to zvýraznené, aj tak ho posielajú na prepracovanie.
* Organizácia kódu:
- Žiadne globálne funkcie.
- Triedy bez menného priestoru sú povolené len vo výnimočne beznádejných situáciách.
* Testovateľnosť (v zmysle jednoduchosti testovania) kódu by mala byť vysoká.
- Pokrytie kódu je povinné pre všetky možné prípady použitia každej verejnej metódy so závislosťami.
* Princípy MVC:
- Žiadne spracovanie vstupov používateľa v modeloch, od slova vôbec.
- Žiadne dotazy do databázy zo šablón.
- Žiadne rozloženie/js/css/sql-in v ovládačoch.
- V modeloch, ŽIADNE MÁGIE, iba súkromné nehnuteľnosti + getry s nastavovačmi.
- V modeloch je povolené použiť metódu uloženia (ak je, samozrejme) len vo výnimočných situáciách. Vo všetkých ostatných - buď vložiť alebo aktualizovať.
* SOLID princípy:
- Žiadne univerzálne predmety, ktoré dokážu všetko.
- Ak je interná metóda súkromná, žiadna verejná.
- Statické metódy sú povolené len vtedy, ak neexistuje východisko.
* Princíp DRY môže byť porušený v nasledujúcich prípadoch:
- Explicitné oddelenie povinností
- V testoch (každý test by mal byť čo najnezávislejší)
* Práca s databázou:
- Požiadavka v cykle musí byť NAOZAJ opodstatnená.
- Za OBJEDNÁVKU PODĽA NÁHODOV() tvrdé pokarhanie
- Vyhľadávanie nie podľa kľúčov (samozrejme, ak tabuľka NIE JE 5 riadková) je zakázané.
- Vyhľadávanie bez LIMITU (opäť, ak tabuľka NIE JE 5 riadková) je zakázané.
- SELECT * - vypnuté.
- Denormalizácia databázy musí byť odôvodnená.
- MyISAM sa nepoužíva (tak)))
- Viacnásobné operácie sú povinné v transakcii, s vrátením späť, ak sa niečo pokazilo.
- Databáza by nemala obsahovať obchodnú logiku, iba dáta v holistickej forme.
- Nemalo by dochádzať k nevhodnému trhaniu databázy tam, kde sa bez nej zaobídete.
* Vyrovnávacia pamäť musí byť vymazaná podľa dvoch podmienok (nie jednej, ale dvoch):
- Čas.
- Prehnitá obchodná logika.
Povolený len čas v zúfalých situáciách, ale potom je čas krátky.
- Pri výpočte cache kľúčov je potrebné použiť premennú z konfigurácie aplikácie (v prípade aktualizácií sa cache resetuje kódom, nie flash cache servera). V prípade použitia viacerých serverov je to veľmi pohodlný a flexibilný nástroj pre diplomy.
* O ľuďoch:
- "Zvykol som si takto písať a budem pokračovať" - žiadna otázka, recenziu prejdete, až keď si to rozmyslíte.
- "Píšem vo vime a je to pre mňa také pohodlné" - super, píšem kód aj s konzolou v nej)) ale na kód sú požiadavky, ak to nezvládneš, neprejdeš kontrolou .
- "Skopíroval som túto hroznú metódu a zmenil som 2 riadky" - to je určite úžasné, ale podľa výčitiek ste autorom celej tejto metódy, takže nebláznime, dobre?
- "Funguje to!" - táto fráza je preložená asi takto: "áno, chápem, že píšem úplný nezmysel, ale nemôžem písať normálne, pretože neviem", pochopil som správne?))
- "Všetko funguje!" - radi, ale čo produkcia?
- "Tam je všetko jednoduché" - nepoužívajte slovo "jednoduché", zo slova "úplne". Tu je pre vás kúsok kódu (prvý, ktorý narazil na zložitú obchodnú logiku), kde je chyba (nezáleží na tom, či existuje alebo nie)? Pozeráš to 2 minúty, v čom je problém, tam je všetko "jednoduché"))
* Čokoľvek:
ActiveRecord (hovorím ti ako fanúšik Yii v minulosti) - je to na hovno, ber to ako originál. V skutočnosti máte modely s napojením na databázu, ktoré nekontrolovane chodia po projekte. Neraz som sa stretol s tým, že v rovnakých šablónach volajú uložiť, prípadne aktualizovať (na to si to musíte vypáliť).
Hlavné:
1. Prítomnosť kritických chýb a zastaraných funkcií.
2. Použitie vzorov, elegancia riešení.
3. Čitateľnosť kódu, prítomnosť komentárov, prítomnosť dokov.
4. Súlad s paradigmami a konvenciami (napríklad porušenie MVC).
Sekundárne / nedôležité:
1. Výkon kódu (okrem vysokého zaťaženia)
2. Spotreba pamäte (okrem veľkých dát)
3. Efektívnosť SQL dotazov (s výnimkou veľmi absurdných)
4. Vyhýbanie sa momentálne nedôležitým, ale potenciálne úzkym miestam (napríklad spomaleniu systému súborov s veľkým počtom obrázkov v priečinku na nahrávanie)
5. Novinky aplikovaných technológií.
6. Opodstatnené/neopodstatnené/nadmerné cyklovanie.
- Kód neobsahuje zjavné a potenciálne chyby.
- Kód funguje tak, ako je opísané v dokumentácii, referenčných podmienkach alebo sprievodných komentároch.
- Štýl kódovania je v súlade s prijatými pravidlami kódovania
- Kód má sprievodné komentáre podľa phpDoc
- Vkladanie blokov nepresahuje 4. úroveň.
- Kód negeneruje správy na úrovni Strict, Warning, Notice, Deprecated. Ak sa tomu nedá vyhnúť, potom bezprostredne pred riadkom, ktorý to generuje, musíte vynútiť vypnutie error_reporting a hneď po riadku zase vrátiť error_reporting na pôvodnú hodnotu (ktorá bola predtým). Takýto kód musí byť zdokumentovaný osobitným spôsobom.
- Komentovaný kus kódu by sa mal odstrániť.
- V PHP kóde (s výnimkou phpTemplate) sú vložky HTML, JavaScript zakázané. Všetky vložky musia byť vyrobené pomocou špeciálnych šablón.
- Triedy, funkcie, premenné a konštanty musia byť logicky pomenované ľudsky čitateľným spôsobom v angličtine v súlade so štandardmi kódovania. Pomenovanie prepisom v ruštine alebo v iných jazykoch nie je povolené
- Rozsah premenných tried a metód musí byť vždy definovaný (súkromné, chránené, verejné).
- Veľkosť jednej metódy by nemala presiahnuť 40-50 riadkov.
- Premenná použitá v slučke alebo v podmienenom bloku musí byť inicializovaná vopred.
- Premenná musí v danom čase obsahovať iba jeden typ. Prázdna premenná musí obsahovať hodnotu null. (nepovolené $var = false; $var = "test"; . povolené $var = null; $var = "test";).
- Pri odovzdávaní objektov tried metódam sa musí použiť kontrola typu.
WordPress znamená prispôsobenie/konfiguráciu. Bol vytvorený tak, že úplne každá sekcia sa dá prispôsobiť. V tejto lekcii sa na to pozrieme vlastné typy príspevkov, jedna z najvýznamnejších a najúžasnejších funkcií WordPress, s ktorou WordPress dokázal dosiahnuť nové výšky.
Aké sú vlastné typy príspevkov?
Povedzme, že chcete, aby mal váš blog samostatnú sekciu pre recenzie filmov. Pomocou vlastných typov príspevkov môžete vytvoriť nový typ príspevku, ako napríklad Príspevky a Stránky, ktorý bude obsahovať iný druh údajov. Bude mať vlastné admin menu, špeciálne editačné stránky, vlastné taxonómie a mnoho ďalších nástrojov, ktoré sú potrebné na plnohodnotnú prácu s publikáciami.
Vlastné typy príspevkov sú ďalšou sadou nastavení správcu, ktoré existujú spolu s nastaveniami pre predvolené typy príspevkov, ako napr záznamy, stránky, Priložené súbory, atď. Vlastné typy príspevkov môžu ukladať akýkoľvek typ údajov. Majú samostatný editor, nástroj na nahrávanie médií a používajú už existujúcu štruktúru tabuliek WordPress, čo uľahčuje správu údajov. Hlavnou výhodou vlastných typov príspevkov vytvorených pomocou WordPress API je ich kompatibilita s už existujúcimi témami a šablónami. Vďaka použitiu trvalých odkazov tiež vlastné typy príspevkov dobre spolupracujú s vyhľadávacími nástrojmi.
Prečo používať vlastné typy príspevkov?
Vlastné typy príspevkov vám pomôžu ukladať rôzne typy príspevkov na rôzne miesta. Pomáha to oddeliť bežné príspevky od ostatných. To je všetko.
Vytvorenie doplnku pre vlastný typ príspevku
Vytvoríme plugin pre vlastný typ príspevku, ktorý bude zobrazovať najlepšie recenzie filmov. Začnime.
Krok 1 . Vytvorte priečinok doplnku WordPress
Otvorte priečinok doplnkov WordPress a vytvorte nový priečinok Filmové recenzie.
Krok 2: Vytvorte súbor PHP
Vo vytvorenom priečinku vytvorte súbor PHP Movie-Reviews.php
Krok 3: Pridajte hlavičku
Otvorte vytvorený súbor a navrch prilepte kód pre hlavičku.
Pred koncovú značku príkazu PHP zadajte nasledujúci riadok kódu create_movie_review. Po inicializácii spustí príslušnú užívateľom definovanú funkciu pri každom vygenerovaní stránky.
Add_action("init", "create_movie_review");
Krok 5: Vykonanie funkcie
Kód na spustenie funkcie create_movie_review.
Funkcia create_movie_review() ( register_post_type("movie_reviews", array("labels" => array("name" => "Recenzie filmov", "singular_name" => "Recenzia filmu", "add_new" => "Pridať nové", "add_new_item" => "Pridať novú recenziu filmu", "edit" => "Upraviť", "edit_item" => "Upraviť recenziu filmu", "new_item" => "Novú recenziu filmu", "zobraziť" => "Zobraziť ", "view_item" => "Zobraziť recenziu filmu", "search_items" => "Hľadať recenzie filmov", "not_found" => "Nenašli sa žiadne recenzie filmov", "not_found_in_trash" => "V koši sa nenašli žiadne recenzie filmov", "parent" => "Parent Movie Review"), "public" => true, "menu_position" => 15, "supports" => array("title", "editor", "comments", "thumbnail", " custom-fields"), "taxonomies" => array(""), "menu_icon" => plugins_url("images/image.png", __FILE__), "has_archive" => true)); )
Väčšinu práce v našom prípade urobí funkcia register_post_type. Hneď po jeho zavolaní pripraví potrebnú konfiguráciu WordPress pre nový vlastný príspevok vrátane ďalších sekcií pre administrátora. Funkcii sú odovzdané dva typy argumentov: jedinečný názov (názov) vlastného typu príspevku a pole s jeho vlastnosťami. Toto je iné pole s rôznymi menovkami, ktoré označujú, ktoré textové reťazce sa zobrazia v rôznych častiach vlastného typu príspevku, napríklad: „názov“ zobrazuje názov vlastného typu príspevku v ovládacom paneli, „upraviť“ a „zobraziť“ " tlačidlá displeja Upraviť A vyhliadka. Myslím, že všetky ostatné argumenty hovoria samy za seba.
Takže v nasledujúcich argumentoch:
- "public" => true nastaví viditeľnosť vlastného typu príspevku v ovládacom paneli správcu aj na strane klienta.
- "menu_position" => 15 určuje, kde v ponuke bude umiestnený vlastný typ príspevku.
- "supports" => array("title", "editor", "comments", "thumbnail", "custom-fields") určuje, ktoré vlastné atribúty typu príspevku sa majú zobraziť.
- "taxonomies" => array("") vytvára vlastné taxonómie. V tomto prípade nie sú definované.
- "menu_icon" => plugins_url("images/image.png", __FILE__) zobrazuje ikonu v ponuke správcu.
- "has_archive" => true umožňuje archiváciu vlastných typov príspevkov.
Viac o ďalších argumentoch používaných vo vlastných typoch príspevkov sa dozviete na stránke WordPress Codex register_post_type.
Krok 6 : Ikona pre vlastný typ príspevku
Uložte ikonu s rozmermi 16 x 16 pixlov do priečinka doplnku. Je to potrebné, aby mal vlastný typ príspevku na ovládacom paneli ikonu.
Krok 7: Aktivujte doplnok
Aktivujte doplnok a voila, máte vlastný typ príspevku s možnosťou upravovať text, nastavenia pre uverejňovanie, obrázky, komentáre a editor vlastných polí.
Krok 8: Pridanie novej položky
Vyberte Pridať nové otvoríte panel úprav pre vlastný typ príspevku. Pridajte názov filmu, text recenzie a vyberte miniatúru obrázka.
Krok 9: Zverejnite
Uverejnite príspevok a kliknite Zobraziť recenziu filmu zobraziť recenziu filmu, ktorú ste vytvorili.
Vytvorenie ďalších polí pre vlastné typy príspevkov
Mechanizmus doplnkových polí (metaboxov) využíva systém doplnkových polí zabudovaný vo WordPresse. To vám pomôže pridať polia, ktoré sú špecifické pre vlastné typy príspevkov bez použitia predvolených vlastných polí v editore.
Krok 1: Registrácia užívateľskej funkcie
Otvorený súbor Movie-Reviews.php a pred koncovú značku pridajte nasledujúci kód. Tento kód registruje funkciu, ktorá sa zavolá pri návšteve administračného panela WordPress.
Add_action("admin_init", "my_admin");
Krok 2: Vykonajte vlastnú funkciu
Pridajte spustenie funkcie my_admin, ktorá zaregistruje ďalšie polia a priradí ich k vlastnému typu príspevku movie_reviews.
Funkcia my_admin() ( add_meta_box("movie_review_meta_box", "Podrobnosti recenzie filmu", "display_movie_review_meta_box", "film_reviews", "normal", "high"); )
V tomto prípade sa funkcia add_meta_box používa na pridanie ďalších polí do vlastného typu príspevku. O atribútoch:
- movie_review_meta_box povinný atribút pre HTML id
- Text podrobností o filmovej recenzii, ktorý bude viditeľný v hlavičke dodatočného poľa
- display_movie_review_meta_box je funkcia spätného volania, ktorá zobrazuje obsah ďalších polí
- movie_review je názov vlastného typu príspevku, kde sa zobrazia dodatočné polia
- normal určuje, kde na stránke sa zobrazí blok úprav
- vysoká určuje prioritu zobrazených polí
Krok 3: Vykonajte funkciu display_movie_review_meta_box
id, "filmový_riaditeľ", true)); $movie_rating = intval(get_post_meta($movie_review->ID, "film_rating", true)); ?>režisér | |
hodnotenie filmu |
Tento kód zobrazuje obsah dodatočných polí. Používa premennú objektu, ktorá obsahuje informácie o každej recenzii filmu zobrazenej na paneli úprav. Pomocou tohto objektu sme dostali ID záznamu a použil ho na vyhľadávanie v databáze, aby získal meno režiséra a hodnotenie, ktoré sa následne zobrazí v poliach na obrazovke. Pri pridávaní nového príspevku funkcia get_post_meta vráti prázdny reťazec a v dôsledku toho budú ďalšie polia prázdne.
Krok 4: Registrácia funkcie Uložiť záznam
add_action("save_post", "add_movie_review_fields", 10, 2);Táto funkcia sa volá, keď sa záznam uloží do databázy.
Krok 5: Vykonajte funkciu add_movie_review_fields
function add_movie_review_fields($movie_review_id, $movie_review) ( // Skontrolujte typ príspevku pre recenzie filmov, ak ($movie_review->post_type == "movie_reviews") ( // Uložte údaje do meta tabuľky príspevku, ak sú prítomné v údajoch príspevku, ak (isset($ _POST["movie_review_director_name"]) && $_POST["movie_review_director_name"] != "") ( update_post_meta($movie_review_id, "movie_director", $_POST["movie_review_director_name"]); ) if (isset"_review"$review"_POST ]) && $_POST["movie_review_rating"] != "") ( update_post_meta($movie_review_id, "movie_rating", $_POST["movie_review_rating"]); ) ) )Táto funkcia sa spustí, keď sa položky uložia alebo odstránia na paneli správcu. V tomto prípade sa skontroluje typ prijatého záznamu a ak je záznam užívateľský, znova sa skontroluje, či majú dodatočné polia nejaké hodnoty, a potom sa tieto hodnoty uložia do týchto polí.
Krok 6: Zakážte štandardné vlastné polia
Pri vytváraní vlastného typu príspevku sme definovali funkciu create_movie_review. Odstráňte prvok custom-fields z poľa podporuje, pretože ho už nepotrebujeme. Teraz, ak uložíte súbor a otvoríte panel úprav Filmové recenzie, v ďalších poliach uvidíte dve polia: Autor filmu A hodnotenie filmu. Rovnakým spôsobom môžete pridať ďalšie prvky.
Vytvorte šablónu pre vlastný typ príspevku
Pre každý typ používateľských príspevkov bude správne používať vlastné šablóny na zobrazovanie údajov. V našom prípade vytvoríme šablónu, ktorá zobrazí všetky recenzie filmov, ktoré boli pridané pomocou vlastného typu príspevku. filmová recenzia.
Krok 1: Registrácia funkcie spustenia šablóny
Otvorený súbor Movie-Reviews.php a pred koncovú značku pridajte nasledujúci kód. Tento kód registruje funkciu, ktorá sa zavolá pri návšteve administračného panela WordPress.
Add_filter("template_include", "include_template_function", 1);
Krok 2: Vykonajte funkciu
function include_template_function($template_path) ( if (get_post_type() == "film_reviews") ( if (is_single()) ( // najprv skontroluje, či súbor existuje v téme, // v opačnom prípade zobrazí súbor z pluginu, ak ($ theme_file = locate_template(pole ("single-movie_reviews.php"))) ( $template_path = $theme_file; ) else ( $template_path = plugin_dir_path(__FILE__) . "/single-movie_reviews.php"; ) ) ) return )Týmto sa skontroluje, či má aktuálny priečinok témy šablónu ako single-(post-type-name).php. Ak tam nie je, tak sa prítomnosť šablóny skontroluje v priečinku s pluginom, kde umiestnime našu šablónu ako súčasť pluginu. Obsluha udalosti template_include (hák) sa používa na zmenu normálneho vykonávania programu a vynútenie spustenia špeciálnej šablóny.
Krok 3: Vytvorte súbor šablóny jednej stránky
Po uložení predtým otvoreného súboru pomocou doplnku vytvorte ďalší súbor s názvom single-movie_reviews.php a vložte do nej nasledujúci kód.
riaditeľ:
hodnotenie: ";) inak (echo" "; } } ?>
V tomto prípade sme vytvorili základnú šablónu stránky pomocou slučky. Funkcia query_posts získava prvky vlastného typu príspevku a zobrazuje ich pomocou slučky. Toto je samozrejme veľmi jednoduchá slučka, môžete ju zmeniť podľa potreby. Na zmenu vzhľadu môžete použiť aj potrebné štýly CSS.
Pozornosť: musíte vytvoriť novú stránku z ovládacieho panela pomocou vytvorenej šablóny.
Krok 4: Obrázky
Uložte dva obrázky ikon hviezd s rozmermi 32 x 32 pixelov do priečinka doplnku. Pomenujte ich podľa toho ikona.png A sivá.png. To je všetko, teraz sa recenzie filmov zobrazujú na samostatnej stránke a sú zoradené podľa dátumu.
Osobný účet poistenca
Automatický identifikačný systém Spoločné používanie AIS s elektronickým mapovým systémom
Wargame: Red Dragon sa nespúšťa?
Smutný escobar „Tvár súdneho systému Ukrajiny“
ROME Total War - ako odomknúť všetky frakcie?