{"id":3179,"date":"2024-11-05T08:25:20","date_gmt":"2024-11-05T07:25:20","guid":{"rendered":"https:\/\/wypo.io\/documentations\/formmaster\/exemples\/ajout-champ-personnalise-selectionner-article-blog\/"},"modified":"2024-11-05T08:54:14","modified_gmt":"2024-11-05T07:54:14","slug":"add-custom-field-selecting-blog-post","status":"publish","type":"wypo_documentations","link":"https:\/\/wypo.io\/en\/documentations\/formmaster\/exemples\/add-custom-field-selecting-blog-post\/","title":{"rendered":"Add a custom field for selecting a blog post"},"content":{"rendered":"            <div class=\"hf_animated fade_bottom none default wp-block-habefast-advanced-layout-group is-layout-constrained wp-block-habefast-advanced-layout-group-is-layout-constrained\">\r\n                <div class=\"wp-block-habefast-advanced-group-container is-style- is-layout-constrained\"  style='--_hfal-cg-d-lg:flex;--_hfal-cg-d-md:flex;--_hfal-cg-d-sm:flex;'>\r\n                                        <div class=\"wp-block-habefast-advanced-group-inner is-layout-flow\">\r\n                        \n\n<p class=\"\">The following code creates a custom post selection field for the WP Form Master plugin, allowing users to select a post from a drop-down list in a form. This field also checks whether a valid selection has been made (if required), saves the ID or title of the selected post, and allows it to be added to forms using a shortcode.<\/p>\n\n\n\n<h2 class=\"wp-block-heading   \" datalink=\"content-code\">Code<\/h2>\n\n\n    <div class=\"wp-block-habefast-code  \">\n      <header class=\"habefast-code-header\">\n        <div class=\"habefast-code-lang is-lang-php\">\n          PHP        <\/div>\n      <\/header>\n      <textarea\n        class=\"habefast-code-source\"\n        name=\"codemirror-1113100665\"\n        id=\"codemirror-1113100665\"\n      >&lt;?php\nif (!defined(&#039;ABSPATH&#039;))\n    exit;\n\nclass WP_FormMaster_AddCustomField_PostSelect {\n    private $fieldname = &quot;select-post&quot;;\n    private $isRequired = true;\n\n    public function __construct() {\n        add_filter(&quot;allowed_block_types_all&quot;, array($this, &quot;setBlocks&quot;), 11, 2);\n        add_shortcode(&quot;wpformmaster-form-post-select&quot;, &#91;$this, &quot;postSelectCallback&quot;&#93;);\n        add_filter(&quot;wpfmaster_form_extractfields&quot;, array($this, &quot;extractFields&quot;), 10, 4);\n        add_filter(&quot;wpformmaster_field_value&quot;, array($this, &quot;getFieldValue&quot;), 10, 7);\n        add_filter(&quot;wpfmaster_form_validate_field&quot;, array($this, &quot;addRequiredError&quot;), 10, 8);\n    }\n\n    public function addRequiredError($error, $formID, $key, $type, $field, $errors, $posts, $files) {\n        if (!$error) {\n            if ($key &amp;&amp; $key === $this-&gt;fieldname) {\n                if ($this-&gt;isRequired) {\n                    if (isset($posts&#91;$key&#93;)) {\n                        $post = get_post($posts&#91;$key&#93;);\n                        if (!$post || $post-&gt;post_type != &quot;post&quot;) {\n                            $error = __(&quot;Please select an item&quot;, &quot;my-domain&quot;);\n                        }\n                    }\n                }\n            }\n        }\n        return $error;\n    }\n\n    public function getFieldValue($value, $key, $type, $attrs, $posts, $files, $getInterpretValue) {\n        if ($key &amp;&amp; $key === $this-&gt;fieldname) {\n            if ($getInterpretValue) {\n                if (isset($posts&#91;$key&#93;) &amp;&amp; $posts&#91;$key&#93;) {\n                    $post = get_post($posts&#91;$key&#93;);\n                    if ($post) {\n                        return sanitize_text_field($post-&gt;post_title);\n                    }\n                }\n            } else {\n                if (isset($posts&#91;$key&#93;) &amp;&amp; $posts&#91;$key&#93;) {\n                    return intval($posts&#91;$key&#93;);\n                }\n            }\n        }\n        return $value;\n    }\n\n    public function extractFields($fields, $formID, $posts, $files) {\n        return array_merge($fields, &#91;\n            &#91;\n                &quot;attrs&quot; =&gt; &#91;\n                    &quot;type&quot; =&gt; &quot;custom-select&quot;,\n                    &quot;name&quot; =&gt; $this-&gt;fieldname\n                &#93;\n            &#93;\n        &#93;);\n    }\n\n    public function postSelectCallback($atts) {\n        ob_start();\n        extract(\n            shortcode_atts(\n                array(\n                    &#039;title&#039; =&gt; __(&quot;Article&quot;, &quot;my-domain&quot;),\n                ),\n                $atts\n            )\n        );\n        ?&gt;\n        &lt;div class=&quot;formmaster-field&quot; datatype=&quot;select&quot; dataname=&quot;&lt;?= $this-&gt;fieldname; ?&gt;&quot;&gt;\n            &lt;div class=&quot;formmaster-select&quot;&gt;\n                &lt;select name=&quot;&lt;?= $this-&gt;fieldname; ?&gt;&quot;&gt;\n                    &lt;option value=&quot;&quot;&gt;&lt;?= $title . ($this-&gt;isRequired ? &quot;*&quot; : &quot;&quot;); ?&gt;&lt;\/option&gt;\n                    &lt;?php\n                    $posts = get_posts(&#91;\n                        &#039;post_type&#039; =&gt; array(&quot;post&quot;),\n                        &#039;post_status&#039; =&gt; &#039;publish&#039;,\n                        &#039;suppress_filters&#039; =&gt; false,\n                        &#039;posts_per_page&#039; =&gt; -1,\n                        &quot;orderby&quot; =&gt; array(\n                            &quot;title&quot; =&gt; &quot;ASC&quot;\n                        )\n                    &#93;);\n                    foreach ($posts as $post) {\n                        ?&gt;\n                        &lt;option value=&quot;&lt;?= $post-&gt;ID; ?&gt;&quot;&gt;&lt;?= $post-&gt;post_title; ?&gt;&lt;\/option&gt;\n                        &lt;?php\n                    }\n                    ?&gt;\n                &lt;\/select&gt;\n            &lt;\/div&gt;\n        &lt;\/div&gt;\n        &lt;?php\n        return ob_get_clean();\n    }\n\n    public function setBlocks($allowed_blocks, $editor_context) {\n        if ($editor_context-&gt;post &amp;&amp; $editor_context-&gt;post-&gt;post_type === &quot;fmaster_form&quot;) {\n            return array_merge($allowed_blocks, &#91;\n                &#039;core\/shortcode&#039;\n            &#93;);\n        }\n        return $allowed_blocks;\n    }\n}\n\nnew WP_FormMaster_AddCustomField_PostSelect();\n?&gt;<\/textarea>\n      <script>\n        CodeMirror.fromTextArea( document.getElementById('codemirror-1113100665'), {\n          mode: {name:'php',startOpen:true},\n          readOnly: true,\n          lineNumbers: true,\n          firstLineNumber: 1,\n          matchBrackets: true,\n          indentUnit: 4,\n          tabSize: 4,\n          lineWrapping: true,\n        } );\n      <\/script>\n    <\/div>\n    \n                    <\/div>\r\n                <\/div>\r\n            <\/div>\r\n            \n\n            <div class=\"hf_animated fade_bottom none default wp-block-habefast-advanced-layout-group is-layout-constrained wp-block-habefast-advanced-layout-group-is-layout-constrained\">\r\n                <div class=\"wp-block-habefast-advanced-group-container is-style- is-layout-constrained\"  style='--_hfal-cg-d-lg:flex;--_hfal-cg-p-t-lg:var(--wp--preset--spacing--30);--_hfal-cg-d-md:flex;--_hfal-cg-d-sm:flex;--_hfal-cg-p-t-md:var(--wp--preset--spacing--30);--_hfal-cg-p-t-sm:var(--wp--preset--spacing--30);'>\r\n                                        <div class=\"wp-block-habefast-advanced-group-inner is-layout-flow\">\r\n                        \n\n<h2 class=\"wp-block-heading   \" datalink=\"content-explanations\">Explanations<\/h2>\n\n\n\n<h3 class=\"wp-block-heading   \" style=\"padding-top:0\" datalink=\"content-overall-class-structure\">Overall class structure<\/h3>\n\n\n\n<p class=\"\">The <code>WP_FormMaster_AddCustomField_PostSelect<\/code> class defines and registers a new custom field that displays a drop-down list of posts. This field uses several WordPress filters and shortcuts to integrate with the form, control display, and manage validation.<\/p>\n\n\n\n<h3 class=\"wp-block-heading   \" datalink=\"content-class-variables\">Class variables<\/h3>\n\n\n\n<ul class=\"wp-block-list  \">\n<li class=\"\"><code>$fieldname<\/code>: Stores the field name, here <code>\u201cselect-post\u201d<\/code>.<\/li>\n\n\n\n<li class=\"\"><code>$isRequired<\/code>: Indicates whether the field is required, here set to <code>true<\/code>.<\/li>\n<\/ul>\n\n                    <\/div>\r\n                <\/div>\r\n            <\/div>\r\n            \n\n            <div class=\"hf_animated fade_bottom none default wp-block-habefast-advanced-layout-group is-layout-constrained wp-block-habefast-advanced-layout-group-is-layout-constrained\">\r\n                <div class=\"wp-block-habefast-advanced-group-container is-style- is-layout-constrained\"  style='--_hfal-cg-d-lg:flex;--_hfal-cg-p-t-lg:var(--wp--preset--spacing--30);--_hfal-cg-d-md:flex;--_hfal-cg-d-sm:flex;--_hfal-cg-p-t-md:var(--wp--preset--spacing--30);--_hfal-cg-p-t-sm:var(--wp--preset--spacing--30);'>\r\n                                        <div class=\"wp-block-habefast-advanced-group-inner is-layout-flow\">\r\n                        \n\n<h3 class=\"wp-block-heading   \" datalink=\"content-class-constructor\">Class constructor<\/h3>\n\n\n\n<p class=\"\">The class constructor adds several filters and a shortcode to integrate the custom field into the form:<\/p>\n\n\n\n<ol class=\"wp-block-list  \">\n<li class=\"\"><strong><code>allowed_block_types_all<\/code><\/strong>: Used to define which blocks are allowed in the WordPress form.<\/li>\n\n\n\n<li class=\"\"><strong><code>wpformmaster-form-post-select<\/code><\/strong>: Creates a shortcode to display the drop-down list of posts in the form.<\/li>\n\n\n\n<li class=\"\"><strong><code>wpfmaster_form_extractfields<\/code><\/strong>: Adds custom field attributes to the form.<\/li>\n\n\n\n<li class=\"\"><strong><code>wpformmaster_field_value<\/code><\/strong>: Extracts and interprets the value selected in the field for data recording.<\/li>\n\n\n\n<li class=\"\"><strong><code>wpfmaster_form_validate_field<\/code><\/strong>: Manages field validation to ensure that a post has been selected if the field is required.<\/li>\n<\/ol>\n\n\n\n<h3 class=\"wp-block-heading   \" datalink=\"content-class-methods\">Class methods<\/h3>\n\n\n\n<h4 class=\"wp-block-heading   \" datalink=\"content-1-addrequirederror\">1. <code>addRequiredError<\/code><\/h4>\n\n\n\n<p class=\"\">This method is used to add an error message if the user does not select a post in the required field:<\/p>\n\n\n\n<ul class=\"wp-block-list  \">\n<li class=\"\"><strong>Parameters<\/strong>: It receives several parameters such as <code>$formID<\/code>, <code>$key<\/code> (field name), <code>$type<\/code>, <code>$field<\/code>, <code>$errors<\/code>, <code>$posts<\/code>, and <code>$files<\/code>.<\/li>\n\n\n\n<li class=\"\"><strong>How it works<\/strong>:\n<ul class=\"wp-block-list  \">\n<li class=\"\">First, it checks whether the field is mandatory.<\/li>\n\n\n\n<li class=\"\">Then it checks whether a valid post is selected (existing and of type post).<\/li>\n\n\n\n<li class=\"\">If the field is empty or contains an invalid selection, it returns an error message: <code>\u201cPlease select an item\u201d<\/code>.<\/li>\n<\/ul>\n<\/li>\n<\/ul>\n\n\n\n<h4 class=\"wp-block-heading   \" datalink=\"content-2-getfieldvalue\">2. <code>getFieldValue<\/code><\/h4>\n\n\n\n<p class=\"\">This method determines the value of the field to be saved in the form:<\/p>\n\n\n\n<ul class=\"wp-block-list  \">\n<li class=\"\"><strong>Parameters<\/strong>: In addition to <code>$value<\/code>, <code>$key<\/code>, <code>$type<\/code>, <code>$attrs<\/code>, <code>$posts<\/code>, <code>$files<\/code>, it also takes <code>$getInterpretValue<\/code> to indicate whether the value should be interpreted.<\/li>\n\n\n\n<li class=\"\"><strong>How it works<\/strong>:\n<ul class=\"wp-block-list  \">\n<li class=\"\">If <code>$getInterpretValue<\/code> is <code>true<\/code>, it returns the title of the selected post.<\/li>\n\n\n\n<li class=\"\">Otherwise, it simply returns the post ID (as an integer).<\/li>\n\n\n\n<li class=\"\">If the field is empty, it returns the default value of <code>$value<\/code>.<\/li>\n<\/ul>\n<\/li>\n<\/ul>\n\n\n\n<h4 class=\"wp-block-heading   \" datalink=\"content-3-extractfields\">3. <code>extractFields<\/code><\/h4>\n\n\n\n<p class=\"\">This method adds this field to the table of fields extracted by WP Form Master :<\/p>\n\n\n\n<ul class=\"wp-block-list  \">\n<li class=\"\"><strong>How it works<\/strong>:\n<ul class=\"wp-block-list  \">\n<li class=\"\">It adds a new field with a <code>custom-select<\/code> attribute and the name defined in <code>$fieldname<\/code>.<\/li>\n\n\n\n<li class=\"\">This field will then be available for the form, with the appropriate name to be identified when sending.<\/li>\n<\/ul>\n<\/li>\n<\/ul>\n\n\n\n<h4 class=\"wp-block-heading   \" datalink=\"content-4-postselectcallback\">4. <code>postSelectCallback<\/code><\/h4>\n\n\n\n<p class=\"\">This method defines the HTML display of the selection field in the form:<\/p>\n\n\n\n<ul class=\"wp-block-list  \">\n<li class=\"\"><strong>Parameters<\/strong>: It takes <code>$atts<\/code> to accept custom attributes passed to the shortcode.<\/li>\n\n\n\n<li class=\"\"><strong>How it works<\/strong>:\n<ul class=\"wp-block-list  \">\n<li class=\"\">Uses <code>get_posts<\/code> to retrieve all published posts.<\/li>\n\n\n\n<li class=\"\">Creates an HTML drop-down list where each option represents a post, displaying its title and storing its ID as a value.<\/li>\n\n\n\n<li class=\"\">If <code>$isRequired<\/code> is <code>true<\/code>, the field title will be marked with an asterisk to indicate that it is mandatory.<\/li>\n<\/ul>\n<\/li>\n<\/ul>\n\n\n\n<h4 class=\"wp-block-heading   \" datalink=\"content-5-setblocks\">5. <code>setBlocks<\/code><\/h4>\n\n\n\n<p class=\"\">This method authorizes certain blocks for the WordPress block editor (Gutenberg) when the form is modified:<\/p>\n\n\n\n<ul class=\"wp-block-list  \">\n<li class=\"\"><strong>How it works<\/strong>:\n<ul class=\"wp-block-list  \">\n<li class=\"\">If the editor is in the context of a WP Form Master form (here identified by the post type <code>fmaster_form<\/code>), it authorizes the <code>core\/shortcode<\/code> block.<\/li>\n\n\n\n<li class=\"\">This allows you to use the shortcode to add this specific field in the block editor.<\/li>\n<\/ul>\n<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading   \" datalink=\"content-class-instantiation\">Class instantiation<\/h3>\n\n\n\n<p class=\"\">The line new <code>WP_FormMaster_AddCustomField_PostSelect();<\/code> creates a new instance of the class and activates the custom field when the code is executed.<\/p>\n\n                    <\/div>\r\n                <\/div>\r\n            <\/div>\r\n            \n\n            <div class=\"hf_animated fade_bottom none default wp-block-habefast-advanced-layout-group is-layout-constrained wp-block-habefast-advanced-layout-group-is-layout-constrained\">\r\n                <div class=\"wp-block-habefast-advanced-group-container is-style- is-layout-constrained\"  style='--_hfal-cg-d-lg:flex;--_hfal-cg-p-t-lg:var(--wp--preset--spacing--30);--_hfal-cg-d-md:flex;--_hfal-cg-d-sm:flex;--_hfal-cg-p-t-md:var(--wp--preset--spacing--30);--_hfal-cg-p-t-sm:var(--wp--preset--spacing--30);'>\r\n                                        <div class=\"wp-block-habefast-advanced-group-inner is-layout-flow\">\r\n                        \n\n<h2 class=\"wp-block-heading   \" datalink=\"content-back-office\">Back-office<\/h2>\n\n\n\n<figure class=\"wp-block-image aligncenter size-full  \"><img loading=\"lazy\" decoding=\"async\" width=\"2131\" height=\"727\" src=\"https:\/\/wypo.io\/wp-content\/uploads\/2024\/11\/wypo-wp-form-master-exemples-ajout-champ-personnalise.jpg\" alt=\"Wypo Wp Form Master Exemples Ajout Champ Personnalise\" class=\"wp-image-3176\" style=\"object-fit:cover\" srcset=\"https:\/\/wypo.io\/wp-content\/uploads\/2024\/11\/wypo-wp-form-master-exemples-ajout-champ-personnalise.jpg 2131w, https:\/\/wypo.io\/wp-content\/uploads\/2024\/11\/wypo-wp-form-master-exemples-ajout-champ-personnalise-300x102.jpg 300w, https:\/\/wypo.io\/wp-content\/uploads\/2024\/11\/wypo-wp-form-master-exemples-ajout-champ-personnalise-1024x349.jpg 1024w, https:\/\/wypo.io\/wp-content\/uploads\/2024\/11\/wypo-wp-form-master-exemples-ajout-champ-personnalise-768x262.jpg 768w, https:\/\/wypo.io\/wp-content\/uploads\/2024\/11\/wypo-wp-form-master-exemples-ajout-champ-personnalise-1536x524.jpg 1536w, https:\/\/wypo.io\/wp-content\/uploads\/2024\/11\/wypo-wp-form-master-exemples-ajout-champ-personnalise-2048x699.jpg 2048w\" sizes=\"(max-width: 2131px) 100vw, 2131px\" \/><\/figure>\n\n                    <\/div>\r\n                <\/div>\r\n            <\/div>\r\n            ","protected":false},"featured_media":0,"parent":3178,"menu_order":5,"template":"","meta":{"_habefastfse_class":"","hf_wpseo_meta_title":"Add a custom field in WP Form Master [separator] [sitetitle]","hf_wpseo_meta_description":"Learn how to integrate a custom post selection field into the WP Form Master plugin. Follow this detailed example to display a drop-down list of posts in your WordPress forms, with optimized validation and data extraction.","hf_wpseo_meta_robots_index":"","hf_wpseo_meta_robots_follow":true,"hf_wpseo_meta_robots_advanced":"{}","hf_wpseo_meta_canonical_url":"","documentation_description":"","documentation_menu_text":"","documentation_related_pageid":0,"wypo_hidden_role_wypo_users_not_logged":false,"wypo_visibility_role_wypo_users_not_logged":false,"wypo_hidden_role_administrator":false,"wypo_visibility_role_administrator":false,"wypo_hidden_role_habefast":false,"wypo_visibility_role_habefast":false,"wypo_hidden_role_customer":false,"wypo_visibility_role_customer":false,"wypo_hidden_role_habefast_manager":false,"wypo_visibility_role_habefast_manager":false,"wypo_hidden_for_role":false,"wypo_visibility_for_role":false},"class_list":["post-3179","wypo_documentations","type-wypo_documentations","status-publish","hentry"],"_links":{"self":[{"href":"https:\/\/wypo.io\/en\/wp-json\/wp\/v2\/wypo_documentations\/3179","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/wypo.io\/en\/wp-json\/wp\/v2\/wypo_documentations"}],"about":[{"href":"https:\/\/wypo.io\/en\/wp-json\/wp\/v2\/types\/wypo_documentations"}],"up":[{"embeddable":true,"href":"https:\/\/wypo.io\/en\/wp-json\/wp\/v2\/wypo_documentations\/3178"}],"wp:attachment":[{"href":"https:\/\/wypo.io\/en\/wp-json\/wp\/v2\/media?parent=3179"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}