qid
int64
4
8.14M
question
stringlengths
20
48.3k
answers
list
date
stringlengths
10
10
metadata
list
input
stringlengths
12
45k
output
stringlengths
2
31.8k
262,754
<p>I need to fill form fields with post_meta from an ajax response. </p> <p>Everything works properly. </p> <p>I could hard-code the swapping of each piece of data.meta into its form field. But that approach is not reusable. </p> <p>Is there a way to loop through the data.meta instead? </p> <p>In some cases, there may not be meta for all the form fields. And in some cases, there may be meta that is not applicable to the form. </p> <p>This is for a form in a bootstrap modal window. </p> <pre><code>$.ajax({ ... success: function (data) { if (data.status === 'success') { $('#title').val(data.title); $.each(data.meta, function(key,value) { alert(key + '---' + value[0]); // if key is a form element, add the value to that element // if key is a form element that is a select dropdown, // then mark that option as selected }); } } }); </code></pre>
[ { "answer_id": 262762, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 1, "selected": false, "text": "<p>First, I can count on one finger the number of times A code which was developed in the hope of being \"reusable\" was actually reused. Write the code to the specification you can test against. \"Reusable\" is not a specification you can test against until you have a proper idea what will you need in the future, will is always hard for people that are not future tellers ;)</p>\n\n<p>Second, this means that all meta data should be queriable from the outside which is a security/privacy nightmare as you will have an end point that can be used to query intimate data that might never be displayed in the open. This is BTW the reason that you need to explicitly opt-in meta fields in order to be able to use them in the REST API.</p>\n" }, { "answer_id": 262871, "author": "shanebp", "author_id": 16575, "author_profile": "https://wordpress.stackexchange.com/users/16575", "pm_score": 1, "selected": true, "text": "<p>This works for me and is reusable. It assumes your form field ids match your post_meta keys.</p>\n\n<pre><code>if (data.status === 'success') {\n\n // populate form with post_meta\n $.each(data.meta, function(key,value) {\n\n //alert(key + '---' + value[0]);\n\n var $form_element = $(\"#\" + key);\n\n if ( $form_element.length &gt; 0 ) {\n\n // check if $form_element is a selector\n if( $form_element.prop('type') == 'select-one' ) \n modal.find($form_element).val(value).change();\n else\n modal.find(\"#\" + key).val(value);\n //modal.find($form_element).val(value);\n\n\n }\n\n });\n\n}\n</code></pre>\n" } ]
2017/04/06
[ "https://wordpress.stackexchange.com/questions/262754", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/16575/" ]
I need to fill form fields with post\_meta from an ajax response. Everything works properly. I could hard-code the swapping of each piece of data.meta into its form field. But that approach is not reusable. Is there a way to loop through the data.meta instead? In some cases, there may not be meta for all the form fields. And in some cases, there may be meta that is not applicable to the form. This is for a form in a bootstrap modal window. ``` $.ajax({ ... success: function (data) { if (data.status === 'success') { $('#title').val(data.title); $.each(data.meta, function(key,value) { alert(key + '---' + value[0]); // if key is a form element, add the value to that element // if key is a form element that is a select dropdown, // then mark that option as selected }); } } }); ```
This works for me and is reusable. It assumes your form field ids match your post\_meta keys. ``` if (data.status === 'success') { // populate form with post_meta $.each(data.meta, function(key,value) { //alert(key + '---' + value[0]); var $form_element = $("#" + key); if ( $form_element.length > 0 ) { // check if $form_element is a selector if( $form_element.prop('type') == 'select-one' ) modal.find($form_element).val(value).change(); else modal.find("#" + key).val(value); //modal.find($form_element).val(value); } }); } ```
262,759
<p>I'm using the Wordpress Plugin Boilerplate to make a plugin and I'm having some trouble outputting a form for users to input configuration options for the said plugin.</p> <p>I have the following methods for a class</p> <pre><code>public function admin_add_menu() { add_menu_page( 'Paypal Me Order', 'Paypal Me', 'manage_options', 'paypal_me_order', array($this, 'admin_display'), 'dashicons-fa-cc-paypal', 20 ); } function admin_init() { register_setting( 'paypal_me_order-group', 'paypal_me_order-option', array( $this , 'sanitize') ); add_settings_section( 'paypal_me_order-section', 'Paypal Me Settings', array( $this, 'admin_section' ), 'paypal_me_order' ); add_settings_field( 'paypal_me_order-link', 'Paypal Me Link', array( $this, 'admn_link_field' ), 'paypal_me_order', 'paypal_me_order-section' ); } function admin_display (){ include plugin_dir_path(__FILE__) . 'partials/paypal_me_order-admin-display.php'; } public function admin_section($args) { include plugin_dir_path(__FILE__) . 'partials/paypal_me_order-admin-section-display.php'; } public function admin_link_field( $args) { include plugin_dir_path(__FILE__) . 'partials/paypal_me_order-link-field.php'; } </code></pre> <p>Inside <code>admin_display()</code></p> <pre><code>&lt;form action="options.php" method="POST"&gt; &lt;?php settings_fields('paypal_me_order-group'); ?&gt; &lt;?php do_settings_sections('paypal_me_order-section'); ?&gt; &lt;?php submit_button(); ?&gt; &lt;/form&gt; </code></pre> <p>I get the top level menu and the Page shows up but not the "section" or the "fields"</p> <p>What am I doing wrong here? Why is it not working?</p> <p><strong>UPDATE</strong></p> <p>I am able to get the page to display but I cannot get the input field to print.</p>
[ { "answer_id": 262819, "author": "MagniGeeks Technologies", "author_id": 116950, "author_profile": "https://wordpress.stackexchange.com/users/116950", "pm_score": 3, "selected": false, "text": "<p>Try this. Please change the field name with yours</p>\n\n<pre><code>&lt;?php\nclass MySettingsPage\n{\n /**\n * Holds the values to be used in the fields callbacks\n */\n private $options;\n\n /**\n * Start up\n */\n public function __construct()\n {\n add_action( 'admin_menu', array( $this, 'add_plugin_page' ) );\n add_action( 'admin_init', array( $this, 'page_init' ) );\n }\n\n /**\n * Add options page\n */\n public function add_plugin_page()\n {\n // This page will be under \"Settings\"\n add_options_page(\n 'Settings Admin', \n 'My Settings', \n 'manage_options', \n 'my-setting-admin', \n array( $this, 'create_admin_page' )\n );\n }\n\n /**\n * Options page callback\n */\n public function create_admin_page()\n {\n // Set class property\n $this-&gt;options = get_option( 'my_option_name' );\n ?&gt;\n &lt;div class=\"wrap\"&gt;\n &lt;h1&gt;My Settings&lt;/h1&gt;\n &lt;form method=\"post\" action=\"options.php\"&gt;\n &lt;?php\n // This prints out all hidden setting fields\n settings_fields( 'my_option_group' );\n do_settings_sections( 'my-setting-admin' );\n submit_button();\n ?&gt;\n &lt;/form&gt;\n &lt;/div&gt;\n &lt;?php\n }\n\n /**\n * Register and add settings\n */\n public function page_init()\n { \n register_setting(\n 'my_option_group', // Option group\n 'my_option_name', // Option name\n array( $this, 'sanitize' ) // Sanitize\n );\n\n add_settings_section(\n 'setting_section_id', // ID\n 'My Custom Settings', // Title\n array( $this, 'print_section_info' ), // Callback\n 'my-setting-admin' // Page\n ); \n\n add_settings_field(\n 'id_number', // ID\n 'ID Number', // Title \n array( $this, 'id_number_callback' ), // Callback\n 'my-setting-admin', // Page\n 'setting_section_id' // Section \n ); \n\n add_settings_field(\n 'title', \n 'Title', \n array( $this, 'title_callback' ), \n 'my-setting-admin', \n 'setting_section_id'\n ); \n }\n\n /**\n * Sanitize each setting field as needed\n *\n * @param array $input Contains all settings fields as array keys\n */\n public function sanitize( $input )\n {\n $new_input = array();\n if( isset( $input['id_number'] ) )\n $new_input['id_number'] = absint( $input['id_number'] );\n\n if( isset( $input['title'] ) )\n $new_input['title'] = sanitize_text_field( $input['title'] );\n\n return $new_input;\n }\n\n /** \n * Print the Section text\n */\n public function print_section_info()\n {\n print 'Enter your settings below:';\n }\n\n /** \n * Get the settings option array and print one of its values\n */\n public function id_number_callback()\n {\n printf(\n '&lt;input type=\"text\" id=\"id_number\" name=\"my_option_name[id_number]\" value=\"%s\" /&gt;',\n isset( $this-&gt;options['id_number'] ) ? esc_attr( $this-&gt;options['id_number']) : ''\n );\n }\n\n /** \n * Get the settings option array and print one of its values\n */\n public function title_callback()\n {\n printf(\n '&lt;input type=\"text\" id=\"title\" name=\"my_option_name[title]\" value=\"%s\" /&gt;',\n isset( $this-&gt;options['title'] ) ? esc_attr( $this-&gt;options['title']) : ''\n );\n }\n}\n\nif( is_admin() )\n $my_settings_page = new MySettingsPage();\n</code></pre>\n" }, { "answer_id": 262844, "author": "Kendall", "author_id": 83851, "author_profile": "https://wordpress.stackexchange.com/users/83851", "pm_score": -1, "selected": true, "text": "<p>Turns out it was a typo in my functions. I can now see the settings page perfectly!</p>\n" } ]
2017/04/07
[ "https://wordpress.stackexchange.com/questions/262759", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/83851/" ]
I'm using the Wordpress Plugin Boilerplate to make a plugin and I'm having some trouble outputting a form for users to input configuration options for the said plugin. I have the following methods for a class ``` public function admin_add_menu() { add_menu_page( 'Paypal Me Order', 'Paypal Me', 'manage_options', 'paypal_me_order', array($this, 'admin_display'), 'dashicons-fa-cc-paypal', 20 ); } function admin_init() { register_setting( 'paypal_me_order-group', 'paypal_me_order-option', array( $this , 'sanitize') ); add_settings_section( 'paypal_me_order-section', 'Paypal Me Settings', array( $this, 'admin_section' ), 'paypal_me_order' ); add_settings_field( 'paypal_me_order-link', 'Paypal Me Link', array( $this, 'admn_link_field' ), 'paypal_me_order', 'paypal_me_order-section' ); } function admin_display (){ include plugin_dir_path(__FILE__) . 'partials/paypal_me_order-admin-display.php'; } public function admin_section($args) { include plugin_dir_path(__FILE__) . 'partials/paypal_me_order-admin-section-display.php'; } public function admin_link_field( $args) { include plugin_dir_path(__FILE__) . 'partials/paypal_me_order-link-field.php'; } ``` Inside `admin_display()` ``` <form action="options.php" method="POST"> <?php settings_fields('paypal_me_order-group'); ?> <?php do_settings_sections('paypal_me_order-section'); ?> <?php submit_button(); ?> </form> ``` I get the top level menu and the Page shows up but not the "section" or the "fields" What am I doing wrong here? Why is it not working? **UPDATE** I am able to get the page to display but I cannot get the input field to print.
Turns out it was a typo in my functions. I can now see the settings page perfectly!
262,792
<p>I have a child theme for twenty-seventeen and am trying to get the possibility to set sections to a one-column layout while the other ones still have their two-columns layout.</p> <p>There seems to be an <a href="https://wordpress.org/support/topic/remove-two-column-display-for-just-a-single-page/" rel="nofollow noreferrer">idea</a> for a solution where a page template is created and a function is inserted into <code>functions.php</code>: </p> <pre><code>add_filter( 'body_class', 'one_column_page_body_classes', 12 ); function one_column_page_body_classes( $classes ) { if ( is_page_template( 'template-parts/one-column-page.php' ) &amp;&amp; in_array('page-two-column', $classes) ) { unset( $classes[array_search('page-two-column', $classes)] ); $classes[] = 'page-one-column'; } return $classes; } </code></pre> <p>I did not manage to get this working.</p> <p>Thanks in advance!</p>
[ { "answer_id": 262830, "author": "Martin", "author_id": 117148, "author_profile": "https://wordpress.stackexchange.com/users/117148", "pm_score": 1, "selected": false, "text": "<p>I found an <a href=\"https://wordpress.org/support/topic/applying-one-column-layout-to-a-specific-front-page-panel/\" rel=\"nofollow noreferrer\">answer</a>, but maybe there is a better way using page-templates and applying the change directly.</p>\n\n<p>For now, it's possible to apply the following in the stylesheet:</p>\n\n<pre><code>body.page-two-column:not(.archive) #primary #panel1 .entry-header{ \n width: 100%;\n}\nbody.page-two-column:not(.archive) #primary #panel1 .entry-content, body.page-two-column #panel1 #comments{\n width: 100%;\n}\n</code></pre>\n\n<p>Altering the <code>#panel</code> number you can hard code the fix onto the respective section.</p>\n" }, { "answer_id": 357708, "author": "Andre", "author_id": 182021, "author_profile": "https://wordpress.stackexchange.com/users/182021", "pm_score": 0, "selected": false, "text": "<p>To make Twenty Seventeen full width in WordPress, add the following CSS to your theme’s CSS file, or in Customizer’s Additional CSS:</p>\n\n<pre><code>.wrap {\n max-width: 100%;\n}\n\n@media screen and (min-width: 48em) {\n .wrap {\n max-width: 100%;\n }\n}\n\n.page.page-one-column:not(.twentyseventeen-front-page) #primary {\n max-width: 100%;\n}\n\n@media screen and (min-width: 30em) {\n .page-one-column .panel-content .wrap {\n max-width: 100%;\n }\n}\n</code></pre>\n\n<p>You can adjust the 100% values. Set these to 90% for example for a 90% main content width.</p>\n" } ]
2017/04/07
[ "https://wordpress.stackexchange.com/questions/262792", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/117148/" ]
I have a child theme for twenty-seventeen and am trying to get the possibility to set sections to a one-column layout while the other ones still have their two-columns layout. There seems to be an [idea](https://wordpress.org/support/topic/remove-two-column-display-for-just-a-single-page/) for a solution where a page template is created and a function is inserted into `functions.php`: ``` add_filter( 'body_class', 'one_column_page_body_classes', 12 ); function one_column_page_body_classes( $classes ) { if ( is_page_template( 'template-parts/one-column-page.php' ) && in_array('page-two-column', $classes) ) { unset( $classes[array_search('page-two-column', $classes)] ); $classes[] = 'page-one-column'; } return $classes; } ``` I did not manage to get this working. Thanks in advance!
I found an [answer](https://wordpress.org/support/topic/applying-one-column-layout-to-a-specific-front-page-panel/), but maybe there is a better way using page-templates and applying the change directly. For now, it's possible to apply the following in the stylesheet: ``` body.page-two-column:not(.archive) #primary #panel1 .entry-header{ width: 100%; } body.page-two-column:not(.archive) #primary #panel1 .entry-content, body.page-two-column #panel1 #comments{ width: 100%; } ``` Altering the `#panel` number you can hard code the fix onto the respective section.
262,796
<p>I built a custom post type where we can find a standard textarea/tinymce generated by <code>wp_editor()</code> and I'm facing an issue for the saving part.</p> <p>If I save the content with the following code : </p> <pre><code>update_post_meta( $post_id, $prefix.'content', $_POST['content'] ); </code></pre> <p>Everything is working fine but there is no security (sanitization, validation etc...)</p> <p>If I save the content with the following code : </p> <pre><code>update_post_meta( $post_id, $prefix.'content', sanitize_text_field($_POST['content']) ); </code></pre> <p>I solve the security issue but I lose all the style, media etc.. in the content.</p> <p>What could be a good way to save the content with all the style applied, the media inserted but including a sanitization ?</p> <p>I read a bit about <code>wp_kses()</code> but I don't know how I could apply a good filter. (Allowing common tags, which one should I block ? etc..)</p>
[ { "answer_id": 262918, "author": "Melch Wanga", "author_id": 117213, "author_profile": "https://wordpress.stackexchange.com/users/117213", "pm_score": 2, "selected": false, "text": "<p>Try </p>\n\n<pre><code>//save this in the database\n$content=sanitize_text_field( htmlentities($_POST['content']) );\n\n//to display, use\nhtml_entity_decode($content);\n</code></pre>\n\n<ol>\n<li><code>htmlentities()</code> will convert all characters which have HTML character entity equivalents to their equivalents.</li>\n<li><code>sanitize_text_field()</code> will then check for invalid UTF-8 characters and strip them off. This can now be stored in the database.</li>\n<li><code>html_entity_decode()</code> will convert HTML entities to their HTML tag equivalents</li>\n</ol>\n" }, { "answer_id": 292507, "author": "bueltge", "author_id": 170, "author_profile": "https://wordpress.stackexchange.com/users/170", "pm_score": 3, "selected": false, "text": "<p>In short: it is in dependence of your context, the data inside your editor.</p>\n<p><code>wp_kses()</code> is really helpful, and you can define your custom allowed HTML tags.\nAlternative, you can use the default functions, like <a href=\"https://codex.wordpress.org/Function_Reference/wp_kses_post\" rel=\"nofollow noreferrer\"><code>wp_kses_post</code></a> or <a href=\"https://codex.wordpress.org/Function_Reference/wp_kses_data\" rel=\"nofollow noreferrer\"><code>wp_kses_data</code></a>.\nThese functions are helpful in ensuring that HTML received from the user only contains white-listed elements. See <a href=\"https://codex.wordpress.org/Data_Validation#HTML.2FXML_Fragments\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Data_Validation#HTML.2FXML_Fragments</a></p>\n<p>WordPress defines much more functions to sanitize the input, see <a href=\"https://codex.wordpress.org/Validating_Sanitizing_and_Escaping_User_Data\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Validating_Sanitizing_and_Escaping_User_Data</a> and <a href=\"https://codex.wordpress.org/Data_Validation\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Data_Validation</a>\nThese pages are really helpful.</p>\n<p>However, in your context should the <code>wp_kses_post</code> function, the right choice.</p>\n" }, { "answer_id": 295906, "author": "Ravi Patel", "author_id": 35477, "author_profile": "https://wordpress.stackexchange.com/users/35477", "pm_score": 0, "selected": false, "text": "<p><a href=\"https://codex.wordpress.org/Function_Reference/wp_slash\" rel=\"nofollow noreferrer\">wp_slash</a> More information.</p>\n\n<pre><code>update_post_meta( $post_id, $prefix.'content',wp_slash($_POST['content']) );\n</code></pre>\n" }, { "answer_id": 314404, "author": "Joe", "author_id": 90212, "author_profile": "https://wordpress.stackexchange.com/users/90212", "pm_score": 1, "selected": false, "text": "<p>You could do someting like this:\n</p>\n\n<pre>/**\n * Most of the 'post' HTML are excepted accept &lt;textarea&gt; itself.\n * @link https://codex.wordpress.org/Function_Reference/wp_kses_allowed_html\n */\n$allowed_html = wp_kses_allowed_html( 'post' );\n\n// Remove '&lt;textarea&gt;' tag\nunset ( $allowed_html['textarea'] );\n\n/**\n * wp_kses_allowed_html return the wrong values for wp_kses,\n * need to change \"true\" -> \"array()\"\n */\narray_walk_recursive(\n $allowed_html,\n function ( &$value ) {\n if ( is_bool( $value ) ) {\n $value = array();\n }\n }\n);\n// Run sanitization.\n$value = wp_kses( $value, $allowed_html );\n</pre>\n\n<p><strong>@fuxia:</strong> as OP wrote:<br>\n<em>\"I read a bit about wp_kses() but I don't know how I could apply a good filter. (Allowing common tags, which one should I block ? etc..)\"</em> </p>\n\n<p>wp_kses does the following:<br>\n<em>\"This function makes sure that only the allowed HTML element names, attribute names and attribute values plus only sane HTML entities will occur in $string. You have to remove any slashes from PHP's magic quotes before you call this function.\"</em><br>\n<a href=\"https://codex.wordpress.org/Function_Reference/wp_kses\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/wp_kses</a></p>\n\n<p>My code uses <code>wp_kses</code> with \"Allowing common tags\". What are the common tags? The list available to read in the given link. It is a long list, so I did not paste it here.<br>\n<a href=\"https://codex.wordpress.org/Function_Reference/wp_kses_allowed_html\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/wp_kses_allowed_html</a></p>\n\n<p>I think textarea itself should not be allowed in textarea. </p>\n\n<p><strong>@bueltge</strong><br>\nwp_kses_post does the same thing, except allow '&lt;textarea&gt;' tag, which - I think - shouldn't be.<br>\n<a href=\"https://core.trac.wordpress.org/browser/tags/4.9.8/src/wp-includes/kses.php#L1575\" rel=\"nofollow noreferrer\">https://core.trac.wordpress.org/browser/tags/4.9.8/src/wp-includes/kses.php#L1575</a><br></p>\n\n<pre>\nfunction wp_kses_post( $data ) {\n return wp_kses( $data, 'post' );\n}\n</pre>\n" } ]
2017/04/07
[ "https://wordpress.stackexchange.com/questions/262796", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/117153/" ]
I built a custom post type where we can find a standard textarea/tinymce generated by `wp_editor()` and I'm facing an issue for the saving part. If I save the content with the following code : ``` update_post_meta( $post_id, $prefix.'content', $_POST['content'] ); ``` Everything is working fine but there is no security (sanitization, validation etc...) If I save the content with the following code : ``` update_post_meta( $post_id, $prefix.'content', sanitize_text_field($_POST['content']) ); ``` I solve the security issue but I lose all the style, media etc.. in the content. What could be a good way to save the content with all the style applied, the media inserted but including a sanitization ? I read a bit about `wp_kses()` but I don't know how I could apply a good filter. (Allowing common tags, which one should I block ? etc..)
In short: it is in dependence of your context, the data inside your editor. `wp_kses()` is really helpful, and you can define your custom allowed HTML tags. Alternative, you can use the default functions, like [`wp_kses_post`](https://codex.wordpress.org/Function_Reference/wp_kses_post) or [`wp_kses_data`](https://codex.wordpress.org/Function_Reference/wp_kses_data). These functions are helpful in ensuring that HTML received from the user only contains white-listed elements. See <https://codex.wordpress.org/Data_Validation#HTML.2FXML_Fragments> WordPress defines much more functions to sanitize the input, see <https://codex.wordpress.org/Validating_Sanitizing_and_Escaping_User_Data> and <https://codex.wordpress.org/Data_Validation> These pages are really helpful. However, in your context should the `wp_kses_post` function, the right choice.
262,801
<p>I have this code below, and I wish to show each link of each post, but I keep getting same link to all posts which is the link of the page.</p> <pre><code>$args = array('posts_per_page' =&gt; 5,'order' =&gt; 'DESC'); $rp = new WP_Query($args); if($rp-&gt;have_posts()) : while($rp-&gt;have_posts()) : $rp-&gt;the_post(); the_title(); $link=the_permalink(); echo '&lt;a href="'.$link.'"&gt;Welcome&lt;/a&gt;'; echo "&lt;br /&gt;"; endwhile; wp_reset_postdata(); endif; </code></pre> <p>Thank you.</p>
[ { "answer_id": 262802, "author": "Toir", "author_id": 117156, "author_profile": "https://wordpress.stackexchange.com/users/117156", "pm_score": 1, "selected": false, "text": "<pre><code>$args = array('posts_per_page' =&gt; 5, 'order' =&gt; 'DESC');\n$rp = new WP_Query($args);\nif ($rp-&gt;have_posts()) :\n $i = 0;\n $link = '';\n while ($rp-&gt;have_posts()) : $rp-&gt;the_post();\n the_title();\n if ($i == 0) $link = get_permalink();\n\n echo '&lt;a href=\"' . $link . '\"&gt;Welcome&lt;/a&gt;';\n echo \"&lt;br /&gt;\";\n $i++;\n endwhile;\n\n wp_reset_postdata();\n\nendif;\n</code></pre>\n\n<p>this core get only first post link</p>\n" }, { "answer_id": 262805, "author": "kiarashi", "author_id": 68619, "author_profile": "https://wordpress.stackexchange.com/users/68619", "pm_score": 4, "selected": true, "text": "<p>Don't forget to use <code>esc_url()</code></p>\n\n<pre><code>echo '&lt;a href=\"'. esc_url( $link ).'\"&gt;Welcome&lt;/a&gt;';\n</code></pre>\n\n<p>Also try this: <code>get_permalink( get_the_ID() );</code></p>\n" }, { "answer_id": 262809, "author": "MagniGeeks Technologies", "author_id": 116950, "author_profile": "https://wordpress.stackexchange.com/users/116950", "pm_score": 0, "selected": false, "text": "<p>You are missing get_the_ID() inside the loop. Thats why its showing the permalink of first post for each post inside the loop; </p>\n\n<p>Try this code</p>\n\n<pre><code>$args = array('posts_per_page' =&gt; 5,'order' =&gt; 'DESC');\n$rp = new WP_Query($args);\nif($rp-&gt;have_posts()) :\nwhile($rp-&gt;have_posts()) : $rp-&gt;the_post();\n\n the_title(); \n\n$link=get_the_permalink(get_the_ID()); //get_the_ID() gets the id of the post inside a loop\necho '&lt;a href=\"'.$link.'\"&gt;Welcome&lt;/a&gt;';\necho \"&lt;br /&gt;\";\n\nendwhile;\n\nwp_reset_postdata(); \n\nendif;\n</code></pre>\n\n<p><strong>Note:</strong> Please check the <a href=\"https://developer.wordpress.org/reference/functions/get_the_id/\" rel=\"nofollow noreferrer\">documentation</a> for better understanding.</p>\n" } ]
2017/04/07
[ "https://wordpress.stackexchange.com/questions/262801", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/117136/" ]
I have this code below, and I wish to show each link of each post, but I keep getting same link to all posts which is the link of the page. ``` $args = array('posts_per_page' => 5,'order' => 'DESC'); $rp = new WP_Query($args); if($rp->have_posts()) : while($rp->have_posts()) : $rp->the_post(); the_title(); $link=the_permalink(); echo '<a href="'.$link.'">Welcome</a>'; echo "<br />"; endwhile; wp_reset_postdata(); endif; ``` Thank you.
Don't forget to use `esc_url()` ``` echo '<a href="'. esc_url( $link ).'">Welcome</a>'; ``` Also try this: `get_permalink( get_the_ID() );`
262,804
<p>I am following an example on <a href="https://codex.wordpress.org/AJAX_in_Plugins" rel="nofollow noreferrer">AJAX in Plugins</a> on Wordpress website. It's very simple example, and I am trying to modify the example as I intend.</p> <p>What I am trying to achieve is simple:</p> <ul> <li>When a new option is selected in select/option dropdown, detect the selected value</li> <li>Pass the selected value to PHP function via AJAX</li> </ul> <p>However, the selected value doesn't seem to be passed via AJAX. The result I am getting is: whatever = 1234 | whatever2 = </p> <p>How do I properly pass my variable to AJAX?</p> <p>My code:</p> <pre><code>// Select/Option Dropdown &lt;select id="_type" name="_type"&gt; &lt;option value="AAA"&gt; AAA &lt;/option&gt; &lt;option value="BBB"&gt; BBB &lt;/option&gt; &lt;option value="CCC"&gt; CCC &lt;/option&gt; &lt;/select&gt; // Detect change and call and AJAX &lt;script type="text/javascript"&gt; jQuery('#_type'.change(function($) { var val = jQuery('#_type').val(); &lt;-- Here I am properly getting val as it changes. console.log( '_type is changed to ' + val ); var data = { 'action': 'my_action', 'type': 'post', 'whatever': 1234, 'whatever2': val &lt;-- But here val becomes empty. }; jQuery.post(ajaxurl, data, function(response) { alert( 'Got this from the server: ' + response ); }); }).change(); &lt;/script&gt; // PHP function 'my_action' add_action( 'wp_ajax_my_action', 'my_action' ); function my_action() { global $wpdb; $whatever = $_POST['whatever']; $whatever2 = $_POST['whatever2']; echo 'whatever = ' . $whatever . ' | whatever2 = ' . $whatever2; wp_die(); } </code></pre>
[ { "answer_id": 262806, "author": "kiarashi", "author_id": 68619, "author_profile": "https://wordpress.stackexchange.com/users/68619", "pm_score": 0, "selected": false, "text": "<p>Try adding <code>type : 'post',</code> inside <code>data = {...}</code>\nAlso, I'm missing 'security' inside your ajax function.</p>\n\n<p>Could you add this and show us the results:</p>\n\n<pre><code>.success( function( results ) {\n console.log( val );\n } )\n</code></pre>\n" }, { "answer_id": 262814, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 3, "selected": true, "text": "<p><strong>The simple answer:</strong> Don't bother with the Admin AJAX API, use the REST API!</p>\n\n<p>Tell WordPress about your endpoint:</p>\n\n<pre><code>add_action( 'rest_api_init', function () { // register dongsan/v1/whatever\n register_rest_route( 'dongsan/v1', '/whatever/', array(\n 'methods' =&gt; 'POST', // use POST to call it\n 'callback' =&gt; 'dongsan_whatever' // call this function\n ) );\n} );\n</code></pre>\n\n<p>Now we have an endpoint at <code>example.com/wp-json/dongsan/v1/whatever</code>!</p>\n\n<p>We told WordPress to run <code>dongsan_whatever</code> when it gets called, so lets do that:</p>\n\n<pre><code>function dongsan_whatever( \\WP_REST_Request $request ) {\n $name = $request['name'];\n return 'hello '.$name;\n}\n</code></pre>\n\n<p>Note that we used <code>$request['name']</code> to get a name parameter!</p>\n\n<p>So we have a URL:</p>\n\n<pre><code>example.com/wp-json/dongsan/v1/whatever\n</code></pre>\n\n<p>And we can send a POST request with a name to it and get some JSON back that says Hello 'name'! So how do we do that?</p>\n\n<p>Simples, it's a standard <a href=\"https://api.jquery.com/jquery.post/\" rel=\"nofollow noreferrer\">jQuery post</a> request:</p>\n\n<pre><code>jQuery.post(\n 'https://example.com/wp-json/dongsan/v1/whatever',\n { 'name': 'Dongsan' }\n).done( function( data ) {\n Console.log( data ); // most likely \"Hello Dongsan\"\n} );\n</code></pre>\n\n<p>Further reading:</p>\n\n<ul>\n<li><a href=\"https://tomjn.com/2017/01/23/writing-wp-rest-api-endpoint-2-minutes/\" rel=\"nofollow noreferrer\">https://tomjn.com/2017/01/23/writing-wp-rest-api-endpoint-2-minutes/</a></li>\n<li><a href=\"https://developer.wordpress.org/rest-api/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/rest-api/</a></li>\n</ul>\n" }, { "answer_id": 262815, "author": "MagniGeeks Technologies", "author_id": 116950, "author_profile": "https://wordpress.stackexchange.com/users/116950", "pm_score": 2, "selected": false, "text": "<p>Just tested your code and it seems to be working fine. Just make sure to add a bracket to the change function <code>jQuery('#_type').change(function($)</code></p>\n\n<p>Also, you need to add <code>no_priv</code> action if you are using the ajax on frontend</p>\n\n<pre><code>add_action( 'wp_ajax_nopriv_my_action', 'my_action' );\n</code></pre>\n\n<p>Check and let me know if this works for you.</p>\n" } ]
2017/04/07
[ "https://wordpress.stackexchange.com/questions/262804", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/116656/" ]
I am following an example on [AJAX in Plugins](https://codex.wordpress.org/AJAX_in_Plugins) on Wordpress website. It's very simple example, and I am trying to modify the example as I intend. What I am trying to achieve is simple: * When a new option is selected in select/option dropdown, detect the selected value * Pass the selected value to PHP function via AJAX However, the selected value doesn't seem to be passed via AJAX. The result I am getting is: whatever = 1234 | whatever2 = How do I properly pass my variable to AJAX? My code: ``` // Select/Option Dropdown <select id="_type" name="_type"> <option value="AAA"> AAA </option> <option value="BBB"> BBB </option> <option value="CCC"> CCC </option> </select> // Detect change and call and AJAX <script type="text/javascript"> jQuery('#_type'.change(function($) { var val = jQuery('#_type').val(); <-- Here I am properly getting val as it changes. console.log( '_type is changed to ' + val ); var data = { 'action': 'my_action', 'type': 'post', 'whatever': 1234, 'whatever2': val <-- But here val becomes empty. }; jQuery.post(ajaxurl, data, function(response) { alert( 'Got this from the server: ' + response ); }); }).change(); </script> // PHP function 'my_action' add_action( 'wp_ajax_my_action', 'my_action' ); function my_action() { global $wpdb; $whatever = $_POST['whatever']; $whatever2 = $_POST['whatever2']; echo 'whatever = ' . $whatever . ' | whatever2 = ' . $whatever2; wp_die(); } ```
**The simple answer:** Don't bother with the Admin AJAX API, use the REST API! Tell WordPress about your endpoint: ``` add_action( 'rest_api_init', function () { // register dongsan/v1/whatever register_rest_route( 'dongsan/v1', '/whatever/', array( 'methods' => 'POST', // use POST to call it 'callback' => 'dongsan_whatever' // call this function ) ); } ); ``` Now we have an endpoint at `example.com/wp-json/dongsan/v1/whatever`! We told WordPress to run `dongsan_whatever` when it gets called, so lets do that: ``` function dongsan_whatever( \WP_REST_Request $request ) { $name = $request['name']; return 'hello '.$name; } ``` Note that we used `$request['name']` to get a name parameter! So we have a URL: ``` example.com/wp-json/dongsan/v1/whatever ``` And we can send a POST request with a name to it and get some JSON back that says Hello 'name'! So how do we do that? Simples, it's a standard [jQuery post](https://api.jquery.com/jquery.post/) request: ``` jQuery.post( 'https://example.com/wp-json/dongsan/v1/whatever', { 'name': 'Dongsan' } ).done( function( data ) { Console.log( data ); // most likely "Hello Dongsan" } ); ``` Further reading: * <https://tomjn.com/2017/01/23/writing-wp-rest-api-endpoint-2-minutes/> * <https://developer.wordpress.org/rest-api/>
262,823
<p>After using WPML Media, a plugin that creates duplicates of each image for each language, we now have almost 100,000 duplicate images that we're not going to use and need to get rid of.</p> <p>We need to not only delete these from the filesystem itself, but also need to make sure that deleting all references in the database as would typically happen if one were to manually delete them through the media gallery.</p> <p>I'm looking for a WP-CLI solution, if it's possible. This solution was very helpful, but it does all images, not just those that are unattached / unused within the system.</p> <p><a href="https://wordpress.stackexchange.com/questions/182817/how-can-i-bulk-delete-media-and-attachments-using-wp-cli">How can I bulk delete media and attachments using WP-CLI?</a></p> <p>Given another solution, the OP put in the comments that he achieved his solution ultimately with SQL. </p> <p><a href="https://wordpress.stackexchange.com/questions/163207/how-do-i-delete-thousands-of-unattached-images">How do I delete thousands of unattached images?</a></p> <p>I'm no stranger to the command line or mysql, but am not familiar enough with WP tables to create a query to maintain the integrity of the database. If you are, then please suggest a pure database related solution, or PHP script that would hook into the system and do things the "wordpress" way.</p> <p>I am not looking for a plugin based solution. I have tried DNUI, DX Delete Attached Media, and a score of others that all ended badly.</p> <p>UPDATE: Using "parent=0" to determine if an image is attached or not was a very clever solution, and I marked it as the answer.</p> <p>There is a way to legitimately use an image in a post and the parent still equals 0; that's when you visit the image details in the media library, and you copy the full image source URL to be manually pasted into a post. <strong>The accepted answer's solution will delete these as well.</strong> Because of that, I would like to encourage other solutions too that would take this into consideration.</p> <p>That would perhaps require scanning the database to find instances of the image name, perhaps similar to the algorithm wp-cli search-replace would use?</p>
[ { "answer_id": 262835, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 5, "selected": true, "text": "<p>You can try this (untested) modification to the answer you linked to by @something</p>\n\n<pre><code>wp post delete $(wp post list --post_type='attachment' --format=ids --post_parent=0)\n</code></pre>\n\n<p>to delete attachments <strong>without parents</strong>.</p>\n\n<p>To target a given <code>mime type</code>, e.g. <code>image/jpeg</code> try:</p>\n\n<pre><code>wp post delete $(wp post list --post_type='attachment' \\\n --format=ids --post_parent=0 --post_mime_type='image/jpeg')\n</code></pre>\n\n<p><strong>Notes:</strong> </p>\n\n<ul>\n<li><p>Remember to backup first before testing! </p></li>\n<li><p>Unattached images might still be used in the post content or e.g. in widgets.</p></li>\n</ul>\n" }, { "answer_id": 377017, "author": "Bart Dabek", "author_id": 196524, "author_profile": "https://wordpress.stackexchange.com/users/196524", "pm_score": 2, "selected": false, "text": "<p>The accepted answer will not delete unattached media for attachments where the parent doesn't exist anymore... this could happen when parents are deleted via the db or some other process that doesn't mark the attached media parents as 0.</p>\n<p>Here is a cli command that will do that check.</p>\n<pre><code>wp post delete $(wp db query --skip-column-names --batch &quot;select DISTINCT p1.ID from wp_posts p1\nleft join wp_posts p2 ON p1.post_parent = p2.ID\nwhere p1.post_type = 'attachment'\nAND p2.ID is NULL&quot;) --force\n</code></pre>\n" }, { "answer_id": 403064, "author": "jadkik94", "author_id": 219610, "author_profile": "https://wordpress.stackexchange.com/users/219610", "pm_score": 1, "selected": false, "text": "<p>I had a similar issue but it involved images that were taking space without being in the database (some interrupted uploads/crashes, or wp post delete messing up, or restoring from backups). Kind of at the crossroads between this question and <a href=\"https://wordpress.stackexchange.com/q/149156\">that one</a>.</p>\n<p>I ended up using a solution based on a variation of the other two answers:</p>\n<pre class=\"lang-bash prettyprint-override\"><code># List all attachment URLs,\n# ... remove the host part and replace by regex fragment &quot;^\\./&quot; (first sed),\n# ... replace extension by empty string to match WP resizes (second sed)\n# ... and write list on terminal and in /tmp/files.txt\n# ... and see them in the less pager in case there's a lot of output\nwp post list --post_type='attachment' --field=guid 2&gt;/dev/null | \\\n sed 's#^.*//[^/]*/#^\\\\./#g' | \\\n sed 's#[.][^.]*$##' | \\\n tee /tmp/files.txt | \\\n less\n\n# Find all files (not directories) that correspond to media uploads\n# ... NOT matching the ones we found in the database\n# ... and see them in the less pager in case there's a lot of output\nfind ./wp-content/uploads/20* -type f | \\\n grep -E -f /tmp/files.txt -v | \\\n less\n</code></pre>\n<p>(the weird <code>sed</code> commands can probably be replaced with a fancy <code>wp db query</code> instead)</p>\n<p>You can modify the <code>grep</code> command by adding <code>-c</code> (to count files that match / don't match) or remove <code>-v</code> (to see files that DO have a match in the database).</p>\n" } ]
2017/04/07
[ "https://wordpress.stackexchange.com/questions/262823", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/37934/" ]
After using WPML Media, a plugin that creates duplicates of each image for each language, we now have almost 100,000 duplicate images that we're not going to use and need to get rid of. We need to not only delete these from the filesystem itself, but also need to make sure that deleting all references in the database as would typically happen if one were to manually delete them through the media gallery. I'm looking for a WP-CLI solution, if it's possible. This solution was very helpful, but it does all images, not just those that are unattached / unused within the system. [How can I bulk delete media and attachments using WP-CLI?](https://wordpress.stackexchange.com/questions/182817/how-can-i-bulk-delete-media-and-attachments-using-wp-cli) Given another solution, the OP put in the comments that he achieved his solution ultimately with SQL. [How do I delete thousands of unattached images?](https://wordpress.stackexchange.com/questions/163207/how-do-i-delete-thousands-of-unattached-images) I'm no stranger to the command line or mysql, but am not familiar enough with WP tables to create a query to maintain the integrity of the database. If you are, then please suggest a pure database related solution, or PHP script that would hook into the system and do things the "wordpress" way. I am not looking for a plugin based solution. I have tried DNUI, DX Delete Attached Media, and a score of others that all ended badly. UPDATE: Using "parent=0" to determine if an image is attached or not was a very clever solution, and I marked it as the answer. There is a way to legitimately use an image in a post and the parent still equals 0; that's when you visit the image details in the media library, and you copy the full image source URL to be manually pasted into a post. **The accepted answer's solution will delete these as well.** Because of that, I would like to encourage other solutions too that would take this into consideration. That would perhaps require scanning the database to find instances of the image name, perhaps similar to the algorithm wp-cli search-replace would use?
You can try this (untested) modification to the answer you linked to by @something ``` wp post delete $(wp post list --post_type='attachment' --format=ids --post_parent=0) ``` to delete attachments **without parents**. To target a given `mime type`, e.g. `image/jpeg` try: ``` wp post delete $(wp post list --post_type='attachment' \ --format=ids --post_parent=0 --post_mime_type='image/jpeg') ``` **Notes:** * Remember to backup first before testing! * Unattached images might still be used in the post content or e.g. in widgets.
262,832
<p>I have this simple code below:</p> <pre><code>function func1() { echo "this is amazing"; } add_action('reko_hook','func1'); </code></pre> <p>Now, I know that I could use <strong><em>reko_hook();</em></strong> either inside <strong><em>index.php</em></strong> or <strong><em>page.php</em></strong> where I want, but I was wondering if there are more pre-defined hooks such as '<strong><em>init</em></strong>'.</p> <p>For example, I could do</p> <pre><code>add_action('init','func1'); </code></pre> <p>but it will echo <strong><em>this is amazing</em></strong> before the header,</p> <p>The question is, if there are other pre-defined hooks to specify the location of the function output <strong><em>this is amazing</em></strong> to be placed:</p> <ol> <li><p>After the header, before the Page/Post title.</p></li> <li><p>After the header, after the Page/Post title.</p></li> <li><p>Before Footer.</p></li> <li><p>After the Footer.</p></li> </ol> <p>Thank you.</p>
[ { "answer_id": 262835, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 5, "selected": true, "text": "<p>You can try this (untested) modification to the answer you linked to by @something</p>\n\n<pre><code>wp post delete $(wp post list --post_type='attachment' --format=ids --post_parent=0)\n</code></pre>\n\n<p>to delete attachments <strong>without parents</strong>.</p>\n\n<p>To target a given <code>mime type</code>, e.g. <code>image/jpeg</code> try:</p>\n\n<pre><code>wp post delete $(wp post list --post_type='attachment' \\\n --format=ids --post_parent=0 --post_mime_type='image/jpeg')\n</code></pre>\n\n<p><strong>Notes:</strong> </p>\n\n<ul>\n<li><p>Remember to backup first before testing! </p></li>\n<li><p>Unattached images might still be used in the post content or e.g. in widgets.</p></li>\n</ul>\n" }, { "answer_id": 377017, "author": "Bart Dabek", "author_id": 196524, "author_profile": "https://wordpress.stackexchange.com/users/196524", "pm_score": 2, "selected": false, "text": "<p>The accepted answer will not delete unattached media for attachments where the parent doesn't exist anymore... this could happen when parents are deleted via the db or some other process that doesn't mark the attached media parents as 0.</p>\n<p>Here is a cli command that will do that check.</p>\n<pre><code>wp post delete $(wp db query --skip-column-names --batch &quot;select DISTINCT p1.ID from wp_posts p1\nleft join wp_posts p2 ON p1.post_parent = p2.ID\nwhere p1.post_type = 'attachment'\nAND p2.ID is NULL&quot;) --force\n</code></pre>\n" }, { "answer_id": 403064, "author": "jadkik94", "author_id": 219610, "author_profile": "https://wordpress.stackexchange.com/users/219610", "pm_score": 1, "selected": false, "text": "<p>I had a similar issue but it involved images that were taking space without being in the database (some interrupted uploads/crashes, or wp post delete messing up, or restoring from backups). Kind of at the crossroads between this question and <a href=\"https://wordpress.stackexchange.com/q/149156\">that one</a>.</p>\n<p>I ended up using a solution based on a variation of the other two answers:</p>\n<pre class=\"lang-bash prettyprint-override\"><code># List all attachment URLs,\n# ... remove the host part and replace by regex fragment &quot;^\\./&quot; (first sed),\n# ... replace extension by empty string to match WP resizes (second sed)\n# ... and write list on terminal and in /tmp/files.txt\n# ... and see them in the less pager in case there's a lot of output\nwp post list --post_type='attachment' --field=guid 2&gt;/dev/null | \\\n sed 's#^.*//[^/]*/#^\\\\./#g' | \\\n sed 's#[.][^.]*$##' | \\\n tee /tmp/files.txt | \\\n less\n\n# Find all files (not directories) that correspond to media uploads\n# ... NOT matching the ones we found in the database\n# ... and see them in the less pager in case there's a lot of output\nfind ./wp-content/uploads/20* -type f | \\\n grep -E -f /tmp/files.txt -v | \\\n less\n</code></pre>\n<p>(the weird <code>sed</code> commands can probably be replaced with a fancy <code>wp db query</code> instead)</p>\n<p>You can modify the <code>grep</code> command by adding <code>-c</code> (to count files that match / don't match) or remove <code>-v</code> (to see files that DO have a match in the database).</p>\n" } ]
2017/04/07
[ "https://wordpress.stackexchange.com/questions/262832", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/117136/" ]
I have this simple code below: ``` function func1() { echo "this is amazing"; } add_action('reko_hook','func1'); ``` Now, I know that I could use ***reko\_hook();*** either inside ***index.php*** or ***page.php*** where I want, but I was wondering if there are more pre-defined hooks such as '***init***'. For example, I could do ``` add_action('init','func1'); ``` but it will echo ***this is amazing*** before the header, The question is, if there are other pre-defined hooks to specify the location of the function output ***this is amazing*** to be placed: 1. After the header, before the Page/Post title. 2. After the header, after the Page/Post title. 3. Before Footer. 4. After the Footer. Thank you.
You can try this (untested) modification to the answer you linked to by @something ``` wp post delete $(wp post list --post_type='attachment' --format=ids --post_parent=0) ``` to delete attachments **without parents**. To target a given `mime type`, e.g. `image/jpeg` try: ``` wp post delete $(wp post list --post_type='attachment' \ --format=ids --post_parent=0 --post_mime_type='image/jpeg') ``` **Notes:** * Remember to backup first before testing! * Unattached images might still be used in the post content or e.g. in widgets.
262,862
<p><strong>SOLVED</strong></p> <p>See my answer below; I cannot immediately accept it.</p> <hr> <p><strong>Original post</strong></p> <p>I made a custom post type of <code>sector</code>:</p> <pre><code>register_post_type( 'sector', array( 'labels' =&gt; array( 'name' =&gt; __( 'Sectors' ), 'singular_name' =&gt; __( 'Sector' ) ), 'public' =&gt; true, 'has_archive' =&gt; false, 'rewrite' =&gt; array('slug' =&gt; 'sector') ) ); </code></pre> <p>I have a sector called "Hotels &amp; Hospitality" which resides at <code>site.com/sector/hotels-hospitality/</code>. I have other sectors that reside at other URLs.</p> <p>I also have a normal Page called "Sector" (which resides at <code>site.com/sector/</code>) and a subpage called "Hotels &amp; Hospitality" whose URL is also <code>site.com/sector/hotels-hospitality/</code>.</p> <p>At the moment, when I navigate to <code>site.com/sector/hotels-hospitality/</code> it's the post-type page that shows. Can I make it so that the normal Page shows instead? This is a special landing page for this sector.</p> <p>I tried this in the functions.php of my theme:</p> <pre><code>flush_rewrite_rules(); add_rewrite_rule( 'sector/hotels-hospitality/', 'index.php?page_id=1700', // 1700 = post_id of the Page 'top' ); </code></pre> <p>No luck so far! I have also tried it without the <code>'top'</code> param and this seemed to make no difference.</p> <p><strong>Related Info</strong></p> <p>After this I also edited the "Hotels &amp; Hospitality" sector post type slug from <code>site.com/sector/hotels-hospitality/</code> to <code>site.com/sector/hotels</code> (thinking that that way, at least I would be able to see the other page), <strike>but now when I go to <code>site.com/sector/hotels-hospitality/</code>, I am redirected to <code>site.com/sector/hotels/</code> and I can't undo it! I tried resaving permalinks...</strike></p> <p>I then tried renaming the Page to <code>site.com/sector/hotels-hospitality-page/</code> and this is now going to a 404.</p> <p>I am using a fresh install of Version 4.7.3.</p> <p><strong>Update</strong></p> <p>@WebElaine helped me delete the redirect from <code>site.com/sector/hotels-hospitality</code> to <code>site.com/sector/hotels</code> by deleting the _wp_old_slug field in wppostmeta.</p> <p><code>site.com/sector/hotels-hospitality-page/</code> is still going to a 404.</p> <p>Going to <code>site.com/index.php?page_id=1700</code> is redirecting to <code>site.com/sector/hotels-hospitality-page</code>, giving a 404.</p> <p>I guess the problem is the site is searching for a sector post with a slug of hotels-hospitality-page and not finding one... it's not getting as far as to check the pages.</p>
[ { "answer_id": 262873, "author": "WebElaine", "author_id": 102815, "author_profile": "https://wordpress.stackexchange.com/users/102815", "pm_score": 0, "selected": false, "text": "<p>The first thing I would try for the main issue is to delete the \"sector\" post called \"Hotels &amp; Hospitality.\" Then, go to your permalinks page (Settings > Permalinks) and save the rules as they are, which flushes your rewrite rules. In theory, if there is not a /sector/hotels-hospitality/ \"sector\" post, WordPress should check and find the Page you're looking for. You may want to use a Chrome Incognito window to make sure past redirects aren't making it seem like there's an issue where there actually isn't.</p>\n\n<p>If that doesn't work, try using the CPT instead of a Page. Re-create the \"sector\" post called \"Hotels &amp; Hospitality\". When you create the CPT \"sector\" add \"supports => page-attributes\" so that your CPT can use Page templates. That way, you can apply Page-like styling to the post, but you won't be confusing WordPress with what post type to display.</p>\n\n<p>So change your CPT registration code to:</p>\n\n<pre><code>register_post_type( 'sector',\n array(\n 'labels' =&gt; array(\n 'name' =&gt; __( 'Sectors' ),\n 'singular_name' =&gt; __( 'Sector' )\n ),\n 'public' =&gt; true,\n 'has_archive' =&gt; false,\n 'rewrite' =&gt; array('slug' =&gt; 'sector'),\n 'supports' =&gt; array('title', 'editor', 'thumbnail', 'revisions', 'page-attributes')\n )\n);\n</code></pre>\n\n<p>Adjust title/editor/thumbnail/revisions as needed - it's \"page-attributes\" that enables you to choose a Page Template. Then just copy your Page content into the CPT, delete the Page, and you should be in business.</p>\n" }, { "answer_id": 262877, "author": "Sarah", "author_id": 39063, "author_profile": "https://wordpress.stackexchange.com/users/39063", "pm_score": 1, "selected": false, "text": "<p>I installed Monkeyman Rewrite Analyzer <a href=\"https://wordpress.org/support/plugin/monkeyman-rewrite-analyzer/\" rel=\"nofollow noreferrer\">https://wordpress.org/support/plugin/monkeyman-rewrite-analyzer/</a> which helped a great deal. I saw this referenced on Jan Fabry's detailed answer on <a href=\"https://wordpress.stackexchange.com/questions/5413/need-help-with-add-rewrite-rule\">this post</a> which also helped me.</p>\n\n<p>First thing that I found out with the plugin was that my rewrites weren't actually getting added; they didn't appear in the logic. It turns out the <code>add_rewrite_rule()</code> function is useless unless rewrites have just been flushed. I took out the <code>flush_rewrite_rules();</code> line from my code but I flushed permalinks manually in the admin panel every time I tested a change.</p>\n\n<p>Once I had renamed the custom post and page back to the same URL <code>sectors/hotels-hospitality</code>, I was able to resolve the issue. As @WebElaine explained in the comments, extra redirects are created if any <code>_wp_old_slug</code> fields are saved in the <code>wp_postsmeta</code> table, which helped me solve the related/secondary redirect issue after I edited the post slug.</p>\n\n<p>This is my final function <strong>and it only works after flushing rewrites</strong> (clicking Save in Settings > Permalinks). I also used <code>pagename</code> instead of <code>page_id</code> in the query, but you can use either.</p>\n\n<pre><code>add_action( 'init', 'addMyRules' );\nfunction addMyRules(){\n add_rewrite_rule('sector/hotels-hospitality','index.php?pagename=sector/hotels-hospitality','top');\n}\n</code></pre>\n\n<p>The <code>top</code> parameter is important as it means this pattern to match will be checked before the system post-type check (check the order of rewrites when using the above mentioned plugin, screenshot below).</p>\n\n<p><a href=\"https://i.stack.imgur.com/5DtUg.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/5DtUg.png\" alt=\"enter image description here\"></a></p>\n\n<p>So, when I go to the matching URL, WordPress shows the page and not the post, because this is the first pattern match reached in the list.</p>\n" } ]
2017/04/07
[ "https://wordpress.stackexchange.com/questions/262862", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/39063/" ]
**SOLVED** See my answer below; I cannot immediately accept it. --- **Original post** I made a custom post type of `sector`: ``` register_post_type( 'sector', array( 'labels' => array( 'name' => __( 'Sectors' ), 'singular_name' => __( 'Sector' ) ), 'public' => true, 'has_archive' => false, 'rewrite' => array('slug' => 'sector') ) ); ``` I have a sector called "Hotels & Hospitality" which resides at `site.com/sector/hotels-hospitality/`. I have other sectors that reside at other URLs. I also have a normal Page called "Sector" (which resides at `site.com/sector/`) and a subpage called "Hotels & Hospitality" whose URL is also `site.com/sector/hotels-hospitality/`. At the moment, when I navigate to `site.com/sector/hotels-hospitality/` it's the post-type page that shows. Can I make it so that the normal Page shows instead? This is a special landing page for this sector. I tried this in the functions.php of my theme: ``` flush_rewrite_rules(); add_rewrite_rule( 'sector/hotels-hospitality/', 'index.php?page_id=1700', // 1700 = post_id of the Page 'top' ); ``` No luck so far! I have also tried it without the `'top'` param and this seemed to make no difference. **Related Info** After this I also edited the "Hotels & Hospitality" sector post type slug from `site.com/sector/hotels-hospitality/` to `site.com/sector/hotels` (thinking that that way, at least I would be able to see the other page), but now when I go to `site.com/sector/hotels-hospitality/`, I am redirected to `site.com/sector/hotels/` and I can't undo it! I tried resaving permalinks... I then tried renaming the Page to `site.com/sector/hotels-hospitality-page/` and this is now going to a 404. I am using a fresh install of Version 4.7.3. **Update** @WebElaine helped me delete the redirect from `site.com/sector/hotels-hospitality` to `site.com/sector/hotels` by deleting the \_wp\_old\_slug field in wppostmeta. `site.com/sector/hotels-hospitality-page/` is still going to a 404. Going to `site.com/index.php?page_id=1700` is redirecting to `site.com/sector/hotels-hospitality-page`, giving a 404. I guess the problem is the site is searching for a sector post with a slug of hotels-hospitality-page and not finding one... it's not getting as far as to check the pages.
I installed Monkeyman Rewrite Analyzer <https://wordpress.org/support/plugin/monkeyman-rewrite-analyzer/> which helped a great deal. I saw this referenced on Jan Fabry's detailed answer on [this post](https://wordpress.stackexchange.com/questions/5413/need-help-with-add-rewrite-rule) which also helped me. First thing that I found out with the plugin was that my rewrites weren't actually getting added; they didn't appear in the logic. It turns out the `add_rewrite_rule()` function is useless unless rewrites have just been flushed. I took out the `flush_rewrite_rules();` line from my code but I flushed permalinks manually in the admin panel every time I tested a change. Once I had renamed the custom post and page back to the same URL `sectors/hotels-hospitality`, I was able to resolve the issue. As @WebElaine explained in the comments, extra redirects are created if any `_wp_old_slug` fields are saved in the `wp_postsmeta` table, which helped me solve the related/secondary redirect issue after I edited the post slug. This is my final function **and it only works after flushing rewrites** (clicking Save in Settings > Permalinks). I also used `pagename` instead of `page_id` in the query, but you can use either. ``` add_action( 'init', 'addMyRules' ); function addMyRules(){ add_rewrite_rule('sector/hotels-hospitality','index.php?pagename=sector/hotels-hospitality','top'); } ``` The `top` parameter is important as it means this pattern to match will be checked before the system post-type check (check the order of rewrites when using the above mentioned plugin, screenshot below). [![enter image description here](https://i.stack.imgur.com/5DtUg.png)](https://i.stack.imgur.com/5DtUg.png) So, when I go to the matching URL, WordPress shows the page and not the post, because this is the first pattern match reached in the list.
262,890
<p>For the plugin i wrote, AJAX request on the frontend <strong>works properly if i am admin</strong>, but the same thing doesn't work when i try it as <strong>normal user</strong>, it always returns 0.</p> <p>This is plugin's core php file where i am doing all the enqueue and localize stuff:</p> <pre><code>require_once ( plugin_dir_path(__FILE__) . 'like-user-request.php' ); function lr_enqueue_ui_scripts() { wp_enqueue_script( 'core-likeranker-js', plugins_url( 'js/like.js', __FILE__ ), array( 'jquery', 'jquery-ui-datepicker' ), false, true ); wp_enqueue_style( 'jquery-style', 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.2/themes/smoothness/jquery-ui.css' ); wp_localize_script( 'core-likeranker-js', 'my_ajax_object', array( 'ajax_url' =&gt; admin_url('admin-ajax.php'), 'security' =&gt; wp_create_nonce('user-like') ) ); } add_action( 'wp_enqueue_scripts', 'lr_enqueue_ui_scripts'); </code></pre> <p>This is javascript file</p> <pre><code>jQuery(document).ready(function($){ var state = $('#post-like-count').data('user-state'); $('.like-button').on('click', function(){ var count = $('#post-like-count').data('id'); var postId = $('#post-like-count').data('post-id'); state == 1 ? count++ : count--; $.ajax({ url: my_ajax_object.ajax_url, type: 'POST', dataType: 'json', data: { action: 'save_like', likeCount: count, id: postId, userState: state, security: my_ajax_object.security }, success: function(response) { if(response.success === true){ $('#post-like-count').html(count + ' Likes'); $('#post-like-count').data('id', count); if(state == 1){ state = 2; $('.like-button').html('Dislike'); } else { state = 1; $('.like-button').html('Like !'); } $('#post-like-count').data('user-state', state); } }, error:function(error) { $('.like-box').after('Error'); } }); }) }); </code></pre> <p>Php file that i handle the AJAX request</p> <pre><code>&lt;?php function lr_save_like_request() { if ( ! check_ajax_referer( 'user-like', 'security' ) ) { wp_send_json_error( 'Invalid Nonce !' ); } $count = $_POST['likeCount']; $postId = $_POST['id']; $ip; if ( ! empty( $_SERVER['HTTP_CLIENT_IP'] ) ) { //check ip from share internet $ip = $_SERVER['HTTP_CLIENT_IP']; } elseif ( ! empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) { //to check ip is pass from proxy $ip = $_SERVER['HTTP_X_FORWARDED_FOR']; } else { $ip = $_SERVER['REMOTE_ADDR']; } $voters_ip = get_post_meta( $postId, '_voters_ip', false ); $flag = empty( $voters_ip ) ? 1 : 0; if( $_POST['userState'] == 1 ) { if( $flag == 1 ) { $voters_ip_buffer = $voters_ip; $voters_ip_buffer[] = $ip; } else { $voters_ip_buffer = $voters_ip[0]; $voters_ip_buffer[] = $ip; } } else { $voters_ip_buffer = $voters_ip[0]; for ( $i=0; $i &lt; count($voters_ip_buffer); $i++ ) { if( $ip == $voters_ip_buffer[$i] ) { unset( $voters_ip_buffer ); } } } if( ! update_post_meta( $postId, '_Like', $count ) ) { add_post_meta ( $postId, '_Like', $count, true ); } if( ! update_post_meta( $postId, '_voters_ip', $voters_ip_buffer ) ) { add_post_meta ( $postId, '_voters_ip', $voters_ip_buffer, true ); } wp_send_json_success( array( 'state' =&gt; $_POST['userState'] )); wp_die(); } add_action( 'wp_ajax_save_like', 'lr_save_like_request' ); </code></pre>
[ { "answer_id": 264653, "author": "Aishan", "author_id": 89530, "author_profile": "https://wordpress.stackexchange.com/users/89530", "pm_score": 1, "selected": false, "text": "<p>Everything has to match here: </p>\n\n<p>JS:<br>\ndata: {<br>\n action: 'save_like',<br>\n likeCount: count,<br>\n id: postId,<br>\n userState: state,<br>\n security: my_ajax_object.security<br>\n }, </p>\n\n<p>ACTION HOOKS:<br>\nadd_action('wp_ajax_save_like', 'save_like');<br>\nadd_action('wp_ajax_nopriv_save_like', 'save_like'); </p>\n\n<p>FUNCTION TO PROCESS AJAX REQUEST<br>\nfunction save_like() {} </p>\n\n<p><a href=\"http://www.makeuseof.com/tag/tutorial-ajax-wordpress/\" rel=\"nofollow noreferrer\">http://www.makeuseof.com/tag/tutorial-ajax-wordpress/</a></p>\n" }, { "answer_id": 295957, "author": "Larzan", "author_id": 34517, "author_profile": "https://wordpress.stackexchange.com/users/34517", "pm_score": 2, "selected": false, "text": "<p>As mmm didn't post an answer but just wrote a comment, here is the answer:</p>\n\n<p>As the documentation for <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/wp_ajax_(action)\" rel=\"nofollow noreferrer\">wp_ajax </a> states in its notes, the hook only fires for <strong>logged in users</strong>.\nIf you want to use an ajax call on the frontend for users that are <strong>not logged in</strong>, you have to use the <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/wp_ajax_nopriv_(action)\" rel=\"nofollow noreferrer\">wp_ajax_nopriv</a> hook.</p>\n\n<p>So instead of </p>\n\n<pre><code>add_action( 'wp_ajax_save_like', 'lr_save_like_request' );\n</code></pre>\n\n<p>you have to write</p>\n\n<pre><code>add_action( 'wp_ajax_nopriv_save_like', 'lr_save_like_request' );\n</code></pre>\n\n<p>Thats all, the functionality of the two hooks is exactly the same, the only difference is that one fires only for logged in users and the other one for everybody.</p>\n" } ]
2017/04/08
[ "https://wordpress.stackexchange.com/questions/262890", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/116595/" ]
For the plugin i wrote, AJAX request on the frontend **works properly if i am admin**, but the same thing doesn't work when i try it as **normal user**, it always returns 0. This is plugin's core php file where i am doing all the enqueue and localize stuff: ``` require_once ( plugin_dir_path(__FILE__) . 'like-user-request.php' ); function lr_enqueue_ui_scripts() { wp_enqueue_script( 'core-likeranker-js', plugins_url( 'js/like.js', __FILE__ ), array( 'jquery', 'jquery-ui-datepicker' ), false, true ); wp_enqueue_style( 'jquery-style', 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.2/themes/smoothness/jquery-ui.css' ); wp_localize_script( 'core-likeranker-js', 'my_ajax_object', array( 'ajax_url' => admin_url('admin-ajax.php'), 'security' => wp_create_nonce('user-like') ) ); } add_action( 'wp_enqueue_scripts', 'lr_enqueue_ui_scripts'); ``` This is javascript file ``` jQuery(document).ready(function($){ var state = $('#post-like-count').data('user-state'); $('.like-button').on('click', function(){ var count = $('#post-like-count').data('id'); var postId = $('#post-like-count').data('post-id'); state == 1 ? count++ : count--; $.ajax({ url: my_ajax_object.ajax_url, type: 'POST', dataType: 'json', data: { action: 'save_like', likeCount: count, id: postId, userState: state, security: my_ajax_object.security }, success: function(response) { if(response.success === true){ $('#post-like-count').html(count + ' Likes'); $('#post-like-count').data('id', count); if(state == 1){ state = 2; $('.like-button').html('Dislike'); } else { state = 1; $('.like-button').html('Like !'); } $('#post-like-count').data('user-state', state); } }, error:function(error) { $('.like-box').after('Error'); } }); }) }); ``` Php file that i handle the AJAX request ``` <?php function lr_save_like_request() { if ( ! check_ajax_referer( 'user-like', 'security' ) ) { wp_send_json_error( 'Invalid Nonce !' ); } $count = $_POST['likeCount']; $postId = $_POST['id']; $ip; if ( ! empty( $_SERVER['HTTP_CLIENT_IP'] ) ) { //check ip from share internet $ip = $_SERVER['HTTP_CLIENT_IP']; } elseif ( ! empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) { //to check ip is pass from proxy $ip = $_SERVER['HTTP_X_FORWARDED_FOR']; } else { $ip = $_SERVER['REMOTE_ADDR']; } $voters_ip = get_post_meta( $postId, '_voters_ip', false ); $flag = empty( $voters_ip ) ? 1 : 0; if( $_POST['userState'] == 1 ) { if( $flag == 1 ) { $voters_ip_buffer = $voters_ip; $voters_ip_buffer[] = $ip; } else { $voters_ip_buffer = $voters_ip[0]; $voters_ip_buffer[] = $ip; } } else { $voters_ip_buffer = $voters_ip[0]; for ( $i=0; $i < count($voters_ip_buffer); $i++ ) { if( $ip == $voters_ip_buffer[$i] ) { unset( $voters_ip_buffer ); } } } if( ! update_post_meta( $postId, '_Like', $count ) ) { add_post_meta ( $postId, '_Like', $count, true ); } if( ! update_post_meta( $postId, '_voters_ip', $voters_ip_buffer ) ) { add_post_meta ( $postId, '_voters_ip', $voters_ip_buffer, true ); } wp_send_json_success( array( 'state' => $_POST['userState'] )); wp_die(); } add_action( 'wp_ajax_save_like', 'lr_save_like_request' ); ```
As mmm didn't post an answer but just wrote a comment, here is the answer: As the documentation for [wp\_ajax](https://codex.wordpress.org/Plugin_API/Action_Reference/wp_ajax_(action)) states in its notes, the hook only fires for **logged in users**. If you want to use an ajax call on the frontend for users that are **not logged in**, you have to use the [wp\_ajax\_nopriv](https://codex.wordpress.org/Plugin_API/Action_Reference/wp_ajax_nopriv_(action)) hook. So instead of ``` add_action( 'wp_ajax_save_like', 'lr_save_like_request' ); ``` you have to write ``` add_action( 'wp_ajax_nopriv_save_like', 'lr_save_like_request' ); ``` Thats all, the functionality of the two hooks is exactly the same, the only difference is that one fires only for logged in users and the other one for everybody.
262,960
<p><strong>It works, the tags are displayed in the loop, But when entering one of the tags appears the error 404</strong> I have also created a template tag-pizza.php</p> <p>Here code of the tags</p> <pre><code>add_action( 'init', 'create_tag_taxonomies', 0 ); function create_tag_taxonomies() { // Add new taxonomy, NOT hierarchical (like tags) $labels = array( 'name' =&gt; _x( 'Tags', 'taxonomy general name' ), 'singular_name' =&gt; _x( 'Tag', 'taxonomy singular name' ), 'search_items' =&gt; __( 'Search Tags' ), 'popular_items' =&gt; __( 'Popular Tags' ), 'all_items' =&gt; __( 'All Tags' ), 'parent_item' =&gt; null, 'parent_item_colon' =&gt; null, 'edit_item' =&gt; __( 'Edit Tag' ), 'update_item' =&gt; __( 'Update Tag' ), 'add_new_item' =&gt; __( 'Add New Tag' ), 'new_item_name' =&gt; __( 'New Tag Name' ), 'separate_items_with_commas' =&gt; __( 'Separate tags with commas' ), 'add_or_remove_items' =&gt; __( 'Add or remove tags' ), 'choose_from_most_used' =&gt; __( 'Choose from the most used tags' ), 'menu_name' =&gt; __( 'Tags' ), ); register_taxonomy('tag','pizza',array( 'hierarchical' =&gt; false, 'labels' =&gt; $labels, 'show_ui' =&gt; true, 'update_count_callback' =&gt; '_update_post_term_count', 'query_var' =&gt; true, 'rewrite' =&gt; array( 'slug' =&gt; 'tag' ), 'with_front' =&gt; true )); } </code></pre> <p>here code of taxonomy principal</p> <pre><code>function my_taxonomies_productpizza() { $labels = array( 'name' =&gt; _x( 'Generos', 'taxonomy general name' ), 'singular_name' =&gt; _x( 'Generos', 'taxonomy singular name' ), 'search_items' =&gt; __( 'Search Product Categories' ), 'all_items' =&gt; __( 'All Product Categories' ), 'parent_item' =&gt; __( 'Parent Product Category' ), 'parent_item_colon' =&gt; __( 'Parent Product Category:' ), 'edit_item' =&gt; __( 'Edit Product Category' ), 'update_item' =&gt; __( 'Update Product Category' ), 'add_new_item' =&gt; __( 'Add New Product Category' ), 'new_item_name' =&gt; __( 'New Product Category' ), 'menu_name' =&gt; __( 'Generos' ), ); $args = array( 'labels' =&gt; $labels, 'hierarchical' =&gt; true, 'public' =&gt; true, 'query_var' =&gt; 'generos', //slug prodotto deve coincidere con il primo parametro dello slug del Custom Post Type correlato 'rewrite' =&gt; array('slug' =&gt; 'pizza' ), '_builtin' =&gt; false, ); register_taxonomy( 'generos', 'pizza', $args ); } add_action( 'init', 'my_taxonomies_productpizza', 0 ); </code></pre>
[ { "answer_id": 262943, "author": "Abhishek Pandey", "author_id": 114826, "author_profile": "https://wordpress.stackexchange.com/users/114826", "pm_score": -1, "selected": false, "text": "<p>Put this CODE in your theme's <code>functions.php</code> file:</p>\n\n<pre><code>function admin_default_page() {\n return '/new-url';\n}\n\nadd_filter('login_redirect', 'admin_default_page');\n</code></pre>\n" }, { "answer_id": 263035, "author": "Tamilvanan", "author_id": 109197, "author_profile": "https://wordpress.stackexchange.com/users/109197", "pm_score": 0, "selected": false, "text": "<p>You can use the <code>is_user_logged_in()</code> and <code>is_page (array(1,2,3-page id's))</code> functions to check. After that you can write the redirection. </p>\n" }, { "answer_id": 263081, "author": "Harry", "author_id": 100916, "author_profile": "https://wordpress.stackexchange.com/users/100916", "pm_score": 0, "selected": false, "text": "<p>Well i have not tested it but you can achieve your point in this way...</p>\n\n<pre><code> if(!is_user_logged_in() &amp;&amp; is_page(1,2,your-page-ids)){\n\n // wp_redirect(LOGIN_PAGE_URL.'?redirect_to='.get_the_permalink(););\n\n }\n</code></pre>\n\n<p>redirect user to login page with a query variable containing link of post or page.</p>\n\n<p>put this code in your child theme's function.php</p>\n\n<p>Hope it will help you...</p>\n" } ]
2017/04/08
[ "https://wordpress.stackexchange.com/questions/262960", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/115933/" ]
**It works, the tags are displayed in the loop, But when entering one of the tags appears the error 404** I have also created a template tag-pizza.php Here code of the tags ``` add_action( 'init', 'create_tag_taxonomies', 0 ); function create_tag_taxonomies() { // Add new taxonomy, NOT hierarchical (like tags) $labels = array( 'name' => _x( 'Tags', 'taxonomy general name' ), 'singular_name' => _x( 'Tag', 'taxonomy singular name' ), 'search_items' => __( 'Search Tags' ), 'popular_items' => __( 'Popular Tags' ), 'all_items' => __( 'All Tags' ), 'parent_item' => null, 'parent_item_colon' => null, 'edit_item' => __( 'Edit Tag' ), 'update_item' => __( 'Update Tag' ), 'add_new_item' => __( 'Add New Tag' ), 'new_item_name' => __( 'New Tag Name' ), 'separate_items_with_commas' => __( 'Separate tags with commas' ), 'add_or_remove_items' => __( 'Add or remove tags' ), 'choose_from_most_used' => __( 'Choose from the most used tags' ), 'menu_name' => __( 'Tags' ), ); register_taxonomy('tag','pizza',array( 'hierarchical' => false, 'labels' => $labels, 'show_ui' => true, 'update_count_callback' => '_update_post_term_count', 'query_var' => true, 'rewrite' => array( 'slug' => 'tag' ), 'with_front' => true )); } ``` here code of taxonomy principal ``` function my_taxonomies_productpizza() { $labels = array( 'name' => _x( 'Generos', 'taxonomy general name' ), 'singular_name' => _x( 'Generos', 'taxonomy singular name' ), 'search_items' => __( 'Search Product Categories' ), 'all_items' => __( 'All Product Categories' ), 'parent_item' => __( 'Parent Product Category' ), 'parent_item_colon' => __( 'Parent Product Category:' ), 'edit_item' => __( 'Edit Product Category' ), 'update_item' => __( 'Update Product Category' ), 'add_new_item' => __( 'Add New Product Category' ), 'new_item_name' => __( 'New Product Category' ), 'menu_name' => __( 'Generos' ), ); $args = array( 'labels' => $labels, 'hierarchical' => true, 'public' => true, 'query_var' => 'generos', //slug prodotto deve coincidere con il primo parametro dello slug del Custom Post Type correlato 'rewrite' => array('slug' => 'pizza' ), '_builtin' => false, ); register_taxonomy( 'generos', 'pizza', $args ); } add_action( 'init', 'my_taxonomies_productpizza', 0 ); ```
You can use the `is_user_logged_in()` and `is_page (array(1,2,3-page id's))` functions to check. After that you can write the redirection.
262,977
<p>i want to add my css file bootstrap.min.css on top of all css file. I used below code </p> <pre><code>wp_enqueue_style( 'bootstrap_css', 'bootstrap.min.css' ); </code></pre> <p>but it add css below theme css file .</p> <p>Issue is that i do not want to modify theme file and want to do from plugin only. I there way i can add my css after <strong></strong> tag using some <strong>wp_head</strong> or <strong>after_title</strong> hook.</p> <p>Please help me with same</p>
[ { "answer_id": 262943, "author": "Abhishek Pandey", "author_id": 114826, "author_profile": "https://wordpress.stackexchange.com/users/114826", "pm_score": -1, "selected": false, "text": "<p>Put this CODE in your theme's <code>functions.php</code> file:</p>\n\n<pre><code>function admin_default_page() {\n return '/new-url';\n}\n\nadd_filter('login_redirect', 'admin_default_page');\n</code></pre>\n" }, { "answer_id": 263035, "author": "Tamilvanan", "author_id": 109197, "author_profile": "https://wordpress.stackexchange.com/users/109197", "pm_score": 0, "selected": false, "text": "<p>You can use the <code>is_user_logged_in()</code> and <code>is_page (array(1,2,3-page id's))</code> functions to check. After that you can write the redirection. </p>\n" }, { "answer_id": 263081, "author": "Harry", "author_id": 100916, "author_profile": "https://wordpress.stackexchange.com/users/100916", "pm_score": 0, "selected": false, "text": "<p>Well i have not tested it but you can achieve your point in this way...</p>\n\n<pre><code> if(!is_user_logged_in() &amp;&amp; is_page(1,2,your-page-ids)){\n\n // wp_redirect(LOGIN_PAGE_URL.'?redirect_to='.get_the_permalink(););\n\n }\n</code></pre>\n\n<p>redirect user to login page with a query variable containing link of post or page.</p>\n\n<p>put this code in your child theme's function.php</p>\n\n<p>Hope it will help you...</p>\n" } ]
2017/04/09
[ "https://wordpress.stackexchange.com/questions/262977", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/70832/" ]
i want to add my css file bootstrap.min.css on top of all css file. I used below code ``` wp_enqueue_style( 'bootstrap_css', 'bootstrap.min.css' ); ``` but it add css below theme css file . Issue is that i do not want to modify theme file and want to do from plugin only. I there way i can add my css after tag using some **wp\_head** or **after\_title** hook. Please help me with same
You can use the `is_user_logged_in()` and `is_page (array(1,2,3-page id's))` functions to check. After that you can write the redirection.
263,008
<p>I have my wordpress server set up using php, mysql, and apache on my raspberry pi. I also have a dynamic dns hostname and configured my router's port forwardiing settings. </p> <p>When trying to access my server from outside of my local LAN, when I type in my dynamic dns host, (for example, my phone on 4G mobile network or at school), the site incorrectly redirects to the server's local IP address: 192.168.0.18 so the page fails to load up.</p> <p>This is very weird because I also have owncloud set up on my pi and in the same condition I try to access mydynamicdnshost/owncloud, it doesn't redirect me to local IP and the page loads up successfully. </p> <p>I know this is a really basic problem with wordpress configuration but I simply cannot fix it. So does anyone know that please answer my question. Many thanks!</p>
[ { "answer_id": 263058, "author": "JItendra Rana", "author_id": 87433, "author_profile": "https://wordpress.stackexchange.com/users/87433", "pm_score": 2, "selected": true, "text": "<p>Change the Site URL in Options Table.</p>\n<pre><code>UPDATE `wp_options` SET `option_value` = 'YOUR_SITE_URL' WHERE `option_name` = 'siteurl' OR `option_name` = 'home';\n</code></pre>\n<p>Also change the static URLs in your post content.</p>\n<pre><code>UPDATE `wp_posts` SET `post_content` = REPLACE(post_content, '192.168.0.18/YOUR_LOCAL_SITE_URL/', 'YOUR_SITE_URL/');\n</code></pre>\n<p>Don't forget to change the table prefix if its not 'wp_'.</p>\n<hr />\n<p><strong>Edit :</strong> Access PHPMyAdmin of your server. Contact your Hosting Provider if you are not aware of this.</p>\n<p>Select your WordPress Database &amp; Access wp_options table. And change 'siteurl' &amp;&amp; 'home' attribute values to your Live Website URL.</p>\n<p>Hire a developer if you are not sure what you are doing !</p>\n<p><a href=\"https://i.stack.imgur.com/iMebr.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/iMebr.png\" alt=\"enter image description here\" /></a></p>\n" }, { "answer_id": 377625, "author": "Chaki_Black", "author_id": 197026, "author_profile": "https://wordpress.stackexchange.com/users/197026", "pm_score": 0, "selected": false, "text": "<p>Inspired @jitendra-rana answer, the direction was correct, but not full.<br/></p>\n<ol>\n<li>Do dump of your database to the file.</li>\n<li>Open dump file and replace all <code>http://192.168.0.18</code> to <code>http://your_site</code><br/></li>\n<li>Execute dump file to replace all data in database.<br/></li>\n<li>Clear cache (hard reload) of your site.<br/></li>\n</ol>\n<p>Profit.</p>\n" } ]
2017/04/09
[ "https://wordpress.stackexchange.com/questions/263008", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/117216/" ]
I have my wordpress server set up using php, mysql, and apache on my raspberry pi. I also have a dynamic dns hostname and configured my router's port forwardiing settings. When trying to access my server from outside of my local LAN, when I type in my dynamic dns host, (for example, my phone on 4G mobile network or at school), the site incorrectly redirects to the server's local IP address: 192.168.0.18 so the page fails to load up. This is very weird because I also have owncloud set up on my pi and in the same condition I try to access mydynamicdnshost/owncloud, it doesn't redirect me to local IP and the page loads up successfully. I know this is a really basic problem with wordpress configuration but I simply cannot fix it. So does anyone know that please answer my question. Many thanks!
Change the Site URL in Options Table. ``` UPDATE `wp_options` SET `option_value` = 'YOUR_SITE_URL' WHERE `option_name` = 'siteurl' OR `option_name` = 'home'; ``` Also change the static URLs in your post content. ``` UPDATE `wp_posts` SET `post_content` = REPLACE(post_content, '192.168.0.18/YOUR_LOCAL_SITE_URL/', 'YOUR_SITE_URL/'); ``` Don't forget to change the table prefix if its not 'wp\_'. --- **Edit :** Access PHPMyAdmin of your server. Contact your Hosting Provider if you are not aware of this. Select your WordPress Database & Access wp\_options table. And change 'siteurl' && 'home' attribute values to your Live Website URL. Hire a developer if you are not sure what you are doing ! [![enter image description here](https://i.stack.imgur.com/iMebr.png)](https://i.stack.imgur.com/iMebr.png)
263,029
<p>I'd like to add some custom HTML and jQuery to a page built with the page.php template. I know how to do the HTML and jQuery I want in functions.php but I'm not sure how to get a hook into page.php where I want it so I can get into functions.php. Currently the page I want to modify has been built with Visual Composer, but I don't see a way with Visual Composer to insert a hook. </p> <p>Thanks for any suggestions.</p>
[ { "answer_id": 263058, "author": "JItendra Rana", "author_id": 87433, "author_profile": "https://wordpress.stackexchange.com/users/87433", "pm_score": 2, "selected": true, "text": "<p>Change the Site URL in Options Table.</p>\n<pre><code>UPDATE `wp_options` SET `option_value` = 'YOUR_SITE_URL' WHERE `option_name` = 'siteurl' OR `option_name` = 'home';\n</code></pre>\n<p>Also change the static URLs in your post content.</p>\n<pre><code>UPDATE `wp_posts` SET `post_content` = REPLACE(post_content, '192.168.0.18/YOUR_LOCAL_SITE_URL/', 'YOUR_SITE_URL/');\n</code></pre>\n<p>Don't forget to change the table prefix if its not 'wp_'.</p>\n<hr />\n<p><strong>Edit :</strong> Access PHPMyAdmin of your server. Contact your Hosting Provider if you are not aware of this.</p>\n<p>Select your WordPress Database &amp; Access wp_options table. And change 'siteurl' &amp;&amp; 'home' attribute values to your Live Website URL.</p>\n<p>Hire a developer if you are not sure what you are doing !</p>\n<p><a href=\"https://i.stack.imgur.com/iMebr.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/iMebr.png\" alt=\"enter image description here\" /></a></p>\n" }, { "answer_id": 377625, "author": "Chaki_Black", "author_id": 197026, "author_profile": "https://wordpress.stackexchange.com/users/197026", "pm_score": 0, "selected": false, "text": "<p>Inspired @jitendra-rana answer, the direction was correct, but not full.<br/></p>\n<ol>\n<li>Do dump of your database to the file.</li>\n<li>Open dump file and replace all <code>http://192.168.0.18</code> to <code>http://your_site</code><br/></li>\n<li>Execute dump file to replace all data in database.<br/></li>\n<li>Clear cache (hard reload) of your site.<br/></li>\n</ol>\n<p>Profit.</p>\n" } ]
2017/04/09
[ "https://wordpress.stackexchange.com/questions/263029", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/87684/" ]
I'd like to add some custom HTML and jQuery to a page built with the page.php template. I know how to do the HTML and jQuery I want in functions.php but I'm not sure how to get a hook into page.php where I want it so I can get into functions.php. Currently the page I want to modify has been built with Visual Composer, but I don't see a way with Visual Composer to insert a hook. Thanks for any suggestions.
Change the Site URL in Options Table. ``` UPDATE `wp_options` SET `option_value` = 'YOUR_SITE_URL' WHERE `option_name` = 'siteurl' OR `option_name` = 'home'; ``` Also change the static URLs in your post content. ``` UPDATE `wp_posts` SET `post_content` = REPLACE(post_content, '192.168.0.18/YOUR_LOCAL_SITE_URL/', 'YOUR_SITE_URL/'); ``` Don't forget to change the table prefix if its not 'wp\_'. --- **Edit :** Access PHPMyAdmin of your server. Contact your Hosting Provider if you are not aware of this. Select your WordPress Database & Access wp\_options table. And change 'siteurl' && 'home' attribute values to your Live Website URL. Hire a developer if you are not sure what you are doing ! [![enter image description here](https://i.stack.imgur.com/iMebr.png)](https://i.stack.imgur.com/iMebr.png)
263,067
<p>I'm trying to list posts in a custom post type, within a layout like following.</p> <p><a href="https://i.stack.imgur.com/nIxPB.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/nIxPB.jpg" alt="Layout"></a> </p> <p>html for below layout like this.</p> <pre><code>&lt;div class="col-md-4 col-sm-6"&gt; PROFILE - 1 &lt;/div&gt; &lt;div class="col-md-4 col-sm-6"&gt; &lt;/div&gt; &lt;div class="col-md-4 col-sm-6"&gt; PROFILE - 2 &lt;/div&gt; &lt;div class="col-md-4 col-sm-6"&gt; PROFILE - 3 &lt;/div&gt; &lt;div class="col-md-4 col-sm-6"&gt; &lt;/div&gt; &lt;div class="col-md-4 col-sm-6"&gt; PROFILE - 4 &lt;/div&gt; </code></pre> <p>as you can see after "PROFILE - 1" there is a div separator then there is "PROFILE - 1 &amp; PROFILE - 2" after "PROFILE - 1 &amp; PROFILE - 2" again div separator.</p> <p>basically the structure as follows.</p> <p>Profile-1 </p> <p>V V</p> <p>Empty space (div based col-md-4 col-sm-6 ) </p> <p>V V </p> <p>Profile-2 </p> <p>V V</p> <p>Profile-3</p> <p>V V</p> <p>Empty space (div based col-md-4 col-sm-6 ) </p> <p>V V</p> <p>Profile-4 </p> <p>i'm using this loop as a custom structure but i'm unable to get it from Profile-2 > Profile-3 > Space point.</p> <p>looking for a help to achieve this loop.</p> <p>THIS IS WHAT I HAVE TRIED</p> <pre><code>&lt;?php $args=array( 'post_type' =&gt; 'ourteam', 'posts_per_page' =&gt; -1 ); //Set up a counter $counter = 0; //Preparing the Loop $query = new WP_Query( $args ); //In while loop counter increments by one $counter++ if( $query-&gt;have_posts() ) : while( $query-&gt;have_posts() ) : $query- &gt;the_post(); $counter++; //We are in loop so we can check if counter is odd or even if( $counter % 2 == 0 ) : //It's even ?&gt; &lt;div class="col-md-4 col-sm-6"&gt; &lt;/div&gt; &lt;div class="col-md-4 col-sm-6"&gt; &lt;div class="cp-attorneys-style-2"&gt; &lt;div class="frame"&gt; &lt;a href="&lt;?php the_permalink(); ?&gt;"&gt;&lt;?php the_post_thumbnail(''); ?&gt;&lt;/a&gt; &lt;div class="caption"&gt; &lt;div class="holder"&gt; &lt;ul&gt; &lt;li&gt;&lt;a href="&lt;?php the_field('mem_twitter'); ?&gt;"&gt;&lt;i class="fa fa-twitter"&gt;&lt;/i&gt;&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="&lt;?php the_field('mem_facebook'); ?&gt;"&gt;&lt;i class="fa fa-facebook"&gt;&lt;/i&gt;&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="&lt;?php the_field('mem_linkedin'); ?&gt;"&gt;&lt;i class="fa fa-linkedin"&gt;&lt;/i&gt;&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;p&gt; &lt;/p&gt; &lt;a href="&lt;?php the_permalink(); ?&gt;" class="btn-style-1"&gt;Read Profile&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="cp-text-box"&gt; &lt;h3&gt;&lt;a href="&lt;?php the_permalink(); ?&gt;"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;&lt;/h3&gt; &lt;em&gt;&lt;?php the_field('mem_titles'); ?&gt;&lt;/em&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="col-md-4 col-sm-6"&gt; &lt;/div&gt; &lt;?php else: //It's odd ?&gt; &lt;div class="col-md-4 col-sm-6"&gt; &lt;div class="cp-attorneys-style-2"&gt; &lt;div class="frame"&gt; &lt;a href="&lt;?php the_permalink(); ?&gt;"&gt;&lt;?php the_post_thumbnail(''); ?&gt;&lt;/a&gt; &lt;div class="caption"&gt; &lt;div class="holder"&gt; &lt;ul&gt; &lt;li&gt;&lt;a href="&lt;?php the_field('mem_twitter'); ?&gt;"&gt;&lt;i class="fa fa-twitter"&gt;&lt;/i&gt;&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="&lt;?php the_field('mem_facebook'); ?&gt;"&gt;&lt;i class="fa fa-facebook"&gt;&lt;/i&gt;&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="&lt;?php the_field('mem_linkedin'); ?&gt;"&gt;&lt;i class="fa fa-linkedin"&gt;&lt;/i&gt;&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;p&gt; &lt;/p&gt; &lt;a href="&lt;?php the_permalink(); ?&gt;" class="btn-style-1"&gt;Read Profile&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="cp-text-box"&gt; &lt;h3&gt;&lt;a href="&lt;?php the_permalink(); ?&gt;"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;&lt;/h3&gt; &lt;em&gt;&lt;?php the_field('mem_titles'); ?&gt;&lt;/em&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;?php endif; endwhile; wp_reset_postdata(); endif; ?&gt; </code></pre>
[ { "answer_id": 263076, "author": "Rishabh", "author_id": 81621, "author_profile": "https://wordpress.stackexchange.com/users/81621", "pm_score": 2, "selected": true, "text": "<p>You can set your custom loop something like this</p>\n\n<pre><code>$a=2;\n//In while loop counter increments by one $counter++\nif( $query-&gt;have_posts() ) : while( $query-&gt;have_posts() ) : $query-&gt;the_post();\n if($a%3!=0){ //Here write function to display title and discription\n ?&gt; \n &lt;div class=\"col-md-4 col-sm-6\"&gt;\n\n &lt;div class=\"cp-attorneys-style-2\"&gt;\n\n &lt;div class=\"frame\"&gt; &lt;a href=\"&lt;?php the_permalink(); ?&gt;\"&gt;&lt;?php the_post_thumbnail(''); ?&gt;&lt;/a&gt;\n\n &lt;div class=\"caption\"&gt;\n\n &lt;div class=\"holder\"&gt;\n\n &lt;ul&gt;\n\n &lt;li&gt;&lt;a href=\"&lt;?php the_field('mem_twitter'); ?&gt;\"&gt;&lt;i class=\"fa fa-twitter\"&gt;&lt;/i&gt;&lt;/a&gt;&lt;/li&gt;\n\n &lt;li&gt;&lt;a href=\"&lt;?php the_field('mem_facebook'); ?&gt;\"&gt;&lt;i class=\"fa fa-facebook\"&gt;&lt;/i&gt;&lt;/a&gt;&lt;/li&gt;\n\n &lt;li&gt;&lt;a href=\"&lt;?php the_field('mem_linkedin'); ?&gt;\"&gt;&lt;i class=\"fa fa-linkedin\"&gt;&lt;/i&gt;&lt;/a&gt;&lt;/li&gt;\n\n &lt;/ul&gt;\n\n &lt;p&gt; &lt;/p&gt;\n\n &lt;a href=\"&lt;?php the_permalink(); ?&gt;\" class=\"btn-style-1\"&gt;Read Profile&lt;/a&gt; &lt;/div&gt;\n\n &lt;/div&gt;\n\n &lt;/div&gt;\n\n &lt;div class=\"cp-text-box\"&gt;\n\n &lt;h3&gt;&lt;a href=\"&lt;?php the_permalink(); ?&gt;\"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;&lt;/h3&gt;\n\n &lt;em&gt;&lt;?php the_field('mem_titles'); ?&gt;&lt;/em&gt; &lt;/div&gt;\n\n &lt;/div&gt;\n\n &lt;/div&gt; \n &lt;?php \n $a = $a+1;\n } else {\n ?&gt;\n &lt;div class=\"col-md-4 col-sm-6\"&gt; \n &lt;?php //Leave this div empty \n ?&gt;\n &lt;/div&gt;\n &lt;div class=\"col-md-4 col-sm-6\"&gt;\n\n &lt;div class=\"cp-attorneys-style-2\"&gt;\n\n &lt;div class=\"frame\"&gt; &lt;a href=\"&lt;?php the_permalink(); ?&gt;\"&gt;&lt;?php the_post_thumbnail(''); ?&gt;&lt;/a&gt;\n\n &lt;div class=\"caption\"&gt;\n\n &lt;div class=\"holder\"&gt;\n\n &lt;ul&gt;\n\n &lt;li&gt;&lt;a href=\"&lt;?php the_field('mem_twitter'); ?&gt;\"&gt;&lt;i class=\"fa fa-twitter\"&gt;&lt;/i&gt;&lt;/a&gt;&lt;/li&gt;\n\n &lt;li&gt;&lt;a href=\"&lt;?php the_field('mem_facebook'); ?&gt;\"&gt;&lt;i class=\"fa fa-facebook\"&gt;&lt;/i&gt;&lt;/a&gt;&lt;/li&gt;\n\n &lt;li&gt;&lt;a href=\"&lt;?php the_field('mem_linkedin'); ?&gt;\"&gt;&lt;i class=\"fa fa-linkedin\"&gt;&lt;/i&gt;&lt;/a&gt;&lt;/li&gt;\n\n &lt;/ul&gt;\n\n &lt;p&gt; &lt;/p&gt;\n\n &lt;a href=\"&lt;?php the_permalink(); ?&gt;\" class=\"btn-style-1\"&gt;Read Profile&lt;/a&gt; &lt;/div&gt;\n\n &lt;/div&gt;\n\n &lt;/div&gt;\n\n &lt;div class=\"cp-text-box\"&gt;\n\n &lt;h3&gt;&lt;a href=\"&lt;?php the_permalink(); ?&gt;\"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;&lt;/h3&gt;\n\n &lt;em&gt;&lt;?php the_field('mem_titles'); ?&gt;&lt;/em&gt; &lt;/div&gt;\n\n &lt;/div&gt;\n\n &lt;/div&gt; \n &lt;?php\n $a = $a+2;\n }\n\nendwhile; wp_reset_postdata(); endif;\n</code></pre>\n\n<p>Take backup of your code first.</p>\n" }, { "answer_id": 263084, "author": "Marius Akerbæk", "author_id": 117303, "author_profile": "https://wordpress.stackexchange.com/users/117303", "pm_score": 0, "selected": false, "text": "<p>Do you need the empty div for anything other than spacing? By the class names, it looks like you are using bootstrap, and in bootstrap you have the offset-classes to ensure correct spacing on the different breakpoints.</p>\n\n<p>If you want two profiles on each row you can do</p>\n\n<pre><code>&lt;div class=\"col-md-offset-2 col-md-4\"&gt;\n</code></pre>\n\n<p>to make sure you have a two-column offset on the left hand side of each div. Then you eliminate the need for empty divs used only for spacing.</p>\n\n<p>More at <a href=\"http://getbootstrap.com/css/#grid-offsetting\" rel=\"nofollow noreferrer\">http://getbootstrap.com/css/#grid-offsetting</a></p>\n" } ]
2017/04/10
[ "https://wordpress.stackexchange.com/questions/263067", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/115607/" ]
I'm trying to list posts in a custom post type, within a layout like following. [![Layout](https://i.stack.imgur.com/nIxPB.jpg)](https://i.stack.imgur.com/nIxPB.jpg) html for below layout like this. ``` <div class="col-md-4 col-sm-6"> PROFILE - 1 </div> <div class="col-md-4 col-sm-6"> </div> <div class="col-md-4 col-sm-6"> PROFILE - 2 </div> <div class="col-md-4 col-sm-6"> PROFILE - 3 </div> <div class="col-md-4 col-sm-6"> </div> <div class="col-md-4 col-sm-6"> PROFILE - 4 </div> ``` as you can see after "PROFILE - 1" there is a div separator then there is "PROFILE - 1 & PROFILE - 2" after "PROFILE - 1 & PROFILE - 2" again div separator. basically the structure as follows. Profile-1 V V Empty space (div based col-md-4 col-sm-6 ) V V Profile-2 V V Profile-3 V V Empty space (div based col-md-4 col-sm-6 ) V V Profile-4 i'm using this loop as a custom structure but i'm unable to get it from Profile-2 > Profile-3 > Space point. looking for a help to achieve this loop. THIS IS WHAT I HAVE TRIED ``` <?php $args=array( 'post_type' => 'ourteam', 'posts_per_page' => -1 ); //Set up a counter $counter = 0; //Preparing the Loop $query = new WP_Query( $args ); //In while loop counter increments by one $counter++ if( $query->have_posts() ) : while( $query->have_posts() ) : $query- >the_post(); $counter++; //We are in loop so we can check if counter is odd or even if( $counter % 2 == 0 ) : //It's even ?> <div class="col-md-4 col-sm-6"> </div> <div class="col-md-4 col-sm-6"> <div class="cp-attorneys-style-2"> <div class="frame"> <a href="<?php the_permalink(); ?>"><?php the_post_thumbnail(''); ?></a> <div class="caption"> <div class="holder"> <ul> <li><a href="<?php the_field('mem_twitter'); ?>"><i class="fa fa-twitter"></i></a></li> <li><a href="<?php the_field('mem_facebook'); ?>"><i class="fa fa-facebook"></i></a></li> <li><a href="<?php the_field('mem_linkedin'); ?>"><i class="fa fa-linkedin"></i></a></li> </ul> <p> </p> <a href="<?php the_permalink(); ?>" class="btn-style-1">Read Profile</a> </div> </div> </div> <div class="cp-text-box"> <h3><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3> <em><?php the_field('mem_titles'); ?></em> </div> </div> </div> <div class="col-md-4 col-sm-6"> </div> <?php else: //It's odd ?> <div class="col-md-4 col-sm-6"> <div class="cp-attorneys-style-2"> <div class="frame"> <a href="<?php the_permalink(); ?>"><?php the_post_thumbnail(''); ?></a> <div class="caption"> <div class="holder"> <ul> <li><a href="<?php the_field('mem_twitter'); ?>"><i class="fa fa-twitter"></i></a></li> <li><a href="<?php the_field('mem_facebook'); ?>"><i class="fa fa-facebook"></i></a></li> <li><a href="<?php the_field('mem_linkedin'); ?>"><i class="fa fa-linkedin"></i></a></li> </ul> <p> </p> <a href="<?php the_permalink(); ?>" class="btn-style-1">Read Profile</a> </div> </div> </div> <div class="cp-text-box"> <h3><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3> <em><?php the_field('mem_titles'); ?></em> </div> </div> </div> <?php endif; endwhile; wp_reset_postdata(); endif; ?> ```
You can set your custom loop something like this ``` $a=2; //In while loop counter increments by one $counter++ if( $query->have_posts() ) : while( $query->have_posts() ) : $query->the_post(); if($a%3!=0){ //Here write function to display title and discription ?> <div class="col-md-4 col-sm-6"> <div class="cp-attorneys-style-2"> <div class="frame"> <a href="<?php the_permalink(); ?>"><?php the_post_thumbnail(''); ?></a> <div class="caption"> <div class="holder"> <ul> <li><a href="<?php the_field('mem_twitter'); ?>"><i class="fa fa-twitter"></i></a></li> <li><a href="<?php the_field('mem_facebook'); ?>"><i class="fa fa-facebook"></i></a></li> <li><a href="<?php the_field('mem_linkedin'); ?>"><i class="fa fa-linkedin"></i></a></li> </ul> <p> </p> <a href="<?php the_permalink(); ?>" class="btn-style-1">Read Profile</a> </div> </div> </div> <div class="cp-text-box"> <h3><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3> <em><?php the_field('mem_titles'); ?></em> </div> </div> </div> <?php $a = $a+1; } else { ?> <div class="col-md-4 col-sm-6"> <?php //Leave this div empty ?> </div> <div class="col-md-4 col-sm-6"> <div class="cp-attorneys-style-2"> <div class="frame"> <a href="<?php the_permalink(); ?>"><?php the_post_thumbnail(''); ?></a> <div class="caption"> <div class="holder"> <ul> <li><a href="<?php the_field('mem_twitter'); ?>"><i class="fa fa-twitter"></i></a></li> <li><a href="<?php the_field('mem_facebook'); ?>"><i class="fa fa-facebook"></i></a></li> <li><a href="<?php the_field('mem_linkedin'); ?>"><i class="fa fa-linkedin"></i></a></li> </ul> <p> </p> <a href="<?php the_permalink(); ?>" class="btn-style-1">Read Profile</a> </div> </div> </div> <div class="cp-text-box"> <h3><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3> <em><?php the_field('mem_titles'); ?></em> </div> </div> </div> <?php $a = $a+2; } endwhile; wp_reset_postdata(); endif; ``` Take backup of your code first.
263,086
<p>I am trying to add pagination to my custom WPQuery loop.</p> <p>I tried pretty much every trick in the book but it does not work.</p> <p>Any ideas on that ? Thank you in advance.</p> <pre><code>&lt;div class="container"&lt;?php if($background_color != "") { echo " style='background-color:". $background_color ."'";} ?&gt;&gt; &lt;?php if(isset($qode_options_proya['overlapping_content']) &amp;&amp; $qode_options_proya['overlapping_content'] == 'yes') {?&gt; &lt;div class="overlapping_content"&gt;&lt;div class="overlapping_content_inner"&gt; &lt;?php } ?&gt; &lt;div class="container_inner default_template_holder clearfix frontpage"&gt; &lt;div class="container"&gt; &lt;?php $paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1; $args=array( 'post_type' =&gt; 'gadget', 'post_status' =&gt; 'publish', 'posts_per_page' =&gt; 24, 'paged' =&gt; $paged ); $fp_query = null; $fp_query = new WP_Query($args); if( $fp_query-&gt;have_posts() ) { $i = 0; while ($fp_query-&gt;have_posts()) : $fp_query-&gt;the_post(); // modified to work with 3 columns // output an open &lt;div&gt; if($i % 3 == 0) { ?&gt; &lt;div class="vc_row prd-box-row"&gt; &lt;?php } ?&gt; &lt;div class="vc_col-md-4 vc_col-sm-6 vc_col-xs-12 prd-box row-height"&gt; &lt;div class="prd-box-inner"&gt; &lt;div class="prd-box-image-container"&gt; &lt;a href="&lt;?php the_permalink(); ?&gt;"&gt; &lt;div class="prd-box-image" style ="background-image: url( &lt;?php /* ACF */ the_field('header_image'); ?&gt; &lt;?php /* Types */ $headerimage = get_post_meta(get_the_ID(), 'wpcf-headerimage'); var_dump($headerimage); echo types_render_field('wpcf-headerimage', array("raw"=&gt;"true", "url"=&gt;"true")); ?&gt;);"&gt; &lt;div class="vc_col-xs-12 prd-box-date"&gt;&lt;?php $short_date = get_the_date( 'M j' ); echo $short_date;?&gt;&lt;span class="full-date"&gt;, &lt;?php $full_date = get_the_date( 'Y' ); echo $full_date;?&gt;&lt;/span&gt;&lt;/div&gt; &lt;div class="badges-container"&gt; &lt;!-- Discount Condition --&gt; &lt;div class="vc_col-xs-2 discounted-badge"&gt; &lt;i class="fa fa-percent" aria-hidden="true"&gt;&lt;/i&gt; &lt;/div&gt; &lt;!-- Video Condition --&gt; &lt;div class="vc_col-xs-2 video-badge"&gt; &lt;i class="fa fa-play" aria-hidden="true"&gt;&lt;/i&gt; &lt;/div&gt; &lt;!-- Crowdfunding Condition --&gt; &lt;div class="vc_col-xs-2 crowdfunding-badge"&gt; &lt;i class="fa fa-money" aria-hidden="true"&gt;&lt;/i&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/a&gt; &lt;/div&gt; &lt;div class="prd-separator"&gt;&lt;/div&gt; &lt;div class="vc_row prd-box-info"&gt; &lt;div class="vc_col-xs-12 prd-box-title"&gt;&lt;a href="&lt;?php the_permalink(); ?&gt;" title="&lt;?php the_title_attribute(); ?&gt;"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;&lt;/div&gt; &lt;/div&gt; &lt;div class="prd-separator"&gt;&lt;/div&gt; &lt;div class="vc_row"&gt; &lt;div class="vc_col-xs-6"&gt; &lt;div class="vc_col-xs-12 prd-box-price"&gt;$10&lt;/div&gt; &lt;/div&gt; &lt;div class="vc_col-xs-6 prd-box-category"&gt; &lt;?php $term_slug = get_query_var('term'); $taxonomy_name = get_query_var('taxonomy'); $current_term = get_term_by('slug', $term_slug, $taxonomy_name); if ( true === is_a( $current_term, 'WP_Term' ) ) { $args = array( 'child_of' =&gt; $current_term-&gt;term_id, 'orderby' =&gt; 'id', 'order' =&gt; 'DESC' ); $terms = get_terms($taxonomyName, $args); if ( true === is_array( $terms ) ) { foreach ($terms as $term) { echo '&lt;li id="mid"&gt;&lt;a href="#tab-' . esc_attr( $term-&gt;slug ) . '"&gt;' . esc_html( $term-&gt;name ) . '&lt;/a&gt;&lt;/li&gt;'; } } } ?&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="vc_row prd-box-share-wh-row"&gt; &lt;div class="prd-separator"&gt;&lt;/div&gt; &lt;div class="prd-box-share-container"&gt; &lt;div class="vc_col-xs-1"&gt;&lt;/div&gt; &lt;div class="vc_col-xs-4"&gt;&lt;?php echo do_shortcode( '[addtoany]' );?&gt;&lt;/div&gt; &lt;div class="vc_col-xs-1"&gt;&lt;/div&gt; &lt;/div&gt; &lt;div class="prd-box-wishlist-container"&gt; &lt;div class="vc_col-xs-1"&gt;&lt;/div&gt; &lt;div class="vc_col-xs-4"&gt; &lt;?php $arg = array ( 'echo' =&gt; true ); do_action('gd_mylist_btn',$arg); ?&gt; &lt;/div&gt; &lt;div class="vc_col-xs-1"&gt;&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="prd-separator"&gt;&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;?php $i++; // Closing the grid row div if($i != 0 &amp;&amp; $i % 3 == 0) { ?&gt; &lt;/div&gt;&lt;!--/.row--&gt; &lt;div class="clearfix"&gt;&lt;/div&gt; &lt;?php } ?&gt; &lt;!-- Random Category Snippet Generation --&gt; &lt;?php if( $i % 12 == 0 ) { $max = 1; //number of categories to display $taxonomy = 'gadget_categories'; $terms = get_terms($taxonomy, 'orderby=name&amp;order= ASC&amp;hide_empty=0'); // Random order shuffle($terms); // Get first $max items $terms = array_slice($terms, 0, $max); // Sort by name usort($terms, function($a, $b){ return strcasecmp($a-&gt;name, $b-&gt;name); }); // Echo random terms sorted alphabetically if ($terms) { foreach($terms as $term) { $termID = $term-&gt;term_id; echo '&lt;div class="random-category-snippet vc_row" style="background-image: url('.types_render_termmeta("category-image", array( "term_id" =&gt; $termID, "output" =&gt;"raw") ).')"&gt;&lt;div class="random-snippet-inner"&gt;&lt;a href="' .get_term_link( $term, $taxonomy ) . '" title="' . sprintf( __( "View all gadgets in %s" ), $term-&gt;name ) . '" ' . '&gt;' . $term-&gt;name.'&lt;/a&gt;&lt;p&gt;' . $term-&gt;description . '&lt;/p&gt;&lt;br&gt;&lt;br&gt;&lt;a class="explore-category" href="'. esc_url( get_term_link( $term ) ) .'"&gt;Explore This Category&lt;/a&gt;&lt;/div&gt;&lt;/div&gt; '; } } } ?&gt; &lt;?php endwhile; } wp_reset_query(); ?&gt; &lt;!-- pagination --&gt; &lt;?php next_posts_link(); ?&gt; &lt;?php previous_posts_link(); ?&gt; &lt;/div&gt;&lt;!--/.container--&gt; &lt;/div&gt; </code></pre>
[ { "answer_id": 263098, "author": "Aniruddha Gawade", "author_id": 101818, "author_profile": "https://wordpress.stackexchange.com/users/101818", "pm_score": -1, "selected": false, "text": "<p>As far as I remember, the functions you are using uses global <code>$wp_query</code>. So instead of <code>$fp_query</code> try: </p>\n\n<pre><code>global $wp_query;\n$args = array(); //your args\n$wp_query = new WP_Query($args);\n//your loop\nnext_posts_link();\nprevious_posts_link();\nwp_reset_query();\n</code></pre>\n\n<p>Also notice that <code>wp_reset_query()</code> is after pagination parts.</p>\n" }, { "answer_id": 263107, "author": "Aamer Shahzad", "author_id": 42772, "author_profile": "https://wordpress.stackexchange.com/users/42772", "pm_score": -1, "selected": false, "text": "<p>source : <a href=\"https://wordpress.stackexchange.com/questions/120407/how-to-fix-pagination-for-custom-loops\">How to fix pagination for custom loops?</a></p>\n\n<pre><code>&lt;?php \n$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;\n$args=array(\n 'post_type' =&gt; 'gadget',\n 'post_status' =&gt; 'publish',\n 'posts_per_page' =&gt; 24,\n 'paged' =&gt; $paged\n);\n\n$temp = $wp_query;\n$fp_query = null;\n$fp_query = new WP_Query($args);\n\nif ( $fp_query-&gt;have_posts() ) : while ( $fp_query-&gt;have_posts() ) : $fp_query-&gt;the_post(); \n\n/* DO STUFF IN THE LOOP */\n\nendwhile; endif;\n\nnext_posts_link();\nprevious_posts_link();\n\n$fp_query = null;\n$fp_query = $temp;\nwp_reset_query(); ?&gt;\n</code></pre>\n" } ]
2017/04/10
[ "https://wordpress.stackexchange.com/questions/263086", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/115305/" ]
I am trying to add pagination to my custom WPQuery loop. I tried pretty much every trick in the book but it does not work. Any ideas on that ? Thank you in advance. ``` <div class="container"<?php if($background_color != "") { echo " style='background-color:". $background_color ."'";} ?>> <?php if(isset($qode_options_proya['overlapping_content']) && $qode_options_proya['overlapping_content'] == 'yes') {?> <div class="overlapping_content"><div class="overlapping_content_inner"> <?php } ?> <div class="container_inner default_template_holder clearfix frontpage"> <div class="container"> <?php $paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1; $args=array( 'post_type' => 'gadget', 'post_status' => 'publish', 'posts_per_page' => 24, 'paged' => $paged ); $fp_query = null; $fp_query = new WP_Query($args); if( $fp_query->have_posts() ) { $i = 0; while ($fp_query->have_posts()) : $fp_query->the_post(); // modified to work with 3 columns // output an open <div> if($i % 3 == 0) { ?> <div class="vc_row prd-box-row"> <?php } ?> <div class="vc_col-md-4 vc_col-sm-6 vc_col-xs-12 prd-box row-height"> <div class="prd-box-inner"> <div class="prd-box-image-container"> <a href="<?php the_permalink(); ?>"> <div class="prd-box-image" style ="background-image: url( <?php /* ACF */ the_field('header_image'); ?> <?php /* Types */ $headerimage = get_post_meta(get_the_ID(), 'wpcf-headerimage'); var_dump($headerimage); echo types_render_field('wpcf-headerimage', array("raw"=>"true", "url"=>"true")); ?>);"> <div class="vc_col-xs-12 prd-box-date"><?php $short_date = get_the_date( 'M j' ); echo $short_date;?><span class="full-date">, <?php $full_date = get_the_date( 'Y' ); echo $full_date;?></span></div> <div class="badges-container"> <!-- Discount Condition --> <div class="vc_col-xs-2 discounted-badge"> <i class="fa fa-percent" aria-hidden="true"></i> </div> <!-- Video Condition --> <div class="vc_col-xs-2 video-badge"> <i class="fa fa-play" aria-hidden="true"></i> </div> <!-- Crowdfunding Condition --> <div class="vc_col-xs-2 crowdfunding-badge"> <i class="fa fa-money" aria-hidden="true"></i> </div> </div> </div> </a> </div> <div class="prd-separator"></div> <div class="vc_row prd-box-info"> <div class="vc_col-xs-12 prd-box-title"><a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a></div> </div> <div class="prd-separator"></div> <div class="vc_row"> <div class="vc_col-xs-6"> <div class="vc_col-xs-12 prd-box-price">$10</div> </div> <div class="vc_col-xs-6 prd-box-category"> <?php $term_slug = get_query_var('term'); $taxonomy_name = get_query_var('taxonomy'); $current_term = get_term_by('slug', $term_slug, $taxonomy_name); if ( true === is_a( $current_term, 'WP_Term' ) ) { $args = array( 'child_of' => $current_term->term_id, 'orderby' => 'id', 'order' => 'DESC' ); $terms = get_terms($taxonomyName, $args); if ( true === is_array( $terms ) ) { foreach ($terms as $term) { echo '<li id="mid"><a href="#tab-' . esc_attr( $term->slug ) . '">' . esc_html( $term->name ) . '</a></li>'; } } } ?> </div> </div> <div class="vc_row prd-box-share-wh-row"> <div class="prd-separator"></div> <div class="prd-box-share-container"> <div class="vc_col-xs-1"></div> <div class="vc_col-xs-4"><?php echo do_shortcode( '[addtoany]' );?></div> <div class="vc_col-xs-1"></div> </div> <div class="prd-box-wishlist-container"> <div class="vc_col-xs-1"></div> <div class="vc_col-xs-4"> <?php $arg = array ( 'echo' => true ); do_action('gd_mylist_btn',$arg); ?> </div> <div class="vc_col-xs-1"></div> </div> </div> <div class="prd-separator"></div> </div> </div> <?php $i++; // Closing the grid row div if($i != 0 && $i % 3 == 0) { ?> </div><!--/.row--> <div class="clearfix"></div> <?php } ?> <!-- Random Category Snippet Generation --> <?php if( $i % 12 == 0 ) { $max = 1; //number of categories to display $taxonomy = 'gadget_categories'; $terms = get_terms($taxonomy, 'orderby=name&order= ASC&hide_empty=0'); // Random order shuffle($terms); // Get first $max items $terms = array_slice($terms, 0, $max); // Sort by name usort($terms, function($a, $b){ return strcasecmp($a->name, $b->name); }); // Echo random terms sorted alphabetically if ($terms) { foreach($terms as $term) { $termID = $term->term_id; echo '<div class="random-category-snippet vc_row" style="background-image: url('.types_render_termmeta("category-image", array( "term_id" => $termID, "output" =>"raw") ).')"><div class="random-snippet-inner"><a href="' .get_term_link( $term, $taxonomy ) . '" title="' . sprintf( __( "View all gadgets in %s" ), $term->name ) . '" ' . '>' . $term->name.'</a><p>' . $term->description . '</p><br><br><a class="explore-category" href="'. esc_url( get_term_link( $term ) ) .'">Explore This Category</a></div></div> '; } } } ?> <?php endwhile; } wp_reset_query(); ?> <!-- pagination --> <?php next_posts_link(); ?> <?php previous_posts_link(); ?> </div><!--/.container--> </div> ```
As far as I remember, the functions you are using uses global `$wp_query`. So instead of `$fp_query` try: ``` global $wp_query; $args = array(); //your args $wp_query = new WP_Query($args); //your loop next_posts_link(); previous_posts_link(); wp_reset_query(); ``` Also notice that `wp_reset_query()` is after pagination parts.
263,109
<p>I'm making a translation system for my website and I'm having troubles with URL rewriting. Each page is translated to multiple languages and should have different URLs for each language, e.g.:</p> <pre><code>/en/best-restaurants-in-tokyo /it/migliori-ristoranti-a-tokyo /fr/meilleurs-restaurants-à-tokyo </code></pre> <p>et cetera.</p> <p>All those links should open the same post. All the translation related info (including the slug) is stored in a separate table. Changing the content of a post based on the selected language is trivial, but I can't come up with working URL rewriting.</p> <p>Ideally, I would like to have code like that:</p> <pre><code>$languageShortNames = join('|', $languageShortNames); add_rewrite_rule('('.$languageShortNames.')/(.*)/?', 'index.php?p=4015&amp;language=$matches[1]', 'top'); </code></pre> <p>but instead of <code>p</code> being a set number, it should be dynamically determined by some callback. </p> <p>One working solution I've stumbled upon is to call <code>add_rewrite_rule</code> in a cycle for every existing post for each language. The problem is that my site has thousands of posts, so I think performance will be abysmal. It would really make more sense if I could simply chose the post ID I want to render in a callback by searching the translation table for a post ID with the slug.</p>
[ { "answer_id": 263098, "author": "Aniruddha Gawade", "author_id": 101818, "author_profile": "https://wordpress.stackexchange.com/users/101818", "pm_score": -1, "selected": false, "text": "<p>As far as I remember, the functions you are using uses global <code>$wp_query</code>. So instead of <code>$fp_query</code> try: </p>\n\n<pre><code>global $wp_query;\n$args = array(); //your args\n$wp_query = new WP_Query($args);\n//your loop\nnext_posts_link();\nprevious_posts_link();\nwp_reset_query();\n</code></pre>\n\n<p>Also notice that <code>wp_reset_query()</code> is after pagination parts.</p>\n" }, { "answer_id": 263107, "author": "Aamer Shahzad", "author_id": 42772, "author_profile": "https://wordpress.stackexchange.com/users/42772", "pm_score": -1, "selected": false, "text": "<p>source : <a href=\"https://wordpress.stackexchange.com/questions/120407/how-to-fix-pagination-for-custom-loops\">How to fix pagination for custom loops?</a></p>\n\n<pre><code>&lt;?php \n$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;\n$args=array(\n 'post_type' =&gt; 'gadget',\n 'post_status' =&gt; 'publish',\n 'posts_per_page' =&gt; 24,\n 'paged' =&gt; $paged\n);\n\n$temp = $wp_query;\n$fp_query = null;\n$fp_query = new WP_Query($args);\n\nif ( $fp_query-&gt;have_posts() ) : while ( $fp_query-&gt;have_posts() ) : $fp_query-&gt;the_post(); \n\n/* DO STUFF IN THE LOOP */\n\nendwhile; endif;\n\nnext_posts_link();\nprevious_posts_link();\n\n$fp_query = null;\n$fp_query = $temp;\nwp_reset_query(); ?&gt;\n</code></pre>\n" } ]
2017/04/10
[ "https://wordpress.stackexchange.com/questions/263109", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/60984/" ]
I'm making a translation system for my website and I'm having troubles with URL rewriting. Each page is translated to multiple languages and should have different URLs for each language, e.g.: ``` /en/best-restaurants-in-tokyo /it/migliori-ristoranti-a-tokyo /fr/meilleurs-restaurants-à-tokyo ``` et cetera. All those links should open the same post. All the translation related info (including the slug) is stored in a separate table. Changing the content of a post based on the selected language is trivial, but I can't come up with working URL rewriting. Ideally, I would like to have code like that: ``` $languageShortNames = join('|', $languageShortNames); add_rewrite_rule('('.$languageShortNames.')/(.*)/?', 'index.php?p=4015&language=$matches[1]', 'top'); ``` but instead of `p` being a set number, it should be dynamically determined by some callback. One working solution I've stumbled upon is to call `add_rewrite_rule` in a cycle for every existing post for each language. The problem is that my site has thousands of posts, so I think performance will be abysmal. It would really make more sense if I could simply chose the post ID I want to render in a callback by searching the translation table for a post ID with the slug.
As far as I remember, the functions you are using uses global `$wp_query`. So instead of `$fp_query` try: ``` global $wp_query; $args = array(); //your args $wp_query = new WP_Query($args); //your loop next_posts_link(); previous_posts_link(); wp_reset_query(); ``` Also notice that `wp_reset_query()` is after pagination parts.
263,116
<p>I'm writing a plugin that makes searches work only on a particular custom post type and it sorts the results according to the taxonomies the user selects in its backend configuration.</p> <p>The admin can select up to 4 taxonomies of the custom post type: each one is then a sort criterion that must be applied to the search results. The admin can then select the terms of each taxonomy that make the post appear before others in search results. The first selected taxonomy will be the most important sort criterion; the others will be applied in order. </p> <p>I need a query along the lines of:</p> <pre><code>SELECT * FROM wp_posts ORDER BY choosen_terms_of_taxonomy1, choosen_terms_of_axonomy2, ... </code></pre> <p>Now let's use some sample data. We have the <code>course</code> post type:</p> <pre><code>+----+------------+ | ID | post_title | +----+------------+ | 12 | Cooking | +----+------------+ | 13 | Surfing | +----+------------+ | 14 | Building | +----+------------+ | 15 | Hacking | +----+------------+ </code></pre> <p>Then we have two taxonomies for this custom post type. One is <code>place</code> and the other is <code>pricetag</code>. The <code>place</code> taxonomy has the following terms:</p> <pre><code>+---------+------------+ | term_id | slug | +---------+------------+ | 21 | downtown | +---------+------------+ | 22 | abroad | +---------+------------+ </code></pre> <p>The <code>pricetag</code> taxonomy has the following terms:</p> <pre><code>+---------+------------+ | term_id | slug | +---------+------------+ | 31 | expensive | +---------+------------+ | 32 | cheap | +---------+------------+ </code></pre> <p>And finally we have <code>wp_term_relationships</code> that links the courses to the taxonomies terms this way:</p> <pre><code>+-----------+------------+---------+ | object_id | post_title | term_id | +-----------+------------+---------+ | 12 | Cooking | 21 | (downtown) +-----------+------------+---------+ | 12 | Cooking | 32 | (cheap) +-----------+------------+---------+ | 13 | Surfing | 22 | (abroad) +-----------+------------+---------+ | 13 | Surfing | 31 | (expensive) +-----------+------------+---------+ | 14 | Building | 21 | (downtown) +-----------+------------+---------+ | 14 | Building | 31 | (expensive) +-----------+------------+---------+ | 15 | Hacking | 22 | (abroad) +-----------+------------+---------+ | 15 | Hacking | 32 | (cheap) +-----------+------------+---------+ </code></pre> <p>(Please note: I do know that's not the real structure of the <code>wp_term_relationships</code> table, but I wanted to simplify it a bit for the sake of this question.)</p> <p>Let's assume the admin has chosen <code>place</code> as the first taxonomy to use as a sort criterion and that he has chosen to show <code>downtown</code> courses first (the admin screen of the plugin is already done and it already provides the admin with the UI to make such choices).</p> <p>Then say the admin has chosen <code>pricetag</code> as second taxonomy to use as sort criterion and that he wants <code>expensive</code> courses to show up first. Note that being a second criterion, it has less sorting priority than the first, so the admin wants downtown courses first and then, in the group of downtown courses, expensive courses first.</p> <p>Now a frontend user searches for all courses on the website, and he should see these results in this exact order:</p> <ol> <li>Building course (because it's downtown and expensive)</li> <li>Cooking course (because it's downtown and cheap)</li> <li>Surfing course (because it's abroad and expensive)</li> <li>Hacking course (because it's abroad and cheap)</li> </ol> <p>My problem is writing the correct <code>JOIN</code> and <code>ORDER BY</code> clauses in the Wordpress query object. I've already hooked <code>posts_clauses</code> and here is the SQL query I'm generating:</p> <pre><code>SELECT SQL_CALC_FOUND_ROWS wp_posts.* FROM wp_posts LEFT JOIN (wp_term_relationships, wp_term_taxonomy, wp_terms) ON (wp_term_relationships.object_id = wp_posts.ID AND wp_term_taxonomy.term_taxonomy_id = wp_term_relationships.term_taxonomy_id AND wp_terms.term_id = wp_term_taxonomy.term_id) WHERE 1=1 AND (((wp_posts.post_title LIKE '%%') OR (wp_posts.post_excerpt LIKE '%%') OR (wp_posts.post_content LIKE '%%'))) AND wp_posts.post_type IN ('post', 'page', 'attachment', 'course') AND (wp_posts.post_status = 'publish' OR wp_posts.post_author = 1 AND wp_posts.post_status = 'private') AND wp_posts.post_type='course' ORDER BY (wp_terms.slug LIKE 'downtown' AND wp_term_taxonomy.taxonomy LIKE 'place') DESC, (wp_terms.slug LIKE 'abroad' AND wp_term_taxonomy.taxonomy LIKE 'place') DESC, (wp_terms.slug LIKE 'expensive' AND wp_term_taxonomy.taxonomy LIKE 'pricetag') DESC, (wp_terms.slug LIKE 'cheap' AND wp_term_taxonomy.taxonomy LIKE 'pricetag') DESC, wp_posts.post_title LIKE '%%' DESC, wp_posts.post_date DESC LIMIT 0, 300 </code></pre> <p>However this query has at least two problems:</p> <ol> <li>it returns twice the results and I don't understand why, because LEFT JOIN should not produce a Cartesian product between the specified tables</li> <li>the resulting sort order is unclear to me (it seems to be just <code>post_date DESC</code>), but it's clear it is NOT what I'm expecting.</li> </ol> <p>I've tried simplifying the query by removing Wordpress generated clauses:</p> <pre><code>SELECT wp_posts.* FROM wp_posts LEFT JOIN (wp_term_relationships, wp_term_taxonomy, wp_terms) ON (wp_term_relationships.object_id = wp_posts.ID AND wp_term_taxonomy.term_taxonomy_id = wp_term_relationships.term_taxonomy_id AND wp_terms.term_id = wp_term_taxonomy.term_id) WHERE 1=1 AND wp_posts.post_type='course' ORDER BY (wp_terms.slug LIKE 'downtown' AND wp_term_taxonomy.taxonomy LIKE 'place') DESC, (wp_terms.slug LIKE 'abroad' AND wp_term_taxonomy.taxonomy LIKE 'place') DESC, (wp_terms.slug LIKE 'expensive' AND wp_term_taxonomy.taxonomy LIKE 'pricetag') DESC, (wp_terms.slug LIKE 'cheap' AND wp_term_taxonomy.taxonomy LIKE 'pricetag') DESC </code></pre> <p>This one has exactly the same problems, but it is a bit easier to understand, and it returns the data as if no <code>ORDER BY</code> was there at all.</p> <p>Can you help me please?</p>
[ { "answer_id": 263420, "author": "Abhishek Pandey", "author_id": 114826, "author_profile": "https://wordpress.stackexchange.com/users/114826", "pm_score": 0, "selected": false, "text": "<p>You can use <code>tax_query</code> for sorting with taxonomy i.e.</p>\n\n<pre><code> $args = array(\n posts_per_page =&gt; -1,\n post_type =&gt; 'your post type',\n tax_query' =&gt; array(\n 'relation' =&gt; 'OR',\n array(\n 'taxonomy' =&gt; 'your custom taxonomy',\n 'field' =&gt; 'slug',\n 'terms' =&gt; $_REQUEST[your post requested],\n ),\n array(\n 'taxonomy' =&gt; 'your 2nd custom taxonomy',\n 'field' =&gt; 'slug',\n 'terms' =&gt; $_REQUEST[your post requested],\n ),\n ),\n ):\n\n $query = new WP_Query( $args );\n</code></pre>\n" }, { "answer_id": 263562, "author": "J.D.", "author_id": 27757, "author_profile": "https://wordpress.stackexchange.com/users/27757", "pm_score": 4, "selected": true, "text": "<p>Unfortunately, although <code>WP_Query</code> supports the <code>'tax_query'</code> arg, it does not support ordering based on post terms. So you will need to modify the query SQL, as you are doing now. However, you are constructing the <code>ORDER BY</code> clause incorrectly, and that is why it is ordering by <code>post_date</code>. What you need to do is use a <code>CASE</code> statement, like this:</p>\n\n<pre><code>CASE \n WHEN (wp_terms.slug LIKE 'downtown' AND wp_term_taxonomy.taxonomy LIKE 'place') THEN 1\n WHEN (wp_terms.slug LIKE 'abroad' AND wp_term_taxonomy.taxonomy LIKE 'place') THEN 0\nEND\n</code></pre>\n\n<p>This will order based on the priority that you assign to each of the terms (<code>1</code>, <code>0</code>, etc., higher being higher priority, unless you use <code>ASC</code> instead of <code>DESC</code> for ordering).</p>\n\n<p>Because you want to order these two taxonomies independently, you will need to have two joins, and two case statements. (See below for example.)</p>\n\n<p>You also need to cause a <code>GROUP BY</code> on the post ID, to avoid duplicate results:</p>\n\n<pre><code> $clauses['groupby'] = 'wptests_posts.ID';\n</code></pre>\n\n<p>So your final query would end up looking something like this (formatted for easier reading):</p>\n\n<pre><code> SELECT SQL_CALC_FOUND_ROWS wptests_posts.ID FROM wptests_posts \n LEFT JOIN (\n wptests_term_relationships tr_place,\n wptests_term_taxonomy tt_place,\n wptests_terms t_place\n ) ON (\n tr_place.object_id = wptests_posts.ID \n AND tt_place.term_taxonomy_id = tr_place.term_taxonomy_id\n AND tt_place.taxonomy = 'place'\n AND t_place.term_id = tt_place.term_id\n ) \n\n LEFT JOIN (\n wptests_term_relationships tr_pricetag,\n wptests_term_taxonomy tt_pricetag,\n wptests_terms t_pricetag\n ) ON (\n tr_pricetag.object_id = wptests_posts.ID \n AND tt_pricetag.term_taxonomy_id = tr_pricetag.term_taxonomy_id\n AND tt_pricetag.taxonomy = 'pricetag'\n AND t_pricetag.term_id = tt_pricetag.term_id\n ) \n WHERE 1=1 AND wptests_posts.post_type = 'course' AND (wptests_posts.post_status = 'publish')\n GROUP BY wptests_posts.ID\n ORDER BY \n (CASE \n WHEN (t_place.slug LIKE 'downtown') THEN 1\n WHEN (t_place.slug LIKE 'abroad') THEN 0\n END) DESC, (CASE\n WHEN (t_pricetag.slug LIKE 'expensive') THEN 1\n WHEN (t_pricetag.slug LIKE 'cheap') THEN 0\n END) DESC,\n wptests_posts.post_date DESC\n LIMIT 0, 10\n</code></pre>\n\n<p>Here is an example PHPUnit test that demonstrates that this works, including example code for generating the joins and orderbys (it was used to generate the above query):</p>\n\n<pre><code>class My_Test extends WP_UnitTestCase {\n\n public function test() {\n\n // Create the post type.\n register_post_type( 'course' );\n\n // Create the posts.\n $cooking_post_id = $this-&gt;factory-&gt;post-&gt;create(\n array( 'post_title' =&gt; 'Cooking', 'post_type' =&gt; 'course' )\n );\n $surfing_post_id = $this-&gt;factory-&gt;post-&gt;create(\n array( 'post_title' =&gt; 'Surfing', 'post_type' =&gt; 'course' )\n );\n $building_post_id = $this-&gt;factory-&gt;post-&gt;create(\n array( 'post_title' =&gt; 'Building', 'post_type' =&gt; 'course' )\n );\n $hacking_post_id = $this-&gt;factory-&gt;post-&gt;create(\n array( 'post_title' =&gt; 'Hacking', 'post_type' =&gt; 'course' )\n );\n\n // Create the taxonomies.\n register_taxonomy( 'place', 'course' );\n register_taxonomy( 'pricetag', 'course' );\n\n // Create the terms.\n $downtown_term_id = wp_create_term( 'downtown', 'place' );\n $abroad_term_id = wp_create_term( 'abroad', 'place' );\n\n $expensive_term_id = wp_create_term( 'expensive', 'pricetag' );\n $cheap_term_id = wp_create_term( 'cheap', 'pricetag' );\n\n // Give the terms to the correct posts.\n wp_add_object_terms( $cooking_post_id, $downtown_term_id, 'place' );\n wp_add_object_terms( $cooking_post_id, $cheap_term_id, 'pricetag' );\n\n wp_add_object_terms( $surfing_post_id, $abroad_term_id, 'place' );\n wp_add_object_terms( $surfing_post_id, $expensive_term_id, 'pricetag' );\n\n wp_add_object_terms( $building_post_id, $downtown_term_id, 'place' );\n wp_add_object_terms( $building_post_id, $expensive_term_id, 'pricetag' );\n\n wp_add_object_terms( $hacking_post_id, $abroad_term_id, 'place' );\n wp_add_object_terms( $hacking_post_id, $cheap_term_id, 'pricetag' );\n\n $query = new WP_Query(\n array(\n 'fields' =&gt; 'ids',\n 'post_type' =&gt; 'course',\n )\n );\n\n add_filter( 'posts_clauses', array( $this, 'filter_post_clauses' ) );\n\n $results = $query-&gt;get_posts();\n\n $this-&gt;assertSame(\n array(\n $building_post_id,\n $cooking_post_id,\n $surfing_post_id,\n $hacking_post_id,\n )\n , $results\n );\n }\n\n public function filter_post_clauses( $clauses ) {\n\n global $wpdb;\n\n $clauses['orderby'] = \"\n (CASE \n WHEN (t_place.slug LIKE 'downtown') THEN 1\n WHEN (t_place.slug LIKE 'abroad') THEN 0\n END) DESC, (CASE\n WHEN (t_pricetag.slug LIKE 'expensive') THEN 1\n WHEN (t_pricetag.slug LIKE 'cheap') THEN 0\n END) DESC,\n \" . $clauses['orderby'];\n\n foreach ( array( 'place', 'pricetag' ) as $taxonomy ) {\n\n // Instead of interpolating directly here, you should use $wpdb-&gt;prepare() for $taxonomy.\n $clauses['join'] .= \"\n LEFT JOIN (\n $wpdb-&gt;term_relationships tr_$taxonomy,\n $wpdb-&gt;term_taxonomy tt_$taxonomy,\n $wpdb-&gt;terms t_$taxonomy\n ) ON (\n tr_$taxonomy.object_id = $wpdb-&gt;posts.ID \n AND tt_$taxonomy.term_taxonomy_id = tr_$taxonomy.term_taxonomy_id\n AND tt_$taxonomy.taxonomy = '$taxonomy'\n AND t_$taxonomy.term_id = tt_$taxonomy.term_id\n ) \n \";\n }\n\n $clauses['groupby'] = 'wptests_posts.ID';\n\n return $clauses;\n }\n}\n</code></pre>\n" } ]
2017/04/10
[ "https://wordpress.stackexchange.com/questions/263116", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/84622/" ]
I'm writing a plugin that makes searches work only on a particular custom post type and it sorts the results according to the taxonomies the user selects in its backend configuration. The admin can select up to 4 taxonomies of the custom post type: each one is then a sort criterion that must be applied to the search results. The admin can then select the terms of each taxonomy that make the post appear before others in search results. The first selected taxonomy will be the most important sort criterion; the others will be applied in order. I need a query along the lines of: ``` SELECT * FROM wp_posts ORDER BY choosen_terms_of_taxonomy1, choosen_terms_of_axonomy2, ... ``` Now let's use some sample data. We have the `course` post type: ``` +----+------------+ | ID | post_title | +----+------------+ | 12 | Cooking | +----+------------+ | 13 | Surfing | +----+------------+ | 14 | Building | +----+------------+ | 15 | Hacking | +----+------------+ ``` Then we have two taxonomies for this custom post type. One is `place` and the other is `pricetag`. The `place` taxonomy has the following terms: ``` +---------+------------+ | term_id | slug | +---------+------------+ | 21 | downtown | +---------+------------+ | 22 | abroad | +---------+------------+ ``` The `pricetag` taxonomy has the following terms: ``` +---------+------------+ | term_id | slug | +---------+------------+ | 31 | expensive | +---------+------------+ | 32 | cheap | +---------+------------+ ``` And finally we have `wp_term_relationships` that links the courses to the taxonomies terms this way: ``` +-----------+------------+---------+ | object_id | post_title | term_id | +-----------+------------+---------+ | 12 | Cooking | 21 | (downtown) +-----------+------------+---------+ | 12 | Cooking | 32 | (cheap) +-----------+------------+---------+ | 13 | Surfing | 22 | (abroad) +-----------+------------+---------+ | 13 | Surfing | 31 | (expensive) +-----------+------------+---------+ | 14 | Building | 21 | (downtown) +-----------+------------+---------+ | 14 | Building | 31 | (expensive) +-----------+------------+---------+ | 15 | Hacking | 22 | (abroad) +-----------+------------+---------+ | 15 | Hacking | 32 | (cheap) +-----------+------------+---------+ ``` (Please note: I do know that's not the real structure of the `wp_term_relationships` table, but I wanted to simplify it a bit for the sake of this question.) Let's assume the admin has chosen `place` as the first taxonomy to use as a sort criterion and that he has chosen to show `downtown` courses first (the admin screen of the plugin is already done and it already provides the admin with the UI to make such choices). Then say the admin has chosen `pricetag` as second taxonomy to use as sort criterion and that he wants `expensive` courses to show up first. Note that being a second criterion, it has less sorting priority than the first, so the admin wants downtown courses first and then, in the group of downtown courses, expensive courses first. Now a frontend user searches for all courses on the website, and he should see these results in this exact order: 1. Building course (because it's downtown and expensive) 2. Cooking course (because it's downtown and cheap) 3. Surfing course (because it's abroad and expensive) 4. Hacking course (because it's abroad and cheap) My problem is writing the correct `JOIN` and `ORDER BY` clauses in the Wordpress query object. I've already hooked `posts_clauses` and here is the SQL query I'm generating: ``` SELECT SQL_CALC_FOUND_ROWS wp_posts.* FROM wp_posts LEFT JOIN (wp_term_relationships, wp_term_taxonomy, wp_terms) ON (wp_term_relationships.object_id = wp_posts.ID AND wp_term_taxonomy.term_taxonomy_id = wp_term_relationships.term_taxonomy_id AND wp_terms.term_id = wp_term_taxonomy.term_id) WHERE 1=1 AND (((wp_posts.post_title LIKE '%%') OR (wp_posts.post_excerpt LIKE '%%') OR (wp_posts.post_content LIKE '%%'))) AND wp_posts.post_type IN ('post', 'page', 'attachment', 'course') AND (wp_posts.post_status = 'publish' OR wp_posts.post_author = 1 AND wp_posts.post_status = 'private') AND wp_posts.post_type='course' ORDER BY (wp_terms.slug LIKE 'downtown' AND wp_term_taxonomy.taxonomy LIKE 'place') DESC, (wp_terms.slug LIKE 'abroad' AND wp_term_taxonomy.taxonomy LIKE 'place') DESC, (wp_terms.slug LIKE 'expensive' AND wp_term_taxonomy.taxonomy LIKE 'pricetag') DESC, (wp_terms.slug LIKE 'cheap' AND wp_term_taxonomy.taxonomy LIKE 'pricetag') DESC, wp_posts.post_title LIKE '%%' DESC, wp_posts.post_date DESC LIMIT 0, 300 ``` However this query has at least two problems: 1. it returns twice the results and I don't understand why, because LEFT JOIN should not produce a Cartesian product between the specified tables 2. the resulting sort order is unclear to me (it seems to be just `post_date DESC`), but it's clear it is NOT what I'm expecting. I've tried simplifying the query by removing Wordpress generated clauses: ``` SELECT wp_posts.* FROM wp_posts LEFT JOIN (wp_term_relationships, wp_term_taxonomy, wp_terms) ON (wp_term_relationships.object_id = wp_posts.ID AND wp_term_taxonomy.term_taxonomy_id = wp_term_relationships.term_taxonomy_id AND wp_terms.term_id = wp_term_taxonomy.term_id) WHERE 1=1 AND wp_posts.post_type='course' ORDER BY (wp_terms.slug LIKE 'downtown' AND wp_term_taxonomy.taxonomy LIKE 'place') DESC, (wp_terms.slug LIKE 'abroad' AND wp_term_taxonomy.taxonomy LIKE 'place') DESC, (wp_terms.slug LIKE 'expensive' AND wp_term_taxonomy.taxonomy LIKE 'pricetag') DESC, (wp_terms.slug LIKE 'cheap' AND wp_term_taxonomy.taxonomy LIKE 'pricetag') DESC ``` This one has exactly the same problems, but it is a bit easier to understand, and it returns the data as if no `ORDER BY` was there at all. Can you help me please?
Unfortunately, although `WP_Query` supports the `'tax_query'` arg, it does not support ordering based on post terms. So you will need to modify the query SQL, as you are doing now. However, you are constructing the `ORDER BY` clause incorrectly, and that is why it is ordering by `post_date`. What you need to do is use a `CASE` statement, like this: ``` CASE WHEN (wp_terms.slug LIKE 'downtown' AND wp_term_taxonomy.taxonomy LIKE 'place') THEN 1 WHEN (wp_terms.slug LIKE 'abroad' AND wp_term_taxonomy.taxonomy LIKE 'place') THEN 0 END ``` This will order based on the priority that you assign to each of the terms (`1`, `0`, etc., higher being higher priority, unless you use `ASC` instead of `DESC` for ordering). Because you want to order these two taxonomies independently, you will need to have two joins, and two case statements. (See below for example.) You also need to cause a `GROUP BY` on the post ID, to avoid duplicate results: ``` $clauses['groupby'] = 'wptests_posts.ID'; ``` So your final query would end up looking something like this (formatted for easier reading): ``` SELECT SQL_CALC_FOUND_ROWS wptests_posts.ID FROM wptests_posts LEFT JOIN ( wptests_term_relationships tr_place, wptests_term_taxonomy tt_place, wptests_terms t_place ) ON ( tr_place.object_id = wptests_posts.ID AND tt_place.term_taxonomy_id = tr_place.term_taxonomy_id AND tt_place.taxonomy = 'place' AND t_place.term_id = tt_place.term_id ) LEFT JOIN ( wptests_term_relationships tr_pricetag, wptests_term_taxonomy tt_pricetag, wptests_terms t_pricetag ) ON ( tr_pricetag.object_id = wptests_posts.ID AND tt_pricetag.term_taxonomy_id = tr_pricetag.term_taxonomy_id AND tt_pricetag.taxonomy = 'pricetag' AND t_pricetag.term_id = tt_pricetag.term_id ) WHERE 1=1 AND wptests_posts.post_type = 'course' AND (wptests_posts.post_status = 'publish') GROUP BY wptests_posts.ID ORDER BY (CASE WHEN (t_place.slug LIKE 'downtown') THEN 1 WHEN (t_place.slug LIKE 'abroad') THEN 0 END) DESC, (CASE WHEN (t_pricetag.slug LIKE 'expensive') THEN 1 WHEN (t_pricetag.slug LIKE 'cheap') THEN 0 END) DESC, wptests_posts.post_date DESC LIMIT 0, 10 ``` Here is an example PHPUnit test that demonstrates that this works, including example code for generating the joins and orderbys (it was used to generate the above query): ``` class My_Test extends WP_UnitTestCase { public function test() { // Create the post type. register_post_type( 'course' ); // Create the posts. $cooking_post_id = $this->factory->post->create( array( 'post_title' => 'Cooking', 'post_type' => 'course' ) ); $surfing_post_id = $this->factory->post->create( array( 'post_title' => 'Surfing', 'post_type' => 'course' ) ); $building_post_id = $this->factory->post->create( array( 'post_title' => 'Building', 'post_type' => 'course' ) ); $hacking_post_id = $this->factory->post->create( array( 'post_title' => 'Hacking', 'post_type' => 'course' ) ); // Create the taxonomies. register_taxonomy( 'place', 'course' ); register_taxonomy( 'pricetag', 'course' ); // Create the terms. $downtown_term_id = wp_create_term( 'downtown', 'place' ); $abroad_term_id = wp_create_term( 'abroad', 'place' ); $expensive_term_id = wp_create_term( 'expensive', 'pricetag' ); $cheap_term_id = wp_create_term( 'cheap', 'pricetag' ); // Give the terms to the correct posts. wp_add_object_terms( $cooking_post_id, $downtown_term_id, 'place' ); wp_add_object_terms( $cooking_post_id, $cheap_term_id, 'pricetag' ); wp_add_object_terms( $surfing_post_id, $abroad_term_id, 'place' ); wp_add_object_terms( $surfing_post_id, $expensive_term_id, 'pricetag' ); wp_add_object_terms( $building_post_id, $downtown_term_id, 'place' ); wp_add_object_terms( $building_post_id, $expensive_term_id, 'pricetag' ); wp_add_object_terms( $hacking_post_id, $abroad_term_id, 'place' ); wp_add_object_terms( $hacking_post_id, $cheap_term_id, 'pricetag' ); $query = new WP_Query( array( 'fields' => 'ids', 'post_type' => 'course', ) ); add_filter( 'posts_clauses', array( $this, 'filter_post_clauses' ) ); $results = $query->get_posts(); $this->assertSame( array( $building_post_id, $cooking_post_id, $surfing_post_id, $hacking_post_id, ) , $results ); } public function filter_post_clauses( $clauses ) { global $wpdb; $clauses['orderby'] = " (CASE WHEN (t_place.slug LIKE 'downtown') THEN 1 WHEN (t_place.slug LIKE 'abroad') THEN 0 END) DESC, (CASE WHEN (t_pricetag.slug LIKE 'expensive') THEN 1 WHEN (t_pricetag.slug LIKE 'cheap') THEN 0 END) DESC, " . $clauses['orderby']; foreach ( array( 'place', 'pricetag' ) as $taxonomy ) { // Instead of interpolating directly here, you should use $wpdb->prepare() for $taxonomy. $clauses['join'] .= " LEFT JOIN ( $wpdb->term_relationships tr_$taxonomy, $wpdb->term_taxonomy tt_$taxonomy, $wpdb->terms t_$taxonomy ) ON ( tr_$taxonomy.object_id = $wpdb->posts.ID AND tt_$taxonomy.term_taxonomy_id = tr_$taxonomy.term_taxonomy_id AND tt_$taxonomy.taxonomy = '$taxonomy' AND t_$taxonomy.term_id = tt_$taxonomy.term_id ) "; } $clauses['groupby'] = 'wptests_posts.ID'; return $clauses; } } ```
263,130
<p>mates, please can you help me with the following sql query attempt. This query controls whether a person has performed a form action for 24 hours.</p> <p>This is the SQL:</p> <pre><code>SELECT min(TIMESTAMPDIFF(DAY, `fecha_inscripcion`, now())) FROM `wp_cf7dbplugin_submits` WHERE `field_name`="cedula" and `field_value` = "1144093762" </code></pre> <p>This is the result:</p> <pre><code>min(TIMESTAMPDIFF(DAY, `fecha_inscripcion`, now())) 5 </code></pre> <p><a href="https://i.stack.imgur.com/NuzI1.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/NuzI1.jpg" alt="enter image description here"></a></p> <p>Now, in WordPress I did so</p> <pre><code>global $wpdb; $day = 'DAY'; $now = 'now()'; $fieldvalue = '1144093762'; $fieldname = 'cedula'; $post_count = $wpdb-&gt;get_var(" SELECT min(TIMESTAMPDIFF($day,$wpdb-&gt;cf7dbplugin_submits.fecha_inscripcion, $now)) FROM $wpdb-&gt;cf7dbplugin_submits WHERE field_name=$fieldname and field_value=$fieldvalue"); print_r($post_count); echo "Resultado"+$post_count; </code></pre> <p>But it returns me in 0, when it should be 5 in this case.</p> <p>Thank</p>
[ { "answer_id": 263133, "author": "Paul 'Sparrow Hawk' Biron", "author_id": 113496, "author_profile": "https://wordpress.stackexchange.com/users/113496", "pm_score": 2, "selected": false, "text": "<p>The main problem is how you're specifying the custom table name (e.g., <code>$wpdb-&gt;cf7dbplugin_submits</code>).</p>\n\n<p><code>$wpdb</code> only knows about the \"built-in\" tables when accessing a table name via <code>$wpdb-&gt;xxx</code>. To specify access a custom table name, use <code>{$wpdb-&gt;prefix}custom_table_name</code>.</p>\n\n<p>The other thing I notice is that, for security purposes, you should <strong>never</strong> use interpolated variables\nin an SQL statement passed to any of the <code>$wpdb</code> query methods. Instead, you should use <a href=\"https://developer.wordpress.org/reference/classes/wpdb/prepare/\" rel=\"nofollow noreferrer\">$wpdb->prepare()</a>.</p>\n\n<p>Putting these 2 things together results in:</p>\n\n<pre><code>$sql = $wpdb-&gt;prepare (\n \"SELECT min(TIMESTAMPDIFF($day,`fecha_inscripcion`, $now))\n FROM {$wpdb-&gt;prefix}cf7dbplugin_submits\n WHERE field_name=%s and field_value=%s\",\n $fieldname,\n $fieldvalue\n ) ;\n$post_count = $wpdb-&gt;get_var ($sql) ;\n</code></pre>\n" }, { "answer_id": 263152, "author": "iDuruiz", "author_id": 108342, "author_profile": "https://wordpress.stackexchange.com/users/108342", "pm_score": 0, "selected": false, "text": "<p>I attach the solution, thank a Paul 'Sparrow Hawk' Biron</p>\n\n<pre><code>global $wpdb;\n$day = 'DAY';\n$now = 'now()';\n$fieldname = \"cedula\";\n$fieldvalue = \"1144092\";\n\n// set the meta_key to the appropriate custom field meta key\n\n$sql = $wpdb-&gt;prepare (\n \"SELECT min(TIMESTAMPDIFF($day,fecha_inscripcion, $now))\n FROM {$wpdb-&gt;prefix}cf7dbplugin_submits\n WHERE field_name=%s and field_value=%s\",\n $fieldname,\n $fieldvalue\n );\n$post_count = $wpdb-&gt;get_var($sql) ;\n\necho \"&lt;p&gt;User count is {$post_count}&lt;/p&gt;\";\n</code></pre>\n" } ]
2017/04/10
[ "https://wordpress.stackexchange.com/questions/263130", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/108342/" ]
mates, please can you help me with the following sql query attempt. This query controls whether a person has performed a form action for 24 hours. This is the SQL: ``` SELECT min(TIMESTAMPDIFF(DAY, `fecha_inscripcion`, now())) FROM `wp_cf7dbplugin_submits` WHERE `field_name`="cedula" and `field_value` = "1144093762" ``` This is the result: ``` min(TIMESTAMPDIFF(DAY, `fecha_inscripcion`, now())) 5 ``` [![enter image description here](https://i.stack.imgur.com/NuzI1.jpg)](https://i.stack.imgur.com/NuzI1.jpg) Now, in WordPress I did so ``` global $wpdb; $day = 'DAY'; $now = 'now()'; $fieldvalue = '1144093762'; $fieldname = 'cedula'; $post_count = $wpdb->get_var(" SELECT min(TIMESTAMPDIFF($day,$wpdb->cf7dbplugin_submits.fecha_inscripcion, $now)) FROM $wpdb->cf7dbplugin_submits WHERE field_name=$fieldname and field_value=$fieldvalue"); print_r($post_count); echo "Resultado"+$post_count; ``` But it returns me in 0, when it should be 5 in this case. Thank
The main problem is how you're specifying the custom table name (e.g., `$wpdb->cf7dbplugin_submits`). `$wpdb` only knows about the "built-in" tables when accessing a table name via `$wpdb->xxx`. To specify access a custom table name, use `{$wpdb->prefix}custom_table_name`. The other thing I notice is that, for security purposes, you should **never** use interpolated variables in an SQL statement passed to any of the `$wpdb` query methods. Instead, you should use [$wpdb->prepare()](https://developer.wordpress.org/reference/classes/wpdb/prepare/). Putting these 2 things together results in: ``` $sql = $wpdb->prepare ( "SELECT min(TIMESTAMPDIFF($day,`fecha_inscripcion`, $now)) FROM {$wpdb->prefix}cf7dbplugin_submits WHERE field_name=%s and field_value=%s", $fieldname, $fieldvalue ) ; $post_count = $wpdb->get_var ($sql) ; ```
263,140
<p>I am developing a theme using bootstrap, but I am not able to display my posts as I would like.</p> <p>This is how I wanted it to be: <a href="https://i.stack.imgur.com/sEMTp.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/sEMTp.png" alt="enter image description here"></a></p> <p>But my best result was that with a eternal loop ....</p> <p><a href="https://i.stack.imgur.com/b00IQ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/b00IQ.png" alt="enter image description here"></a></p> <p>To differentiate the images in size I use different classes, this is the code I did ...</p> <pre><code>&lt;div id="blog"&gt; &lt;div class="container"&gt; &lt;div class="row"&gt; &lt;div class="col-md-12 text-center titulo-blog"&gt; &lt;h3 class="page-h3"&gt;&lt;?php the_title(); ?&gt;&lt;/h3&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <pre><code>&lt;?php while ( have_posts() ): the_post(); ?&gt; &lt;!-- ================================= BIG - SMALL ==================================== --&gt; &lt;?php if ( $i % 2 == 0 ): ?&gt; &lt;div class="container"&gt; &lt;div class="row"&gt; &lt;div class="col-md-4 col-sm-12 imp-blog"&gt; &lt;?php query_posts( array( 'category_name' =&gt; 'imp', ) ); ?&gt; &lt;?php if (have_posts()): the_post(); ?&gt; &lt;a href="&lt;?php the_permalink(); ?&gt;"&gt; &lt;div class="hoverzoom img-responsive"&gt; &lt;?php the_post_thumbnail(); ?&gt; &lt;div class="retina"&gt; &lt;div class="ret-text"&gt; &lt;p class="ret-title"&gt;&lt;?php the_title(); ?&gt;&lt;/p&gt; &lt;p class="ret-sub"&gt;&lt;?php the_subtitle(); ?&gt;&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/a&gt; &lt;?php endif; ?&gt; &lt;/div&gt; &lt;div class="col-md-8 col-sm-12 img-blog"&gt; &lt;?php query_posts( array( 'category_name' =&gt; 'img', ) ); ?&gt; &lt;?php if (have_posts()): the_post(); ?&gt; &lt;a href="&lt;?php the_permalink(); ?&gt;"&gt; &lt;div class="hoverzoom img-responsive"&gt; &lt;?php the_post_thumbnail(); ?&gt; &lt;div class="retina"&gt; &lt;div class="ret-text"&gt; &lt;p class="ret-title"&gt;&lt;?php the_title(); ?&gt;&lt;/p&gt; &lt;p class="ret-sub"&gt;&lt;?php the_subtitle(); ?&gt;&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/a&gt; &lt;?php endif; ?&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;?php $i ++; ?&gt; &lt;? else: ?&gt; &lt;!-- ======================================== SMALL - BIG =====================================--&gt; &lt;div class="container"&gt; &lt;div class="row"&gt; &lt;div class="col-md-8 col-sm-12 img-blog "&gt; &lt;?php query_posts( array( 'category_name' =&gt; 'img', ) ); ?&gt; &lt;?php if (have_posts()): the_post(); ?&gt; &lt;a href="&lt;?php the_permalink(); ?&gt;"&gt; &lt;div class="hoverzoom img-responsive"&gt; &lt;?php the_post_thumbnail(); ?&gt; &lt;div class="retina"&gt; &lt;div class="ret-text"&gt; &lt;p class="ret-title"&gt;&lt;?php the_title(); ?&gt;&lt;/p&gt; &lt;p class="ret-sub"&gt;&lt;?php the_subtitle(); ?&gt;&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/a&gt; &lt;?php endif; ?&gt; &lt;/div&gt; &lt;div class="col-md-4 col-sm-12 imp-blog"&gt; &lt;?php query_posts( array( 'category_name' =&gt; 'imp', ) ); ?&gt; &lt;?php if (have_posts()): the_post(); ?&gt; &lt;a href="&lt;?php the_permalink(); ?&gt;"&gt; &lt;div class="hoverzoom img-responsive"&gt; &lt;?php the_post_thumbnail(); ?&gt; &lt;div class="retina"&gt; &lt;div class="ret-text"&gt; &lt;p class="ret-title"&gt;&lt;?php the_title(); ?&gt;&lt;/p&gt; &lt;p class="ret-sub"&gt;&lt;?php the_subtitle(); ?&gt;&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/a&gt; &lt;?php endif; ?&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;?php $i ++; ?&gt; &lt;?php endif; ?&gt; &lt;?php endwhile; ?&gt; </code></pre> <p>Please help me i have no idea how to solve this</p>
[ { "answer_id": 263144, "author": "dev", "author_id": 117342, "author_profile": "https://wordpress.stackexchange.com/users/117342", "pm_score": -1, "selected": false, "text": "<p>I will too suggest you to use Masonry javascript \n<a href=\"http://masonry.desandro.com/\" rel=\"nofollow noreferrer\">Here is the link to masonry project</a></p>\n\n<pre><code>&lt;div class=\"grid\" data-masonry='{ \"itemSelector\": \".grid-item\", \"columnWidth\": 200 }'&gt;\n</code></pre>\n\n<p>\n \n</p>\n\n<p>Run the <code>&lt;div class=\"grid-item\"&gt;&lt;/div&gt;</code> inside the loop</p>\n" }, { "answer_id": 263146, "author": "Industrial Themes", "author_id": 274, "author_profile": "https://wordpress.stackexchange.com/users/274", "pm_score": 2, "selected": true, "text": "<p>You don't need any plugins to accomplish this. In fact, this is not really a use case for a masonry layout since the heights of the images are all the same. Masonry.js is for varying post heights. You just need a counter to keep track of alternating rows, and each alternating row put the small column first instead of second. Set a counter to 0 like so:</p>\n\n<pre><code>$i = 0;\n</code></pre>\n\n<p>Then after each post increment it by one like so:</p>\n\n<pre><code>$i++;\n</code></pre>\n\n<p>Then you need to use mod to check if it's evenly divisible by 2 (alternate row) or not. If it is, put the small column first instead of second. Check like this:</p>\n\n<pre><code>if($i % 2 == 0) { \n\n //...this is an alternate row...\n //...put your markup here...\n\n} else {\n\n //...this is a regular row...\n //...put your markup here...\n}\n</code></pre>\n\n<p>From the looks of your markup, you might need to modify it so it's all within one loop in order for this to work.</p>\n" } ]
2017/04/10
[ "https://wordpress.stackexchange.com/questions/263140", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/117341/" ]
I am developing a theme using bootstrap, but I am not able to display my posts as I would like. This is how I wanted it to be: [![enter image description here](https://i.stack.imgur.com/sEMTp.png)](https://i.stack.imgur.com/sEMTp.png) But my best result was that with a eternal loop .... [![enter image description here](https://i.stack.imgur.com/b00IQ.png)](https://i.stack.imgur.com/b00IQ.png) To differentiate the images in size I use different classes, this is the code I did ... ``` <div id="blog"> <div class="container"> <div class="row"> <div class="col-md-12 text-center titulo-blog"> <h3 class="page-h3"><?php the_title(); ?></h3> </div> </div> </div> ``` ``` <?php while ( have_posts() ): the_post(); ?> <!-- ================================= BIG - SMALL ==================================== --> <?php if ( $i % 2 == 0 ): ?> <div class="container"> <div class="row"> <div class="col-md-4 col-sm-12 imp-blog"> <?php query_posts( array( 'category_name' => 'imp', ) ); ?> <?php if (have_posts()): the_post(); ?> <a href="<?php the_permalink(); ?>"> <div class="hoverzoom img-responsive"> <?php the_post_thumbnail(); ?> <div class="retina"> <div class="ret-text"> <p class="ret-title"><?php the_title(); ?></p> <p class="ret-sub"><?php the_subtitle(); ?></p> </div> </div> </div> </a> <?php endif; ?> </div> <div class="col-md-8 col-sm-12 img-blog"> <?php query_posts( array( 'category_name' => 'img', ) ); ?> <?php if (have_posts()): the_post(); ?> <a href="<?php the_permalink(); ?>"> <div class="hoverzoom img-responsive"> <?php the_post_thumbnail(); ?> <div class="retina"> <div class="ret-text"> <p class="ret-title"><?php the_title(); ?></p> <p class="ret-sub"><?php the_subtitle(); ?></p> </div> </div> </div> </a> <?php endif; ?> </div> </div> </div> <?php $i ++; ?> <? else: ?> <!-- ======================================== SMALL - BIG =====================================--> <div class="container"> <div class="row"> <div class="col-md-8 col-sm-12 img-blog "> <?php query_posts( array( 'category_name' => 'img', ) ); ?> <?php if (have_posts()): the_post(); ?> <a href="<?php the_permalink(); ?>"> <div class="hoverzoom img-responsive"> <?php the_post_thumbnail(); ?> <div class="retina"> <div class="ret-text"> <p class="ret-title"><?php the_title(); ?></p> <p class="ret-sub"><?php the_subtitle(); ?></p> </div> </div> </div> </a> <?php endif; ?> </div> <div class="col-md-4 col-sm-12 imp-blog"> <?php query_posts( array( 'category_name' => 'imp', ) ); ?> <?php if (have_posts()): the_post(); ?> <a href="<?php the_permalink(); ?>"> <div class="hoverzoom img-responsive"> <?php the_post_thumbnail(); ?> <div class="retina"> <div class="ret-text"> <p class="ret-title"><?php the_title(); ?></p> <p class="ret-sub"><?php the_subtitle(); ?></p> </div> </div> </div> </a> <?php endif; ?> </div> </div> </div> <?php $i ++; ?> <?php endif; ?> <?php endwhile; ?> ``` Please help me i have no idea how to solve this
You don't need any plugins to accomplish this. In fact, this is not really a use case for a masonry layout since the heights of the images are all the same. Masonry.js is for varying post heights. You just need a counter to keep track of alternating rows, and each alternating row put the small column first instead of second. Set a counter to 0 like so: ``` $i = 0; ``` Then after each post increment it by one like so: ``` $i++; ``` Then you need to use mod to check if it's evenly divisible by 2 (alternate row) or not. If it is, put the small column first instead of second. Check like this: ``` if($i % 2 == 0) { //...this is an alternate row... //...put your markup here... } else { //...this is a regular row... //...put your markup here... } ``` From the looks of your markup, you might need to modify it so it's all within one loop in order for this to work.
263,149
<p>I am using the SimpleLightbox plugin (<a href="https://wordpress.org/plugins/simplelightbox/" rel="nofollow noreferrer">https://wordpress.org/plugins/simplelightbox/</a>) on a test site: <a href="http://joshrodg.com/theiveys/about" rel="nofollow noreferrer">http://joshrodg.com/theiveys/about</a>.</p> <p>If you click on one of the pictures, SimpleLightbox opens a larger version in a Lightbox. You'll notice that to close the Lightbox you need to click the white "X" in the upper-right hand corner, but that is directly over the page menu (where the three lines are).</p> <p>So, I added some code that would remove the navigation bar from the page when the Lightbox loads, which looks like:</p> <pre><code>$(document).ready(function(){ $(".simplelightbox").click(function(){ $(".burger").hide(); }) }); </code></pre> <p>This works because the code gets executed when someone clicks on one of the Lightbox images with the class "simplelightbox"</p> <p>The problem I'm having is making the nav bar re-appear.</p> <p>I have tried:</p> <pre><code>$(document).ready(function(){ $(".simple-lightbox").click(function(){ $(".burger").show(); }) }); </code></pre> <p>but that doesn't work - the nav bar doesn't re-appear. That one uses class .simple-lightbox (because that is the main class when the Lightbox is showing) - there is also sl-overlay, sl-wrapper, sl-image, and sl-close but none of those worked either.</p> <p>Anyone have any ideas?</p> <p>Thanks,<br /> Josh</p>
[ { "answer_id": 263144, "author": "dev", "author_id": 117342, "author_profile": "https://wordpress.stackexchange.com/users/117342", "pm_score": -1, "selected": false, "text": "<p>I will too suggest you to use Masonry javascript \n<a href=\"http://masonry.desandro.com/\" rel=\"nofollow noreferrer\">Here is the link to masonry project</a></p>\n\n<pre><code>&lt;div class=\"grid\" data-masonry='{ \"itemSelector\": \".grid-item\", \"columnWidth\": 200 }'&gt;\n</code></pre>\n\n<p>\n \n</p>\n\n<p>Run the <code>&lt;div class=\"grid-item\"&gt;&lt;/div&gt;</code> inside the loop</p>\n" }, { "answer_id": 263146, "author": "Industrial Themes", "author_id": 274, "author_profile": "https://wordpress.stackexchange.com/users/274", "pm_score": 2, "selected": true, "text": "<p>You don't need any plugins to accomplish this. In fact, this is not really a use case for a masonry layout since the heights of the images are all the same. Masonry.js is for varying post heights. You just need a counter to keep track of alternating rows, and each alternating row put the small column first instead of second. Set a counter to 0 like so:</p>\n\n<pre><code>$i = 0;\n</code></pre>\n\n<p>Then after each post increment it by one like so:</p>\n\n<pre><code>$i++;\n</code></pre>\n\n<p>Then you need to use mod to check if it's evenly divisible by 2 (alternate row) or not. If it is, put the small column first instead of second. Check like this:</p>\n\n<pre><code>if($i % 2 == 0) { \n\n //...this is an alternate row...\n //...put your markup here...\n\n} else {\n\n //...this is a regular row...\n //...put your markup here...\n}\n</code></pre>\n\n<p>From the looks of your markup, you might need to modify it so it's all within one loop in order for this to work.</p>\n" } ]
2017/04/10
[ "https://wordpress.stackexchange.com/questions/263149", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/9820/" ]
I am using the SimpleLightbox plugin (<https://wordpress.org/plugins/simplelightbox/>) on a test site: <http://joshrodg.com/theiveys/about>. If you click on one of the pictures, SimpleLightbox opens a larger version in a Lightbox. You'll notice that to close the Lightbox you need to click the white "X" in the upper-right hand corner, but that is directly over the page menu (where the three lines are). So, I added some code that would remove the navigation bar from the page when the Lightbox loads, which looks like: ``` $(document).ready(function(){ $(".simplelightbox").click(function(){ $(".burger").hide(); }) }); ``` This works because the code gets executed when someone clicks on one of the Lightbox images with the class "simplelightbox" The problem I'm having is making the nav bar re-appear. I have tried: ``` $(document).ready(function(){ $(".simple-lightbox").click(function(){ $(".burger").show(); }) }); ``` but that doesn't work - the nav bar doesn't re-appear. That one uses class .simple-lightbox (because that is the main class when the Lightbox is showing) - there is also sl-overlay, sl-wrapper, sl-image, and sl-close but none of those worked either. Anyone have any ideas? Thanks, Josh
You don't need any plugins to accomplish this. In fact, this is not really a use case for a masonry layout since the heights of the images are all the same. Masonry.js is for varying post heights. You just need a counter to keep track of alternating rows, and each alternating row put the small column first instead of second. Set a counter to 0 like so: ``` $i = 0; ``` Then after each post increment it by one like so: ``` $i++; ``` Then you need to use mod to check if it's evenly divisible by 2 (alternate row) or not. If it is, put the small column first instead of second. Check like this: ``` if($i % 2 == 0) { //...this is an alternate row... //...put your markup here... } else { //...this is a regular row... //...put your markup here... } ``` From the looks of your markup, you might need to modify it so it's all within one loop in order for this to work.
263,163
<p>I am integrating an API into my Wordpress website and I am having trouble understanding the instructions on Github as to how to install the API. I am comfortable with using Wordpress themes and plugins but I am new to coding + API.</p> <p>I have downloaded the library from Github and extracted it on my computer. Where should I be saving this folder in my Wordpress directory, ie. root, plugins, themes or elsewhere?</p> <p>It has asked for me to "Extract the library into the php include path." Is this the same as the extraction I have done above?</p> <p>Then it requires me to integrate this line of code:</p> <pre><code>require_once(dirname(__FILE__) . 'path_to ChargeBee.php'); </code></pre> <p>and I have no idea where I should do this. Do I need to create a separate .php file for this? I saw a video online where I could insert this in .htaccess. Is this correct? Or should I be placing it in one of the files of the library?</p> <p>I assume "path_to Chargebee.php" above needs to be changed to the path where I save the library in my Wordpress directory?</p> <p>The linkt to where the above information is is: <a href="https://github.com/chargebee/chargebee-php" rel="nofollow noreferrer">https://github.com/chargebee/chargebee-php</a>.</p> <p>Any help would be appreciated to this newbie.:) Thanks in advance.</p> <p>P/S: I thought I should add this. I spent the entire day yesterday looking at youtube API videos but none of them explained the basics for a dummy like me. I have tried searching Google but again I couldn't find anything answering my questions. I hope someone can help....pretty pleeeaasssee.....</p>
[ { "answer_id": 263175, "author": "rudtek", "author_id": 77767, "author_profile": "https://wordpress.stackexchange.com/users/77767", "pm_score": 1, "selected": false, "text": "<p>this line IS your php inlcude path:</p>\n\n<pre><code>require_once(dirname(__FILE__) . 'path_to ChargeBee.php');\n</code></pre>\n\n<p>you need to change it to something specific to your coding. ie: are you putting this into a theme or a plugin? ( would suggest a plugin)</p>\n\n<p>If that were the case you would use something like this:</p>\n\n<p>require_once( CHARGEBEEPLUGIN_DIR . '/lib/chargebee.php' );</p>\n\n<p>this would include the file that it finds at wp-content/plugins/chargebeeapi/lib/chargebee.php</p>\n\n<p>the chargbee.php is what you're getting from github.</p>\n\n<p>Do you have experience with api's though? It's not as simple as just putting the github folder on your system and you're off to the races unfortunately. </p>\n\n<p>The link you referenced is the library to for the chargbee api. You now need to create your side of the tool to utilize the library. I suggested a plugin as that is how I do it. You're not going to just put it in the plugin folder though: you need to create a folder within the plugin directory with your new plugin folders. </p>\n\n<p>for instance:\nIn the wp-content/plugins folder you create a new folder, \"chargebeeapi\"</p>\n\n<p>then in that folder you add your library (the lib folder you downloaded from gitub)</p>\n\n<p>wp-content/plugins/chargebeeapi/lib</p>\n\n<p>now in the chargbeeapi folder you create your main plugin php file that will reference the library by using the above include path.</p>\n\n<p>In this php file you'll need to create form and submission button (this will vary depending upon how you need to interact with chargbee.) As well as a response container to get the response back after your request/push to their system. Lastly you'll need to tell wordpress this is a plugin and identify where the form / interaction will occur in wordpress.</p>\n" }, { "answer_id": 263205, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 0, "selected": false, "text": "<p>An API is just a piece of code, that does nothing by itself. First thing to do is to figure out what is it that you want to do with that API, then write a plugin that wraps the API code and exposes API in the \"wordpress way\" via widgets, shortcodes, or in case it is a self contained JS file, enqueues it and set whatever are the required parameters (and add whatever admin is needed).</p>\n\n<p>Where do you put the \"API\" code itself (the proper term in this case is more likely SDK) is of not much importance, it just obviously have to be part of the plugin, and to keep things clean you will probably want to keep it in its own directory.</p>\n\n<p>This goes also for integrating it in a theme.</p>\n" } ]
2017/04/10
[ "https://wordpress.stackexchange.com/questions/263163", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/117354/" ]
I am integrating an API into my Wordpress website and I am having trouble understanding the instructions on Github as to how to install the API. I am comfortable with using Wordpress themes and plugins but I am new to coding + API. I have downloaded the library from Github and extracted it on my computer. Where should I be saving this folder in my Wordpress directory, ie. root, plugins, themes or elsewhere? It has asked for me to "Extract the library into the php include path." Is this the same as the extraction I have done above? Then it requires me to integrate this line of code: ``` require_once(dirname(__FILE__) . 'path_to ChargeBee.php'); ``` and I have no idea where I should do this. Do I need to create a separate .php file for this? I saw a video online where I could insert this in .htaccess. Is this correct? Or should I be placing it in one of the files of the library? I assume "path\_to Chargebee.php" above needs to be changed to the path where I save the library in my Wordpress directory? The linkt to where the above information is is: <https://github.com/chargebee/chargebee-php>. Any help would be appreciated to this newbie.:) Thanks in advance. P/S: I thought I should add this. I spent the entire day yesterday looking at youtube API videos but none of them explained the basics for a dummy like me. I have tried searching Google but again I couldn't find anything answering my questions. I hope someone can help....pretty pleeeaasssee.....
this line IS your php inlcude path: ``` require_once(dirname(__FILE__) . 'path_to ChargeBee.php'); ``` you need to change it to something specific to your coding. ie: are you putting this into a theme or a plugin? ( would suggest a plugin) If that were the case you would use something like this: require\_once( CHARGEBEEPLUGIN\_DIR . '/lib/chargebee.php' ); this would include the file that it finds at wp-content/plugins/chargebeeapi/lib/chargebee.php the chargbee.php is what you're getting from github. Do you have experience with api's though? It's not as simple as just putting the github folder on your system and you're off to the races unfortunately. The link you referenced is the library to for the chargbee api. You now need to create your side of the tool to utilize the library. I suggested a plugin as that is how I do it. You're not going to just put it in the plugin folder though: you need to create a folder within the plugin directory with your new plugin folders. for instance: In the wp-content/plugins folder you create a new folder, "chargebeeapi" then in that folder you add your library (the lib folder you downloaded from gitub) wp-content/plugins/chargebeeapi/lib now in the chargbeeapi folder you create your main plugin php file that will reference the library by using the above include path. In this php file you'll need to create form and submission button (this will vary depending upon how you need to interact with chargbee.) As well as a response container to get the response back after your request/push to their system. Lastly you'll need to tell wordpress this is a plugin and identify where the form / interaction will occur in wordpress.
263,176
<p>I have this weird problem. Trying to enqueue a CSS file on an existing <code>functions.php</code> file and nothing seems to work. This is the pertinent part of the functions file, made by someone else based on TwentySixteen theme :</p> <pre><code>function twentysixteen_scripts() { // Add custom fonts, used in the main stylesheet. wp_enqueue_style( 'twentysixteen-fonts', twentysixteen_fonts_url(), array(), null ); // Add Genericons, used in the main stylesheet. wp_enqueue_style( 'genericons', get_template_directory_uri() . '/genericons/genericons.css', array(), '3.4.1' ); wp_enqueue_style( 'bootstrap', get_template_directory_uri() . '/css/bootstrap.css', array(), '3.4.1' ); wp_enqueue_style( 'theme-owl', get_template_directory_uri() . '/css/owl.carousel.css', array(), '3.4.1' ); wp_enqueue_style( 'theme-owl-min', get_template_directory_uri() . '/css/owl.theme.css', array(), '3.4.1' ); // Theme stylesheet. wp_enqueue_style( 'twentysixteen-style', get_stylesheet_uri() ); if (! is_front_page() || is_single()) {wp_enqueue_style( 'blog-styles', get_template_directory_uri() . 'full-style.css', array( 'twentysixteen-style' ), '20170410' );} // Load the Internet Explorer specific stylesheet. wp_enqueue_style( 'twentysixteen-ie', get_template_directory_uri() . '/css/ie.css', array( 'twentysixteen-style' ), '20150930' ); /* 09.02.2017 */ wp_enqueue_style( 'jquery-ui', get_template_directory_uri() . '/css/jquery-ui.css', array( 'twentysixteen-style' ), '20150930' ); /* 09.02.2017 */ wp_style_add_data( 'twentysixteen-ie', 'conditional', 'lt IE 10' ); // Load the Internet Explorer 8 specific stylesheet. wp_enqueue_style( 'twentysixteen-ie8', get_template_directory_uri() . '/css/ie8.css', array( 'twentysixteen-style' ), '20151230' ); wp_style_add_data( 'twentysixteen-ie8', 'conditional', 'lt IE 9' ); // Load the Internet Explorer 7 specific stylesheet. wp_enqueue_style( 'twentysixteen-ie7', get_template_directory_uri() . '/css/ie7.css', array( 'twentysixteen-style' ), '20150930' ); wp_style_add_data( 'twentysixteen-ie7', 'conditional', 'lt IE 8' ); // Load the html5 shiv. wp_enqueue_script( 'twentysixteen-html5', get_template_directory_uri() . '/js/html5.js', array(), '3.7.3' ); wp_script_add_data( 'twentysixteen-html5', 'conditional', 'lt IE 9' ); wp_enqueue_script( 'twentysixteen-skip-link-focus-fix', get_template_directory_uri() . '/js/skip-link-focus-fix.js', array(), '20151112', true ); /* 09.02.2017 start */ wp_enqueue_script( 'jquery-ui', get_template_directory_uri() . '/js/jquery-ui.js', array(), '20151112', true ); //wp_enqueue_script( 'taskCompRegress', get_template_directory_uri() . '/js/taskCompRegress.js', array(), '20151112', true ); if(is_single(556) || is_single(274)){ wp_enqueue_script( 'UXSalary2014', get_template_directory_uri() . '/js/UXSalary2014.js', array(), '20151112', true ); } if(is_single(6440)){ wp_enqueue_script( 'UXSalary2016', get_template_directory_uri() . '/js/UXSalary2016.js', array(), '20170314', true ); } if(is_single(3656)){ wp_enqueue_script( 'UXSalary.js', get_template_directory_uri() . '/js/UXSalary.js', array(), '20110823', true ); } if(is_single(204)){ wp_enqueue_script( 'taskCompRegress.js', get_template_directory_uri() . '/js/taskCompRegress.js', array(), '20110321', true ); } if(is_single(274)){ //wp_enqueue_script( 'UXSalary', get_template_directory_uri() . '/js/UXSalary.js', array(), '20151112', true ); wp_enqueue_script( 'npsSUSMeanRegress', get_template_directory_uri() . '/js/npsSUSMeanRegress.js', array(), '20151112', true ); } if(is_single(458)){ wp_enqueue_script( 'UXQuiz', get_template_directory_uri() . '/js/UXQuiz.js', array(), '20131112', true ); } //wp_enqueue_script( 'UXQuiz', get_template_directory_uri() . '/js/UXQuiz.js', array(), '20151112', true ); if(is_single(3695)){ wp_enqueue_script( 'bs', get_template_directory_uri() . '/js/bs.js', array(), '20151112', true ); } if(is_single(3703)){ wp_enqueue_script( 'uiProbs', get_template_directory_uri() . '/js/uiProbs.js', array(), '20151112', true ); } wp_enqueue_script( 'ciquiz', get_template_directory_uri() . '/js/ciquiz.js', array(), '20151112', true ); wp_enqueue_script( 'geoMean', get_template_directory_uri() . '/js/geoMean.js', array(), '20151112', true ); wp_enqueue_script( 'jquery-2.2.4.min', get_template_directory_uri() . '/js/jquery-2.2.4.min.js', array(), '20151112', true ); wp_enqueue_script( 'jquery-3.1.0.min.js', get_template_directory_uri() . '/js/jquery-3.1.0.min.js', array(), '20151112', true ); wp_enqueue_script( 'custSampSize.js', get_template_directory_uri() . '/js/custSampSize.js', array(), '20151112', true ); wp_enqueue_script( 'actb.js', get_template_directory_uri() . '/js/actb.js', array(), '20151112', true ); // wp_enqueue_script( 'color-scheme-control', get_template_directory_uri() . '/js/color-scheme-control.js', array(), '20151112', true ); //wp_enqueue_script( 'compSUSRegress', get_template_directory_uri() . '/js/compSUSRegress.js', array(), '20151112', true ); //wp_enqueue_script( 'customize-preview', get_template_directory_uri() . '/js/customize-preview.js', array(), '20151112', true ); wp_enqueue_script( 'html5', get_template_directory_uri() . '/js/html5.js', array(), '20151112', true ); //wp_enqueue_script( 'keyboard-image-navigation', get_template_directory_uri() . '/js/keyboard-image-navigation.js', array(), '20151112', true ); wp_enqueue_script( 'klm', get_template_directory_uri() . '/js/klm.js', array(), '20151112', true ); wp_enqueue_script( 'myscript', get_template_directory_uri() . '/js/myscript.js', array(), '20151112', true ); wp_enqueue_script( 'myselect2', get_template_directory_uri() . '/js/myselect2.js', array(), '20151112', true ); //wp_enqueue_script( 'npsMeanRegress', get_template_directory_uri() . '/js/npsMeanRegress.js', array(), '20151112', true ); if(is_single(230)) { wp_enqueue_script( 'npsMeanRegress', get_template_directory_uri() . '/js/npsMeanRegress.js', array(), '20151112', true ); wp_enqueue_script( 'npsSUSMeanRegress', get_template_directory_uri() . '/js/npsSUSMeanRegress.js', array(), '20151112', true ); } wp_enqueue_script( 'organic', get_template_directory_uri() . '/js/organic.js', array(), '20151112', true ); wp_enqueue_script( 'skip-link-focus-fix', get_template_directory_uri() . '/js/skip-link-focus-fix.js', array(), '20151112', true ); wp_enqueue_script( 'jquery-1.10.2', get_template_directory_uri() . '/js/jquery-1.10.2.js', array(), '20151112', true ); /* 09.02.2017 end */ wp_enqueue_style( 'custom-style', get_template_directory_uri() . '/css/custom.css', array(), false, '' ); if ( is_singular() &amp;&amp; comments_open() &amp;&amp; get_option( 'thread_comments' ) ) { wp_enqueue_script( 'comment-reply' ); } if ( is_singular() &amp;&amp; wp_attachment_is_image() ) { wp_enqueue_script( 'twentysixteen-keyboard-image-navigation', get_template_directory_uri() . '/js/keyboard-image-navigation.js', array( 'jquery' ), '20151104' ); } wp_enqueue_script( 'twentysixteen-script', get_template_directory_uri() . '/js/functions.js', array( 'jquery' ), '20151204', true ); wp_enqueue_script( 'twentysixteen-jquery', get_template_directory_uri() . '/js/jquery-1.12.0.min.js', array( 'jquery' ), '', true ); wp_enqueue_script( 'twentysixteen-boot', get_template_directory_uri() . '/js/bootstrap.js', array( 'jquery' ), '', true ); wp_enqueue_script( 'twentysixteen-owl', get_template_directory_uri() . '/js/owl.carousel.js', array( 'jquery' ), '', true ); wp_enqueue_script( 'twentysixteen-main', get_template_directory_uri() . '/js/main.js', array( 'jquery' ), '', true ); wp_localize_script( 'twentysixteen-script', 'screenReaderText', array( 'expand' =&gt; __( 'expand child menu', 'twentysixteen' ), 'collapse' =&gt; __( 'collapse child menu', 'twentysixteen' ), ) ); } add_action( 'wp_enqueue_scripts', 'twentysixteen_scripts' ); </code></pre> <p>All of this works. Now, I want to enqueue yet another file. Additionally, I wanted to make it load conditionally, anywhere but front page, but at this point I'd be very happy by making it load at all!</p> <p>First, I tried the conditional version <code>(if ! is_front_page...)</code> but didn't work (I made it work on <code>header.php</code>, but I want it to load after everything else). Thinking there might be an error in my code, I tried enqueuing the file just to see it loads.... and nothing. Tried everything I could think of... and nothing. </p> <p>So, as a last resource, I tried replacing one of the files that actually loads, <code>custom-style --&gt; css/custom.css</code> and as weird as it sounds, it does nothing. Furthermore, if I check the source, even so <code>css/custom.css</code> shouldn't be there, it still is. <strong>Just in case: I don't have any cache and I can see any other changes that are not related to this file.</strong></p> <p>Finally, I tried to create a different function to enqueue files and nothing, it doesn't work at all.</p> <p>This is the code I tried to add with no luck:</p> <pre><code>{wp_enqueue_style( 'blog-styles', get_template_directory_uri() . 'full-style.css', array( 'twentysixteen-style' ), '20170410' );} </code></pre> <p>Finally, based on <a href="https://wordpress.stackexchange.com/questions/124354/why-wp-register-style-is-important-while-im-using-a-complete-wp-enqueue-style/124381#124381">this answer</a> I tried this, which would also help with the conditional part:</p> <pre><code>add_action('init', 'my_register_styles'); function my_register_styles() { wp_register_style( 'style1', get_template_directory_uri() . '/style.css' ); wp_register_style( 'style2', get_template_directory_uri() . '/full-style.css' ); } add_action( 'wp_enqueue_scripts', 'my_enqueue_styles' ); function my_enqueue_styles() { if ( is_front_page() ) { wp_enqueue_style( 'style1' ); } else { wp_enqueue_style( 'style2' ); } } </code></pre> <p>but as you probably imagine by now.... it didn't work!</p> <h1>Question(s)</h1> <ul> <li>What is causing this? What am I doing wrong?</li> <li>Is there a way to make the stylesheet load on header.php AFTER the enqueued scripts?</li> </ul>
[ { "answer_id": 263175, "author": "rudtek", "author_id": 77767, "author_profile": "https://wordpress.stackexchange.com/users/77767", "pm_score": 1, "selected": false, "text": "<p>this line IS your php inlcude path:</p>\n\n<pre><code>require_once(dirname(__FILE__) . 'path_to ChargeBee.php');\n</code></pre>\n\n<p>you need to change it to something specific to your coding. ie: are you putting this into a theme or a plugin? ( would suggest a plugin)</p>\n\n<p>If that were the case you would use something like this:</p>\n\n<p>require_once( CHARGEBEEPLUGIN_DIR . '/lib/chargebee.php' );</p>\n\n<p>this would include the file that it finds at wp-content/plugins/chargebeeapi/lib/chargebee.php</p>\n\n<p>the chargbee.php is what you're getting from github.</p>\n\n<p>Do you have experience with api's though? It's not as simple as just putting the github folder on your system and you're off to the races unfortunately. </p>\n\n<p>The link you referenced is the library to for the chargbee api. You now need to create your side of the tool to utilize the library. I suggested a plugin as that is how I do it. You're not going to just put it in the plugin folder though: you need to create a folder within the plugin directory with your new plugin folders. </p>\n\n<p>for instance:\nIn the wp-content/plugins folder you create a new folder, \"chargebeeapi\"</p>\n\n<p>then in that folder you add your library (the lib folder you downloaded from gitub)</p>\n\n<p>wp-content/plugins/chargebeeapi/lib</p>\n\n<p>now in the chargbeeapi folder you create your main plugin php file that will reference the library by using the above include path.</p>\n\n<p>In this php file you'll need to create form and submission button (this will vary depending upon how you need to interact with chargbee.) As well as a response container to get the response back after your request/push to their system. Lastly you'll need to tell wordpress this is a plugin and identify where the form / interaction will occur in wordpress.</p>\n" }, { "answer_id": 263205, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 0, "selected": false, "text": "<p>An API is just a piece of code, that does nothing by itself. First thing to do is to figure out what is it that you want to do with that API, then write a plugin that wraps the API code and exposes API in the \"wordpress way\" via widgets, shortcodes, or in case it is a self contained JS file, enqueues it and set whatever are the required parameters (and add whatever admin is needed).</p>\n\n<p>Where do you put the \"API\" code itself (the proper term in this case is more likely SDK) is of not much importance, it just obviously have to be part of the plugin, and to keep things clean you will probably want to keep it in its own directory.</p>\n\n<p>This goes also for integrating it in a theme.</p>\n" } ]
2017/04/10
[ "https://wordpress.stackexchange.com/questions/263176", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/95156/" ]
I have this weird problem. Trying to enqueue a CSS file on an existing `functions.php` file and nothing seems to work. This is the pertinent part of the functions file, made by someone else based on TwentySixteen theme : ``` function twentysixteen_scripts() { // Add custom fonts, used in the main stylesheet. wp_enqueue_style( 'twentysixteen-fonts', twentysixteen_fonts_url(), array(), null ); // Add Genericons, used in the main stylesheet. wp_enqueue_style( 'genericons', get_template_directory_uri() . '/genericons/genericons.css', array(), '3.4.1' ); wp_enqueue_style( 'bootstrap', get_template_directory_uri() . '/css/bootstrap.css', array(), '3.4.1' ); wp_enqueue_style( 'theme-owl', get_template_directory_uri() . '/css/owl.carousel.css', array(), '3.4.1' ); wp_enqueue_style( 'theme-owl-min', get_template_directory_uri() . '/css/owl.theme.css', array(), '3.4.1' ); // Theme stylesheet. wp_enqueue_style( 'twentysixteen-style', get_stylesheet_uri() ); if (! is_front_page() || is_single()) {wp_enqueue_style( 'blog-styles', get_template_directory_uri() . 'full-style.css', array( 'twentysixteen-style' ), '20170410' );} // Load the Internet Explorer specific stylesheet. wp_enqueue_style( 'twentysixteen-ie', get_template_directory_uri() . '/css/ie.css', array( 'twentysixteen-style' ), '20150930' ); /* 09.02.2017 */ wp_enqueue_style( 'jquery-ui', get_template_directory_uri() . '/css/jquery-ui.css', array( 'twentysixteen-style' ), '20150930' ); /* 09.02.2017 */ wp_style_add_data( 'twentysixteen-ie', 'conditional', 'lt IE 10' ); // Load the Internet Explorer 8 specific stylesheet. wp_enqueue_style( 'twentysixteen-ie8', get_template_directory_uri() . '/css/ie8.css', array( 'twentysixteen-style' ), '20151230' ); wp_style_add_data( 'twentysixteen-ie8', 'conditional', 'lt IE 9' ); // Load the Internet Explorer 7 specific stylesheet. wp_enqueue_style( 'twentysixteen-ie7', get_template_directory_uri() . '/css/ie7.css', array( 'twentysixteen-style' ), '20150930' ); wp_style_add_data( 'twentysixteen-ie7', 'conditional', 'lt IE 8' ); // Load the html5 shiv. wp_enqueue_script( 'twentysixteen-html5', get_template_directory_uri() . '/js/html5.js', array(), '3.7.3' ); wp_script_add_data( 'twentysixteen-html5', 'conditional', 'lt IE 9' ); wp_enqueue_script( 'twentysixteen-skip-link-focus-fix', get_template_directory_uri() . '/js/skip-link-focus-fix.js', array(), '20151112', true ); /* 09.02.2017 start */ wp_enqueue_script( 'jquery-ui', get_template_directory_uri() . '/js/jquery-ui.js', array(), '20151112', true ); //wp_enqueue_script( 'taskCompRegress', get_template_directory_uri() . '/js/taskCompRegress.js', array(), '20151112', true ); if(is_single(556) || is_single(274)){ wp_enqueue_script( 'UXSalary2014', get_template_directory_uri() . '/js/UXSalary2014.js', array(), '20151112', true ); } if(is_single(6440)){ wp_enqueue_script( 'UXSalary2016', get_template_directory_uri() . '/js/UXSalary2016.js', array(), '20170314', true ); } if(is_single(3656)){ wp_enqueue_script( 'UXSalary.js', get_template_directory_uri() . '/js/UXSalary.js', array(), '20110823', true ); } if(is_single(204)){ wp_enqueue_script( 'taskCompRegress.js', get_template_directory_uri() . '/js/taskCompRegress.js', array(), '20110321', true ); } if(is_single(274)){ //wp_enqueue_script( 'UXSalary', get_template_directory_uri() . '/js/UXSalary.js', array(), '20151112', true ); wp_enqueue_script( 'npsSUSMeanRegress', get_template_directory_uri() . '/js/npsSUSMeanRegress.js', array(), '20151112', true ); } if(is_single(458)){ wp_enqueue_script( 'UXQuiz', get_template_directory_uri() . '/js/UXQuiz.js', array(), '20131112', true ); } //wp_enqueue_script( 'UXQuiz', get_template_directory_uri() . '/js/UXQuiz.js', array(), '20151112', true ); if(is_single(3695)){ wp_enqueue_script( 'bs', get_template_directory_uri() . '/js/bs.js', array(), '20151112', true ); } if(is_single(3703)){ wp_enqueue_script( 'uiProbs', get_template_directory_uri() . '/js/uiProbs.js', array(), '20151112', true ); } wp_enqueue_script( 'ciquiz', get_template_directory_uri() . '/js/ciquiz.js', array(), '20151112', true ); wp_enqueue_script( 'geoMean', get_template_directory_uri() . '/js/geoMean.js', array(), '20151112', true ); wp_enqueue_script( 'jquery-2.2.4.min', get_template_directory_uri() . '/js/jquery-2.2.4.min.js', array(), '20151112', true ); wp_enqueue_script( 'jquery-3.1.0.min.js', get_template_directory_uri() . '/js/jquery-3.1.0.min.js', array(), '20151112', true ); wp_enqueue_script( 'custSampSize.js', get_template_directory_uri() . '/js/custSampSize.js', array(), '20151112', true ); wp_enqueue_script( 'actb.js', get_template_directory_uri() . '/js/actb.js', array(), '20151112', true ); // wp_enqueue_script( 'color-scheme-control', get_template_directory_uri() . '/js/color-scheme-control.js', array(), '20151112', true ); //wp_enqueue_script( 'compSUSRegress', get_template_directory_uri() . '/js/compSUSRegress.js', array(), '20151112', true ); //wp_enqueue_script( 'customize-preview', get_template_directory_uri() . '/js/customize-preview.js', array(), '20151112', true ); wp_enqueue_script( 'html5', get_template_directory_uri() . '/js/html5.js', array(), '20151112', true ); //wp_enqueue_script( 'keyboard-image-navigation', get_template_directory_uri() . '/js/keyboard-image-navigation.js', array(), '20151112', true ); wp_enqueue_script( 'klm', get_template_directory_uri() . '/js/klm.js', array(), '20151112', true ); wp_enqueue_script( 'myscript', get_template_directory_uri() . '/js/myscript.js', array(), '20151112', true ); wp_enqueue_script( 'myselect2', get_template_directory_uri() . '/js/myselect2.js', array(), '20151112', true ); //wp_enqueue_script( 'npsMeanRegress', get_template_directory_uri() . '/js/npsMeanRegress.js', array(), '20151112', true ); if(is_single(230)) { wp_enqueue_script( 'npsMeanRegress', get_template_directory_uri() . '/js/npsMeanRegress.js', array(), '20151112', true ); wp_enqueue_script( 'npsSUSMeanRegress', get_template_directory_uri() . '/js/npsSUSMeanRegress.js', array(), '20151112', true ); } wp_enqueue_script( 'organic', get_template_directory_uri() . '/js/organic.js', array(), '20151112', true ); wp_enqueue_script( 'skip-link-focus-fix', get_template_directory_uri() . '/js/skip-link-focus-fix.js', array(), '20151112', true ); wp_enqueue_script( 'jquery-1.10.2', get_template_directory_uri() . '/js/jquery-1.10.2.js', array(), '20151112', true ); /* 09.02.2017 end */ wp_enqueue_style( 'custom-style', get_template_directory_uri() . '/css/custom.css', array(), false, '' ); if ( is_singular() && comments_open() && get_option( 'thread_comments' ) ) { wp_enqueue_script( 'comment-reply' ); } if ( is_singular() && wp_attachment_is_image() ) { wp_enqueue_script( 'twentysixteen-keyboard-image-navigation', get_template_directory_uri() . '/js/keyboard-image-navigation.js', array( 'jquery' ), '20151104' ); } wp_enqueue_script( 'twentysixteen-script', get_template_directory_uri() . '/js/functions.js', array( 'jquery' ), '20151204', true ); wp_enqueue_script( 'twentysixteen-jquery', get_template_directory_uri() . '/js/jquery-1.12.0.min.js', array( 'jquery' ), '', true ); wp_enqueue_script( 'twentysixteen-boot', get_template_directory_uri() . '/js/bootstrap.js', array( 'jquery' ), '', true ); wp_enqueue_script( 'twentysixteen-owl', get_template_directory_uri() . '/js/owl.carousel.js', array( 'jquery' ), '', true ); wp_enqueue_script( 'twentysixteen-main', get_template_directory_uri() . '/js/main.js', array( 'jquery' ), '', true ); wp_localize_script( 'twentysixteen-script', 'screenReaderText', array( 'expand' => __( 'expand child menu', 'twentysixteen' ), 'collapse' => __( 'collapse child menu', 'twentysixteen' ), ) ); } add_action( 'wp_enqueue_scripts', 'twentysixteen_scripts' ); ``` All of this works. Now, I want to enqueue yet another file. Additionally, I wanted to make it load conditionally, anywhere but front page, but at this point I'd be very happy by making it load at all! First, I tried the conditional version `(if ! is_front_page...)` but didn't work (I made it work on `header.php`, but I want it to load after everything else). Thinking there might be an error in my code, I tried enqueuing the file just to see it loads.... and nothing. Tried everything I could think of... and nothing. So, as a last resource, I tried replacing one of the files that actually loads, `custom-style --> css/custom.css` and as weird as it sounds, it does nothing. Furthermore, if I check the source, even so `css/custom.css` shouldn't be there, it still is. **Just in case: I don't have any cache and I can see any other changes that are not related to this file.** Finally, I tried to create a different function to enqueue files and nothing, it doesn't work at all. This is the code I tried to add with no luck: ``` {wp_enqueue_style( 'blog-styles', get_template_directory_uri() . 'full-style.css', array( 'twentysixteen-style' ), '20170410' );} ``` Finally, based on [this answer](https://wordpress.stackexchange.com/questions/124354/why-wp-register-style-is-important-while-im-using-a-complete-wp-enqueue-style/124381#124381) I tried this, which would also help with the conditional part: ``` add_action('init', 'my_register_styles'); function my_register_styles() { wp_register_style( 'style1', get_template_directory_uri() . '/style.css' ); wp_register_style( 'style2', get_template_directory_uri() . '/full-style.css' ); } add_action( 'wp_enqueue_scripts', 'my_enqueue_styles' ); function my_enqueue_styles() { if ( is_front_page() ) { wp_enqueue_style( 'style1' ); } else { wp_enqueue_style( 'style2' ); } } ``` but as you probably imagine by now.... it didn't work! Question(s) =========== * What is causing this? What am I doing wrong? * Is there a way to make the stylesheet load on header.php AFTER the enqueued scripts?
this line IS your php inlcude path: ``` require_once(dirname(__FILE__) . 'path_to ChargeBee.php'); ``` you need to change it to something specific to your coding. ie: are you putting this into a theme or a plugin? ( would suggest a plugin) If that were the case you would use something like this: require\_once( CHARGEBEEPLUGIN\_DIR . '/lib/chargebee.php' ); this would include the file that it finds at wp-content/plugins/chargebeeapi/lib/chargebee.php the chargbee.php is what you're getting from github. Do you have experience with api's though? It's not as simple as just putting the github folder on your system and you're off to the races unfortunately. The link you referenced is the library to for the chargbee api. You now need to create your side of the tool to utilize the library. I suggested a plugin as that is how I do it. You're not going to just put it in the plugin folder though: you need to create a folder within the plugin directory with your new plugin folders. for instance: In the wp-content/plugins folder you create a new folder, "chargebeeapi" then in that folder you add your library (the lib folder you downloaded from gitub) wp-content/plugins/chargebeeapi/lib now in the chargbeeapi folder you create your main plugin php file that will reference the library by using the above include path. In this php file you'll need to create form and submission button (this will vary depending upon how you need to interact with chargbee.) As well as a response container to get the response back after your request/push to their system. Lastly you'll need to tell wordpress this is a plugin and identify where the form / interaction will occur in wordpress.
263,185
<p>I'm trying to make a Wordpress blog where the home page shows only the 3 most recent posts, but for the newest of these posts, it shows the entire post (not just the teaser content), and then for the other 2, it shows the teaser content with the "read more" button.</p> <p>I'm currently building all this with the "Basic" theme.</p> <p>I'm still fairly new to Wordpress and PHP, but have a firm background in HTML/CSS, and a little Java background.</p> <p>Any ideas?</p> <p>Also, is there a way to control how much of the post is shown before the "Read More" button?</p>
[ { "answer_id": 263203, "author": "frenchy black", "author_id": 28580, "author_profile": "https://wordpress.stackexchange.com/users/28580", "pm_score": 0, "selected": false, "text": "<p>for the first part of your question i would use this to achieve it</p>\n\n<p><pre><code> // FIRST LOOP: display posts 1 \nquery_posts('showposts=1'); \n $posts = get_posts('numberposts=1&amp;offset=0'); foreach ($posts as $post) : start_wp(); \n static $count1 = 0; if ($count1 == \"1\") { break; } else { </p>\n\n<p>the_title(); \n the_content(); </p>\n\n<p>$count1++; } \n endforeach; </p>\n\n<p>// SECOND LOOP: display posts 2 and 3\n query_posts('showposts=2'); \n $posts = get_posts('numberposts=2&amp;offset=1'); foreach ($posts as $post) : start_wp(); \n static $count2 = 0; if ($count2 == \"2\") { break; } else { </p>\n\n<p>the_title(); \n the_excerpt(); </p>\n\n<p>$count2++; } \n endforeach;\n</code></pre></p>\n\n<p>For the second part of you question on showing how much is show before the read more, add this to your function file</p>\n\n<pre><code>function new_excerpt_length($length) { return 15; } add_filter('excerpt_length', 'new_excerpt_length');\n</code></pre>\n\n<p>change the number 15 to the amount you like to be shown</p>\n" }, { "answer_id": 263204, "author": "rudtek", "author_id": 77767, "author_profile": "https://wordpress.stackexchange.com/users/77767", "pm_score": 1, "selected": false, "text": "<p>Add a counter to the query and vary the output depending upon what the count is.</p>\n\n<p>You'll need to either directly edit the args to limit to 3 posts_per_page or use pre_get_posts to do it.</p>\n\n<p>pre get posts example (into your functions.php)</p>\n\n<pre><code>function hwl_home_pagesize( $query ) {\n if ( is_home() ) {\n // Display only 3 post for the original blog archive\n $query-&gt;set( 'posts_per_page', 3 );\n return;\n }\n\n}\nadd_action( 'pre_get_posts', 'hwl_home_pagesize', 1 );\n</code></pre>\n\n<p>Then into your home.php (or whichever file basic theme uses):</p>\n\n<pre><code>if ( have_posts() ) {\n $i=1;\n while ( have_posts() ) {\n the_post(); \n //\n if ($i==1) {\n //first post\n the_title();\n the_content();\n }else{\n //other 2 posts\n the_title();\n the_excerpt();\n }\n //\n $i++;\n } // end while\n} // end if\n</code></pre>\n\n<p>Now in your dashboard also make sure that settings/reading the option \"show full text\" is selected.</p>\n\n<p>Or, if you want to start your own query you can instead of using the main query:</p>\n\n<pre><code>// WP_Query arguments\n$args = array( 'posts_per_page' =&gt; '3'; 'post_type' =&gt; 'posts';\n);\n\n// The Query\n$query = new WP_Query( $args );\n\n// The Loop\nif ( $query-&gt;have_posts() ) {\n $i=1;\nwhile ( $query-&gt;have_posts() ) {\n $query-&gt;the_post();\n // do something\n if ($i==1) {\n //first post\n the_title();\n the_content();\n }else{\n //other 2 posts\n the_title();\n the_excerpt();\n }\n $i++;\n\n}\n\n } else {\n // no posts found\n }\n// Restore original Post Data\nwp_reset_postdata();\n</code></pre>\n\n<p>THis would eliminate the need to add to your functions.php</p>\n" }, { "answer_id": 263206, "author": "Abhishek Pandey", "author_id": 114826, "author_profile": "https://wordpress.stackexchange.com/users/114826", "pm_score": 0, "selected": false, "text": "<p>You can set posts per page from wordpress admin pannel Settings > Reading settings > Blog pages show at most, set to whatever you need.</p>\n\n<pre><code>$args = array(\n 'posts_per_page' =&gt; 3,\n 'orderby' =&gt; 'date',\n 'order' =&gt; 'DESC',\n 'post_type' =&gt; 'post',\n 'post_status' =&gt; 'publish',\n);\n$posts_array = get_posts( $args );\necho \"&lt;ul&gt;\";\nforeach ( $myposts as $post ) : setup_postdata( $post ); ?&gt;\n &lt;li&gt;\n &lt;a href=\"&lt;?php the_permalink(); ?&gt;\"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;\n &lt;?php the_content();?&gt;\n &lt;/li&gt;\n&lt;?php endforeach; \nwp_reset_postdata();?&gt;\necho \"&lt;/ul&gt;\";\n</code></pre>\n" } ]
2017/04/11
[ "https://wordpress.stackexchange.com/questions/263185", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/117365/" ]
I'm trying to make a Wordpress blog where the home page shows only the 3 most recent posts, but for the newest of these posts, it shows the entire post (not just the teaser content), and then for the other 2, it shows the teaser content with the "read more" button. I'm currently building all this with the "Basic" theme. I'm still fairly new to Wordpress and PHP, but have a firm background in HTML/CSS, and a little Java background. Any ideas? Also, is there a way to control how much of the post is shown before the "Read More" button?
Add a counter to the query and vary the output depending upon what the count is. You'll need to either directly edit the args to limit to 3 posts\_per\_page or use pre\_get\_posts to do it. pre get posts example (into your functions.php) ``` function hwl_home_pagesize( $query ) { if ( is_home() ) { // Display only 3 post for the original blog archive $query->set( 'posts_per_page', 3 ); return; } } add_action( 'pre_get_posts', 'hwl_home_pagesize', 1 ); ``` Then into your home.php (or whichever file basic theme uses): ``` if ( have_posts() ) { $i=1; while ( have_posts() ) { the_post(); // if ($i==1) { //first post the_title(); the_content(); }else{ //other 2 posts the_title(); the_excerpt(); } // $i++; } // end while } // end if ``` Now in your dashboard also make sure that settings/reading the option "show full text" is selected. Or, if you want to start your own query you can instead of using the main query: ``` // WP_Query arguments $args = array( 'posts_per_page' => '3'; 'post_type' => 'posts'; ); // The Query $query = new WP_Query( $args ); // The Loop if ( $query->have_posts() ) { $i=1; while ( $query->have_posts() ) { $query->the_post(); // do something if ($i==1) { //first post the_title(); the_content(); }else{ //other 2 posts the_title(); the_excerpt(); } $i++; } } else { // no posts found } // Restore original Post Data wp_reset_postdata(); ``` THis would eliminate the need to add to your functions.php
263,215
<p>I am using the below code in functions.php to add custom query variables to my WordPress project.</p> <pre><code>&lt;?php function add_custom_query_var( $vars ){ $vars[] = "brand"; return $vars; } add_filter( 'query_vars', 'add_custom_query_var' ); ?&gt; </code></pre> <p>And then on the content page I am using:</p> <pre><code>&lt;?php echo $currentbrand = get_query_var('brand'); ?&gt; </code></pre> <p>So now I can pass a URL like:</p> <pre><code>http://myexamplesite.com/store/?brand=nike </code></pre> <p>and get nike in result.</p> <p>How can I pass multiple values for a brand. So I would like to have 3 values for brand say, nike, adidas and woodland.</p> <p>I have tried the following and none of them works:</p> <ol> <li><p><code>http://myexamplesite.com/store/?brand=nike&amp;brand=adidas&amp;brand=woodland</code> It just returns the last brand, in this case woodland.</p></li> <li><p><code>http://myexamplesite.com/store/?brand=nike+adidas+woodland</code> This returns all three with spaces. I kind of think this is not the correct solution. So may be there is a correct way to pass multiple values for a query variable and retrieve them in an array may be so that a loop can be run.</p></li> </ol>
[ { "answer_id": 263236, "author": "Faysal Mahamud", "author_id": 83752, "author_profile": "https://wordpress.stackexchange.com/users/83752", "pm_score": 3, "selected": true, "text": "<p>I am giving you some solutions whatever you want to use.</p>\n\n<blockquote>\n <p>Using plus <a href=\"http://myexamplesite.com/store/?brand=nike+adidas+woodland\" rel=\"nofollow noreferrer\">http://myexamplesite.com/store/?brand=nike+adidas+woodland</a></p>\n</blockquote>\n\n<pre><code>//Don't decode URL\n &lt;?php\n $brand = get_query_var('brand');\n $brand = explode('+',$brand);\n print_r($brand);\n ?&gt;\n</code></pre>\n\n<blockquote>\n <p>using ,separator <a href=\"http://myexamplesite.com/store/?brand=nike,adidas,woodland\" rel=\"nofollow noreferrer\">http://myexamplesite.com/store/?brand=nike,adidas,woodland</a></p>\n</blockquote>\n\n<pre><code>$brand = get_query_var('brand');\n$brand = explode(',',$brand);\nprint_r($brand);\n</code></pre>\n\n<blockquote>\n <p>Serialize way</p>\n</blockquote>\n\n<pre><code>&lt;?php $array = array('nike','adidas','woodland');?&gt;\nhttp://myexamplesite.com/store/?brand=&lt;?php echo serialize($array)?&gt;\nto get url data\n$array= unserialize($_GET['var']);\nor $array= unserialize(get_query_var('brand'));\nprint_r($array);\n</code></pre>\n\n<blockquote>\n <p>json way</p>\n</blockquote>\n\n<pre><code>&lt;?php $array = array('nike','adidas','woodland');\n $tags = base64_encode(json_encode($array));\n?&gt;\nhttp://myexamplesite.com/store/?brand=&lt;?php echo $tags;?&gt;\n&lt;?php $json = json_decode(base64_decode($tags))?&gt;\n&lt;?php print_r($json);?&gt;\n</code></pre>\n\n<blockquote>\n <p>using - way</p>\n</blockquote>\n\n<p>I suggest using mod_rewrite to rewrite like <a href=\"http://myexamplesite.com/store/brand/nike-adidas-woodland\" rel=\"nofollow noreferrer\">http://myexamplesite.com/store/brand/nike-adidas-woodland</a> or if you want to use only php <a href=\"http://myexamplesite.com/store/?brand=tags=nike-adidas-woodland\" rel=\"nofollow noreferrer\">http://myexamplesite.com/store/?brand=tags=nike-adidas-woodland</a>. Using the '-' makes it search engine friendly.</p>\n\n<pre><code>&lt;?php\n $brand = get_query_var('brand');\n $brand = explode('-',$brand);\n print_r($brand);\n?&gt;\n</code></pre>\n\n<blockquote>\n <p>In every case, you will get the same result</p>\n</blockquote>\n\n<pre><code> Array\n (\n [0] =&gt; nike\n [1] =&gt; adidas\n [2] =&gt; woodland\n )\n</code></pre>\n" }, { "answer_id": 383541, "author": "Nicolas RIVIERE", "author_id": 202069, "author_profile": "https://wordpress.stackexchange.com/users/202069", "pm_score": 1, "selected": false, "text": "<p>Use &quot;name[]&quot; in name property :</p>\n<pre><code>&lt;input type=&quot;checkbox&quot; name=&quot;brand[]&quot;&gt;\n</code></pre>\n" } ]
2017/04/11
[ "https://wordpress.stackexchange.com/questions/263215", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/81898/" ]
I am using the below code in functions.php to add custom query variables to my WordPress project. ``` <?php function add_custom_query_var( $vars ){ $vars[] = "brand"; return $vars; } add_filter( 'query_vars', 'add_custom_query_var' ); ?> ``` And then on the content page I am using: ``` <?php echo $currentbrand = get_query_var('brand'); ?> ``` So now I can pass a URL like: ``` http://myexamplesite.com/store/?brand=nike ``` and get nike in result. How can I pass multiple values for a brand. So I would like to have 3 values for brand say, nike, adidas and woodland. I have tried the following and none of them works: 1. `http://myexamplesite.com/store/?brand=nike&brand=adidas&brand=woodland` It just returns the last brand, in this case woodland. 2. `http://myexamplesite.com/store/?brand=nike+adidas+woodland` This returns all three with spaces. I kind of think this is not the correct solution. So may be there is a correct way to pass multiple values for a query variable and retrieve them in an array may be so that a loop can be run.
I am giving you some solutions whatever you want to use. > > Using plus <http://myexamplesite.com/store/?brand=nike+adidas+woodland> > > > ``` //Don't decode URL <?php $brand = get_query_var('brand'); $brand = explode('+',$brand); print_r($brand); ?> ``` > > using ,separator <http://myexamplesite.com/store/?brand=nike,adidas,woodland> > > > ``` $brand = get_query_var('brand'); $brand = explode(',',$brand); print_r($brand); ``` > > Serialize way > > > ``` <?php $array = array('nike','adidas','woodland');?> http://myexamplesite.com/store/?brand=<?php echo serialize($array)?> to get url data $array= unserialize($_GET['var']); or $array= unserialize(get_query_var('brand')); print_r($array); ``` > > json way > > > ``` <?php $array = array('nike','adidas','woodland'); $tags = base64_encode(json_encode($array)); ?> http://myexamplesite.com/store/?brand=<?php echo $tags;?> <?php $json = json_decode(base64_decode($tags))?> <?php print_r($json);?> ``` > > using - way > > > I suggest using mod\_rewrite to rewrite like <http://myexamplesite.com/store/brand/nike-adidas-woodland> or if you want to use only php <http://myexamplesite.com/store/?brand=tags=nike-adidas-woodland>. Using the '-' makes it search engine friendly. ``` <?php $brand = get_query_var('brand'); $brand = explode('-',$brand); print_r($brand); ?> ``` > > In every case, you will get the same result > > > ``` Array ( [0] => nike [1] => adidas [2] => woodland ) ```
263,251
<p>I have a custom post type no_resume and when a new post is created in it and a meta that is job_category is assigned to it I want to perform a function in which a mail will be sent to all the user that has that category in their database.</p> <p>I tried <code>save_post</code> and <code>publish_post</code> and checked if meta exists in the database but save post fires before adding meta I want to execute that function only when a new post is created not when it is updated.</p>
[ { "answer_id": 263236, "author": "Faysal Mahamud", "author_id": 83752, "author_profile": "https://wordpress.stackexchange.com/users/83752", "pm_score": 3, "selected": true, "text": "<p>I am giving you some solutions whatever you want to use.</p>\n\n<blockquote>\n <p>Using plus <a href=\"http://myexamplesite.com/store/?brand=nike+adidas+woodland\" rel=\"nofollow noreferrer\">http://myexamplesite.com/store/?brand=nike+adidas+woodland</a></p>\n</blockquote>\n\n<pre><code>//Don't decode URL\n &lt;?php\n $brand = get_query_var('brand');\n $brand = explode('+',$brand);\n print_r($brand);\n ?&gt;\n</code></pre>\n\n<blockquote>\n <p>using ,separator <a href=\"http://myexamplesite.com/store/?brand=nike,adidas,woodland\" rel=\"nofollow noreferrer\">http://myexamplesite.com/store/?brand=nike,adidas,woodland</a></p>\n</blockquote>\n\n<pre><code>$brand = get_query_var('brand');\n$brand = explode(',',$brand);\nprint_r($brand);\n</code></pre>\n\n<blockquote>\n <p>Serialize way</p>\n</blockquote>\n\n<pre><code>&lt;?php $array = array('nike','adidas','woodland');?&gt;\nhttp://myexamplesite.com/store/?brand=&lt;?php echo serialize($array)?&gt;\nto get url data\n$array= unserialize($_GET['var']);\nor $array= unserialize(get_query_var('brand'));\nprint_r($array);\n</code></pre>\n\n<blockquote>\n <p>json way</p>\n</blockquote>\n\n<pre><code>&lt;?php $array = array('nike','adidas','woodland');\n $tags = base64_encode(json_encode($array));\n?&gt;\nhttp://myexamplesite.com/store/?brand=&lt;?php echo $tags;?&gt;\n&lt;?php $json = json_decode(base64_decode($tags))?&gt;\n&lt;?php print_r($json);?&gt;\n</code></pre>\n\n<blockquote>\n <p>using - way</p>\n</blockquote>\n\n<p>I suggest using mod_rewrite to rewrite like <a href=\"http://myexamplesite.com/store/brand/nike-adidas-woodland\" rel=\"nofollow noreferrer\">http://myexamplesite.com/store/brand/nike-adidas-woodland</a> or if you want to use only php <a href=\"http://myexamplesite.com/store/?brand=tags=nike-adidas-woodland\" rel=\"nofollow noreferrer\">http://myexamplesite.com/store/?brand=tags=nike-adidas-woodland</a>. Using the '-' makes it search engine friendly.</p>\n\n<pre><code>&lt;?php\n $brand = get_query_var('brand');\n $brand = explode('-',$brand);\n print_r($brand);\n?&gt;\n</code></pre>\n\n<blockquote>\n <p>In every case, you will get the same result</p>\n</blockquote>\n\n<pre><code> Array\n (\n [0] =&gt; nike\n [1] =&gt; adidas\n [2] =&gt; woodland\n )\n</code></pre>\n" }, { "answer_id": 383541, "author": "Nicolas RIVIERE", "author_id": 202069, "author_profile": "https://wordpress.stackexchange.com/users/202069", "pm_score": 1, "selected": false, "text": "<p>Use &quot;name[]&quot; in name property :</p>\n<pre><code>&lt;input type=&quot;checkbox&quot; name=&quot;brand[]&quot;&gt;\n</code></pre>\n" } ]
2017/04/11
[ "https://wordpress.stackexchange.com/questions/263251", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/104741/" ]
I have a custom post type no\_resume and when a new post is created in it and a meta that is job\_category is assigned to it I want to perform a function in which a mail will be sent to all the user that has that category in their database. I tried `save_post` and `publish_post` and checked if meta exists in the database but save post fires before adding meta I want to execute that function only when a new post is created not when it is updated.
I am giving you some solutions whatever you want to use. > > Using plus <http://myexamplesite.com/store/?brand=nike+adidas+woodland> > > > ``` //Don't decode URL <?php $brand = get_query_var('brand'); $brand = explode('+',$brand); print_r($brand); ?> ``` > > using ,separator <http://myexamplesite.com/store/?brand=nike,adidas,woodland> > > > ``` $brand = get_query_var('brand'); $brand = explode(',',$brand); print_r($brand); ``` > > Serialize way > > > ``` <?php $array = array('nike','adidas','woodland');?> http://myexamplesite.com/store/?brand=<?php echo serialize($array)?> to get url data $array= unserialize($_GET['var']); or $array= unserialize(get_query_var('brand')); print_r($array); ``` > > json way > > > ``` <?php $array = array('nike','adidas','woodland'); $tags = base64_encode(json_encode($array)); ?> http://myexamplesite.com/store/?brand=<?php echo $tags;?> <?php $json = json_decode(base64_decode($tags))?> <?php print_r($json);?> ``` > > using - way > > > I suggest using mod\_rewrite to rewrite like <http://myexamplesite.com/store/brand/nike-adidas-woodland> or if you want to use only php <http://myexamplesite.com/store/?brand=tags=nike-adidas-woodland>. Using the '-' makes it search engine friendly. ``` <?php $brand = get_query_var('brand'); $brand = explode('-',$brand); print_r($brand); ?> ``` > > In every case, you will get the same result > > > ``` Array ( [0] => nike [1] => adidas [2] => woodland ) ```
263,265
<p>I know this isn't technically a WordPress issue but since it's on a WP project, I'm posting here hoping others have encountered and resolved a similar issue.</p> <p>I've changed the Blog section of a site I'm working on to News and it all works great, but the one thing I need is for legacy posts using the Blog slug to redirect using the News one. Seems straightforward, I know, which is why I'm scratching my head with this one.</p> <p>Here's the code I'm using in my .htaccess file (the last rewrite rule being what I added to the file):</p> <pre><code># BEGIN WordPress &lt;IfModule mod_rewrite.c&gt; RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] RewriteRule ^blog/(.*)$ /news/$1 [R=301,L] &lt;/IfModule&gt; # END WordPress </code></pre> <p>For some reason, it isn't working and I've done everyone from flushing the cache to deactivating plugins and nada. </p> <p>Any insight would be greatly appreciated!</p>
[ { "answer_id": 263281, "author": "WebElaine", "author_id": 102815, "author_profile": "https://wordpress.stackexchange.com/users/102815", "pm_score": 0, "selected": false, "text": "<p>I usually have more luck when I put any custom redirects above the WP code. Also you need a / before 'blog' in the redirect:</p>\n\n<pre><code>&lt;IfModule mod_rewrite.c&gt;\nRewriteEngine On\nRewriteBase /\nRewriteRule ^/blog/(.*)$ /news/$1 [R=301,L]\n&lt;/IfModule&gt;\n\n# BEGIN WordPress\n&lt;IfModule mod_rewrite.c&gt;\nRewriteEngine On\nRewriteBase /\nRewriteRule ^index\\.php$ - [L]\nRewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\nRewriteRule . /index.php [L]\n&lt;/IfModule&gt;\n# END WordPress\n</code></pre>\n" }, { "answer_id": 263302, "author": "user117406", "author_id": 117406, "author_profile": "https://wordpress.stackexchange.com/users/117406", "pm_score": 2, "selected": false, "text": "<p>OK, so here's the solution that works for me...</p>\n\n<pre><code>&lt;IfModule mod_rewrite.c&gt;\nRewriteEngine On\nRewriteBase /\nRewriteRule ^blog/(.*) news/$1 [L,R=301]\n&lt;/IfModule&gt;\n\n# BEGIN WordPress\n&lt;IfModule mod_rewrite.c&gt;\nRewriteEngine On\nRewriteBase /\nRewriteRule ^index\\.php$ - [L]\nRewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\nRewriteRule . /index.php [L]\n&lt;/IfModule&gt;\n</code></pre>\n\n<p># END WordPress</p>\n\n<p>Thanks again to @WebElaine for the input!</p>\n" } ]
2017/04/11
[ "https://wordpress.stackexchange.com/questions/263265", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/117406/" ]
I know this isn't technically a WordPress issue but since it's on a WP project, I'm posting here hoping others have encountered and resolved a similar issue. I've changed the Blog section of a site I'm working on to News and it all works great, but the one thing I need is for legacy posts using the Blog slug to redirect using the News one. Seems straightforward, I know, which is why I'm scratching my head with this one. Here's the code I'm using in my .htaccess file (the last rewrite rule being what I added to the file): ``` # BEGIN WordPress <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] RewriteRule ^blog/(.*)$ /news/$1 [R=301,L] </IfModule> # END WordPress ``` For some reason, it isn't working and I've done everyone from flushing the cache to deactivating plugins and nada. Any insight would be greatly appreciated!
OK, so here's the solution that works for me... ``` <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^blog/(.*) news/$1 [L,R=301] </IfModule> # BEGIN WordPress <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] </IfModule> ``` # END WordPress Thanks again to @WebElaine for the input!
263,268
<p>I am generating critical CSS for every page and category. At the moment I am inserting the stylesheet through <code>functions.php</code> like this simply using <code>echo</code>.</p> <pre><code>function criticalCSS_wp_head() { if (is_front_page() ){ echo '&lt;style&gt;'; include get_stylesheet_directory() . '/css/critical/ccss-index.min.css'; echo '&lt;/style&gt;'; } elseif (is_category('orange') ){ echo '&lt;style&gt;'; include get_stylesheet_directory() . '/css/critical/ccss-orange.min.css'; echo '&lt;/style&gt;'; } elseif (is_page('hello-world') ){ echo '&lt;style&gt;'; include get_stylesheet_directory() . '/css/critical/ccss-hello-world.min.css'; echo '&lt;/style&gt;'; } elseif (is_single() ){ echo '&lt;style&gt;'; include get_stylesheet_directory() . '/css/critical/ccss-single.min.css'; echo '&lt;/style&gt;'; } } add_action( 'wp_head', 'criticalCSS_wp_head' ); </code></pre> <ol> <li>What would be the best way to include these stylesheets with regards to best practise coding style <strong>and pure relentless speed</strong>, meaning to avoid PHP calls, database calls and so on.</li> <li>Is it better to directly hard-code the critical CSS in the page template perhaps like written in <a href="https://techtage.com/speeding-up-wordpress-sites/" rel="nofollow noreferrer">this post</a> (#10) linked from <a href="https://codex.wordpress.org/WordPress_Optimization" rel="nofollow noreferrer">the official WordPress Optimization documentation</a>?</li> </ol> <p>edit Since this question was answered I forgot to mention that critical CSS needs to be inline in the DOM and not being linked to as a file to avoid render blocking. So I am still looking for a way to use the critical CSS with <code>wp_enqueue_scripts</code>. Perhaps store the file content in a variable and output that when <code>wp_enqueue_scripts</code> asks for it?</p>
[ { "answer_id": 263272, "author": "user3135691", "author_id": 59755, "author_profile": "https://wordpress.stackexchange.com/users/59755", "pm_score": 1, "selected": true, "text": "<p>You can do it like this, put it in your <code>functions.php</code> :</p>\n\n<p>This is the correct way of doing it \"the WordPress way\".</p>\n\n<pre><code>&lt;?php\n // Check if function exisits\n if (!function_exists('rg_templateScriptSetup')) {\n // if not, create one\n function rg_templateScriptSetup() {\n // Register styles in WordPress\n wp_register_style('prefix-basic-css', get_template_directory_uri(). '/css/basic-style.css');\n\n // Register styles in WordPress\n wp_register_style('first-css', get_template_directory_uri(). '/css/first-style.css');\n\n // Register styles in WordPress\n wp_register_style('second-css', get_template_directory_uri(). '/css/second-style.css');\n\n if (is_page('your_page_name') {\n // enqueue your first style\n wp_enqueue_style('first-css');\n } else if(is_page('your_other_page_name')) {\n // enqueue your second style\n wp_enqueue_style('second-css');\n } etc...\n\n\n } // End of Stylesheet logic / setup\n\n add_action('wp_enqueue_scripts', 'rg_templateScriptSetup');\n\n?&gt;\n</code></pre>\n\n<p>Why?</p>\n\n<p>Because WordPress gives you all the tools, necessary to achieve that goal.</p>\n\n<p>What is exactly happening here:</p>\n\n<ol>\n<li>first, we check if the function already exists</li>\n<li>if it doesn't, we create our function</li>\n<li>then we \"register our styles\", basically telling WordPress: here,grab these CSS', so.. WordPress has our stylesheets in it's pocket, but it doesn't use them yet</li>\n<li>then we use the native WordPress function <strong>is_page</strong> in combination with an if\nstatement (if (is_page('your-page-name'))</li>\n<li>in case that if statement returns bool 'true' we activate the css according to our condition (in your case, the page name).</li>\n</ol>\n\n<p>I hope that helps.</p>\n\n<p>In case that answer has helped you, please mark it as correct, and not just grab the code, thanks.</p>\n\n<p>Personal question: what do you mean by critical? Lots of !important? </p>\n" }, { "answer_id": 263276, "author": "WebElaine", "author_id": 102815, "author_profile": "https://wordpress.stackexchange.com/users/102815", "pm_score": 1, "selected": false, "text": "<p>The best-practice and generally accepted right way to add CSS or JS is to enqueue them. That way, if you have say a theme + 2 plugins that all want to enqueue jQuery, you only end up with 1 copy loaded - not 3.</p>\n\n<p>In functions.php:</p>\n\n<pre><code>add_action('wp_enqueue_scripts', 'my_enqueues');\nfunction my_enqueues() {\n if(is_front_page()) {\n wp_enqueue_style('front-page', get_stylesheet_directory() . '/css/critical/ccss-index.min.css', array(), '', 'screen');\n } elseif(is_category('orange')) {\n wp_enqueue_style('orange', get_stylesheet_directory() . '/css/critical/ccss-orange.min.css', array(), '', 'screen');\n }\n}\n</code></pre>\n\n<p>If your per-page styles are short, you can actually enqueue inline styles instead so that the web browser isn't requesting a separate resource.</p>\n\n<pre><code>add_action('wp_enqueue_scripts', 'my_inline_enqueues');\nfunction my_inline_enqueues() {\n wp_add_inline_style('front-page',\n '.myfrontpageclass { font-size:6em; }'\n );\n}\n</code></pre>\n\n<p>Final suggestion - I don't know the content of your stylesheets, but I'd suggest that it may be both simpler and faster to load these pages if you just include all of the CSS in the theme's <code>style.css</code> file together. Use <code>body_class</code> to target whatever you need to and keep it all in one minified file.</p>\n" } ]
2017/04/11
[ "https://wordpress.stackexchange.com/questions/263268", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/77054/" ]
I am generating critical CSS for every page and category. At the moment I am inserting the stylesheet through `functions.php` like this simply using `echo`. ``` function criticalCSS_wp_head() { if (is_front_page() ){ echo '<style>'; include get_stylesheet_directory() . '/css/critical/ccss-index.min.css'; echo '</style>'; } elseif (is_category('orange') ){ echo '<style>'; include get_stylesheet_directory() . '/css/critical/ccss-orange.min.css'; echo '</style>'; } elseif (is_page('hello-world') ){ echo '<style>'; include get_stylesheet_directory() . '/css/critical/ccss-hello-world.min.css'; echo '</style>'; } elseif (is_single() ){ echo '<style>'; include get_stylesheet_directory() . '/css/critical/ccss-single.min.css'; echo '</style>'; } } add_action( 'wp_head', 'criticalCSS_wp_head' ); ``` 1. What would be the best way to include these stylesheets with regards to best practise coding style **and pure relentless speed**, meaning to avoid PHP calls, database calls and so on. 2. Is it better to directly hard-code the critical CSS in the page template perhaps like written in [this post](https://techtage.com/speeding-up-wordpress-sites/) (#10) linked from [the official WordPress Optimization documentation](https://codex.wordpress.org/WordPress_Optimization)? edit Since this question was answered I forgot to mention that critical CSS needs to be inline in the DOM and not being linked to as a file to avoid render blocking. So I am still looking for a way to use the critical CSS with `wp_enqueue_scripts`. Perhaps store the file content in a variable and output that when `wp_enqueue_scripts` asks for it?
You can do it like this, put it in your `functions.php` : This is the correct way of doing it "the WordPress way". ``` <?php // Check if function exisits if (!function_exists('rg_templateScriptSetup')) { // if not, create one function rg_templateScriptSetup() { // Register styles in WordPress wp_register_style('prefix-basic-css', get_template_directory_uri(). '/css/basic-style.css'); // Register styles in WordPress wp_register_style('first-css', get_template_directory_uri(). '/css/first-style.css'); // Register styles in WordPress wp_register_style('second-css', get_template_directory_uri(). '/css/second-style.css'); if (is_page('your_page_name') { // enqueue your first style wp_enqueue_style('first-css'); } else if(is_page('your_other_page_name')) { // enqueue your second style wp_enqueue_style('second-css'); } etc... } // End of Stylesheet logic / setup add_action('wp_enqueue_scripts', 'rg_templateScriptSetup'); ?> ``` Why? Because WordPress gives you all the tools, necessary to achieve that goal. What is exactly happening here: 1. first, we check if the function already exists 2. if it doesn't, we create our function 3. then we "register our styles", basically telling WordPress: here,grab these CSS', so.. WordPress has our stylesheets in it's pocket, but it doesn't use them yet 4. then we use the native WordPress function **is\_page** in combination with an if statement (if (is\_page('your-page-name')) 5. in case that if statement returns bool 'true' we activate the css according to our condition (in your case, the page name). I hope that helps. In case that answer has helped you, please mark it as correct, and not just grab the code, thanks. Personal question: what do you mean by critical? Lots of !important?
263,293
<p>Final state: As Nathan Johnson stated, I change my plug in to a class, still can't use post id in increment_like function...</p> <pre><code>&lt;?php .... //irrelevant parts skipped class wpse_263293 { protected $ID; //* Add actions on init public function init() { add_action( 'the_post', [ $this, 'createLikeButton' ] ); add_action( 'wp_footer', [ $this, 'footer' ] ); add_action('wp_enqueue_scripts',[ $this ,'button_js']); add_action('wp_ajax_increment_like', [$this,'increment_like']); add_action('wp_ajax_no_priv_increment_like',[$this,'increment_like']); } public function footer() { //* Print the ID property in the footer echo $this-&gt;ID; //This one works } public function createLikeButton( $post ) { $this-&gt;ID = $post-&gt;ID; $myId=$post-&gt;ID; echo "&lt;button onclick=\"likeButton()\" p style=\"font-size:10px\" id=\"likeButton\"&gt;LIKE&lt;/button&gt;"; } public function button_js(){ wp_enqueue_script( 'likeButton', plugins_url( '/like.js', __FILE__ ),array('jquery')); wp_localize_script('likeButton', 'my_ajax_object', array( 'ajax_url' =&gt;admin_url('admin-ajax.php'))); wp_localize_script('likeButton', 'new_ajax_object', array( 'ajax_url' =&gt;admin_url('admin-ajax.php'))); } public function increment_like() { echo $this-&gt;ID."test"; //I only see test /* irrelevant code*/ } } //* Initiate the class and hook into init add_action( 'init', [ $wpse_263293 = new wpse_263293(), 'init' ] ); ?&gt; </code></pre>
[ { "answer_id": 263290, "author": "rudtek", "author_id": 77767, "author_profile": "https://wordpress.stackexchange.com/users/77767", "pm_score": 0, "selected": false, "text": "<p>The best way to figure out what is going on is to disable your plugins and see if it goes away.</p>\n\n<p>Rename your plugins folder to something else. Does this fix the issue?</p>\n\n<p>If it does rename the plugin folder back to plugins. Now you have to enable 1 by 1 each plugin and check if all still is working.\nWhen all seems okay then at least you found a solution but still have no answer about the 'why was it not working' but it would be too far to dig into that issue but at least now you can take some time to find out what is causing that field to appear.</p>\n\n<p>Are you using x theme? It could be that theme itself so try switching themes as well.</p>\n" }, { "answer_id": 263309, "author": "cjbj", "author_id": 75495, "author_profile": "https://wordpress.stackexchange.com/users/75495", "pm_score": 3, "selected": true, "text": "<p>Yes, this is a <a href=\"https://yoast.com/what-is-cornerstone-content/\" rel=\"nofollow noreferrer\">new Yoast SEO feature</a>. It's a checkbox, so as long a you don't select it in the SEO-metabox, the value will be zero/empty. I presume it's overwritten every time the post is saved, hence it won't delete or accept a value written directly into the database table.</p>\n\n<p>There doesn't seem to be a setting in the dashboard, so in order to disable it you'll have to search the code for a filter or contact Yoast.</p>\n" }, { "answer_id": 263496, "author": "Nathalie", "author_id": 117573, "author_profile": "https://wordpress.stackexchange.com/users/117573", "pm_score": 0, "selected": false, "text": "<p>Yes it seems to be SEO Yoast, any posts done with the updated plugin active will add the text, deactivating the plugin and creating a new post does not produce the unwanted <code>yst_is_cornerstone</code>, however, it still remains on the posts done with the plugin active, how strange and annoying!</p>\n" }, { "answer_id": 263543, "author": "Amjad", "author_id": 34472, "author_profile": "https://wordpress.stackexchange.com/users/34472", "pm_score": 1, "selected": false, "text": "<p>To disable that custom field, go to <strong>Yoast SEO > Dashboard > Features.</strong></p>\n\n<p><a href=\"https://i.stack.imgur.com/DX79A.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/DX79A.png\" alt=\"Pic of screenshot\"></a></p>\n\n<p>Read more about <a href=\"https://yoast.com/what-is-cornerstone-content/#utm_source=dashboard-feature-tab&amp;utm_medium=inline-help&amp;utm_campaign=cornerstone-content&amp;utm_content=4.6\" rel=\"nofollow noreferrer\">cornerstore content</a></p>\n" } ]
2017/04/11
[ "https://wordpress.stackexchange.com/questions/263293", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/117351/" ]
Final state: As Nathan Johnson stated, I change my plug in to a class, still can't use post id in increment\_like function... ``` <?php .... //irrelevant parts skipped class wpse_263293 { protected $ID; //* Add actions on init public function init() { add_action( 'the_post', [ $this, 'createLikeButton' ] ); add_action( 'wp_footer', [ $this, 'footer' ] ); add_action('wp_enqueue_scripts',[ $this ,'button_js']); add_action('wp_ajax_increment_like', [$this,'increment_like']); add_action('wp_ajax_no_priv_increment_like',[$this,'increment_like']); } public function footer() { //* Print the ID property in the footer echo $this->ID; //This one works } public function createLikeButton( $post ) { $this->ID = $post->ID; $myId=$post->ID; echo "<button onclick=\"likeButton()\" p style=\"font-size:10px\" id=\"likeButton\">LIKE</button>"; } public function button_js(){ wp_enqueue_script( 'likeButton', plugins_url( '/like.js', __FILE__ ),array('jquery')); wp_localize_script('likeButton', 'my_ajax_object', array( 'ajax_url' =>admin_url('admin-ajax.php'))); wp_localize_script('likeButton', 'new_ajax_object', array( 'ajax_url' =>admin_url('admin-ajax.php'))); } public function increment_like() { echo $this->ID."test"; //I only see test /* irrelevant code*/ } } //* Initiate the class and hook into init add_action( 'init', [ $wpse_263293 = new wpse_263293(), 'init' ] ); ?> ```
Yes, this is a [new Yoast SEO feature](https://yoast.com/what-is-cornerstone-content/). It's a checkbox, so as long a you don't select it in the SEO-metabox, the value will be zero/empty. I presume it's overwritten every time the post is saved, hence it won't delete or accept a value written directly into the database table. There doesn't seem to be a setting in the dashboard, so in order to disable it you'll have to search the code for a filter or contact Yoast.
263,307
<p>I'm new to writing rewrite rules in WordPress and I want to make sure I'm not going about this the wrong way.</p> <p><strong>My goal</strong>: to use random numbers and letters as the URL ending for my custom post type <code>project</code> pages</p> <p>My code below is what I've attempted so far ...</p> <h3>functions.php</h3> <pre><code>// Create a random string and save it to the post for the URL ending add_action('save_post','add_url_id'); function add_url_id( $id, $post ){ $url_id = uniqid(); if ( isset( $post-&gt;url_id ) ) { return; } update_post_meta($id, 'url_id', $url_id ); } // Let WordPress know about my custom query variable url_id add_filter( 'query_vars', 'add_query_var' ); function add_query_var( $vars ) { $vars[] = 'url_id'; return $vars; } // My rewrite rule to search for the custom post with the URL's same url_id add_action('init', 'custom_rewrite_rule', 10, 0); function custom_rewrite_rule() { add_rewrite_rule( '^projects/([0-9a-z]+)/?', 'index.php?post_type=project&amp;url_id=$matches[1]', 'top'); } </code></pre> <p>When I <code>var_dump</code> my post on the individual custom post pages, I can see that they do have a value in their <code>url_id</code> field. When I save this code and flush the permalinks cache, I find that I'm redirected to <code>http://example.com/projects/&lt;string of numbers and letters&gt;</code>, but I only see the homepage instead of the custom post. I'm guessing the issue has to do with no results being returned by my <code>url_id</code> variable, but I'm not sure why my query doesn't have any result since I do have posts with this field populated.</p> <p><strong>Edit:</strong></p> <p>This is what I'm currently seeing in the Rewrite Analyzer plugin <a href="https://i.stack.imgur.com/vr3aU.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vr3aU.png" alt="rewrite results" /></a></p> <p>I'm also not finding that my URLs are being re-written at all at the moment, so I am not as far along as I had expected.</p>
[ { "answer_id": 263290, "author": "rudtek", "author_id": 77767, "author_profile": "https://wordpress.stackexchange.com/users/77767", "pm_score": 0, "selected": false, "text": "<p>The best way to figure out what is going on is to disable your plugins and see if it goes away.</p>\n\n<p>Rename your plugins folder to something else. Does this fix the issue?</p>\n\n<p>If it does rename the plugin folder back to plugins. Now you have to enable 1 by 1 each plugin and check if all still is working.\nWhen all seems okay then at least you found a solution but still have no answer about the 'why was it not working' but it would be too far to dig into that issue but at least now you can take some time to find out what is causing that field to appear.</p>\n\n<p>Are you using x theme? It could be that theme itself so try switching themes as well.</p>\n" }, { "answer_id": 263309, "author": "cjbj", "author_id": 75495, "author_profile": "https://wordpress.stackexchange.com/users/75495", "pm_score": 3, "selected": true, "text": "<p>Yes, this is a <a href=\"https://yoast.com/what-is-cornerstone-content/\" rel=\"nofollow noreferrer\">new Yoast SEO feature</a>. It's a checkbox, so as long a you don't select it in the SEO-metabox, the value will be zero/empty. I presume it's overwritten every time the post is saved, hence it won't delete or accept a value written directly into the database table.</p>\n\n<p>There doesn't seem to be a setting in the dashboard, so in order to disable it you'll have to search the code for a filter or contact Yoast.</p>\n" }, { "answer_id": 263496, "author": "Nathalie", "author_id": 117573, "author_profile": "https://wordpress.stackexchange.com/users/117573", "pm_score": 0, "selected": false, "text": "<p>Yes it seems to be SEO Yoast, any posts done with the updated plugin active will add the text, deactivating the plugin and creating a new post does not produce the unwanted <code>yst_is_cornerstone</code>, however, it still remains on the posts done with the plugin active, how strange and annoying!</p>\n" }, { "answer_id": 263543, "author": "Amjad", "author_id": 34472, "author_profile": "https://wordpress.stackexchange.com/users/34472", "pm_score": 1, "selected": false, "text": "<p>To disable that custom field, go to <strong>Yoast SEO > Dashboard > Features.</strong></p>\n\n<p><a href=\"https://i.stack.imgur.com/DX79A.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/DX79A.png\" alt=\"Pic of screenshot\"></a></p>\n\n<p>Read more about <a href=\"https://yoast.com/what-is-cornerstone-content/#utm_source=dashboard-feature-tab&amp;utm_medium=inline-help&amp;utm_campaign=cornerstone-content&amp;utm_content=4.6\" rel=\"nofollow noreferrer\">cornerstore content</a></p>\n" } ]
2017/04/11
[ "https://wordpress.stackexchange.com/questions/263307", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/113595/" ]
I'm new to writing rewrite rules in WordPress and I want to make sure I'm not going about this the wrong way. **My goal**: to use random numbers and letters as the URL ending for my custom post type `project` pages My code below is what I've attempted so far ... ### functions.php ``` // Create a random string and save it to the post for the URL ending add_action('save_post','add_url_id'); function add_url_id( $id, $post ){ $url_id = uniqid(); if ( isset( $post->url_id ) ) { return; } update_post_meta($id, 'url_id', $url_id ); } // Let WordPress know about my custom query variable url_id add_filter( 'query_vars', 'add_query_var' ); function add_query_var( $vars ) { $vars[] = 'url_id'; return $vars; } // My rewrite rule to search for the custom post with the URL's same url_id add_action('init', 'custom_rewrite_rule', 10, 0); function custom_rewrite_rule() { add_rewrite_rule( '^projects/([0-9a-z]+)/?', 'index.php?post_type=project&url_id=$matches[1]', 'top'); } ``` When I `var_dump` my post on the individual custom post pages, I can see that they do have a value in their `url_id` field. When I save this code and flush the permalinks cache, I find that I'm redirected to `http://example.com/projects/<string of numbers and letters>`, but I only see the homepage instead of the custom post. I'm guessing the issue has to do with no results being returned by my `url_id` variable, but I'm not sure why my query doesn't have any result since I do have posts with this field populated. **Edit:** This is what I'm currently seeing in the Rewrite Analyzer plugin [![rewrite results](https://i.stack.imgur.com/vr3aU.png)](https://i.stack.imgur.com/vr3aU.png) I'm also not finding that my URLs are being re-written at all at the moment, so I am not as far along as I had expected.
Yes, this is a [new Yoast SEO feature](https://yoast.com/what-is-cornerstone-content/). It's a checkbox, so as long a you don't select it in the SEO-metabox, the value will be zero/empty. I presume it's overwritten every time the post is saved, hence it won't delete or accept a value written directly into the database table. There doesn't seem to be a setting in the dashboard, so in order to disable it you'll have to search the code for a filter or contact Yoast.
263,337
<p>I know this question has been asked before, and I've already referenced the following questions here:</p> <p><a href="https://wordpress.stackexchange.com/questions/233184/child-theme-not-overriding-parent-theme">Child Theme Not Overriding Parent Theme</a></p> <p><a href="https://wordpress.stackexchange.com/questions/92157/some-things-in-child-theme-css-not-overriding-parent">some things in child theme css not overriding parent</a> </p> <p><a href="https://wordpress.stackexchange.com/questions/43122/css-in-child-theme-not-overriding-the-parent-theme">CSS in child theme not overriding the parent theme [closed]</a> </p> <p><a href="https://wordpress.stackexchange.com/questions/157865/function-in-child-theme-not-overriding-parent-theme-function">Function in Child Theme not overriding Parent Theme function [duplicate]</a> </p> <p>None of these address my particular issue. </p> <p>The issue I am having is that the stylesheet for my parent theme isn't located in the traditional <code>themedirectory/style.css</code>. They did all the styling in <code>themedirectory/assets/css/main.css</code>. So I tried to create the child theme and added the following code to my <code>functions.php</code> file:</p> <pre><code>&lt;?php function my_theme_enqueue_styles() { $parent_style = 'maya-reloaded-style'; wp_enqueue_style( $parent_style, get_template_directory_uri() . 'assets/css/main.css' ); wp_enqueue_style( 'child-style', get_stylesheet_directory_uri() . '/style.css', array( $parent_style ), wp_get_theme()-&gt;get('Version') ); } add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' ); ?&gt; </code></pre> <p>I updated the directory of the parent theme to the location of the current parent theme, but I still have an issue of my new stylesheet not overwriting the parent's child theme. It seems like the parent's stylesheet is being loaded after the child style sheet. When I inspect the element with Firefox it shows that the parent stylesheet is overwriting the child stylesheet. </p> <p>What am I doing wrong and how can I fix this so the child stylesheet is loaded after the parent stylesheet? </p> <p><strong>UPDATE</strong></p> <p>Here is the <em>PARENT</em> (main.css) file:</p> <pre><code>/* Theme Name: Maya Reloaded Description: Onepage, Multipage and Mutipurpose WP Theme Theme URI: http://themeforest.net/user/unCommons/portfolio Author: unCommons Team Author URI: http://www.uncommons.pro Version: 1.1 License: GNU General Public License version 3.0 License URI: http://www.gnu.org/licenses/gpl-3.0.html Tags: one-column, two-columns, right-sidebar, fluid-layout, custom-menu, editor-style, featured-images, post-formats, translation-ready */ /* Main Style -&gt; assets/css/main.css */ </code></pre> <p>Here is the <em>CHILD</em> (style.css) file:</p> <pre><code>/* Theme Name: Maya Reloaded - Child Theme URI: http:www.girlpowerhour.com/Maya-child Description: Child theme for the Maya Reloaded theme Author: Me Author URI: http:www.virgsolutions.com Template: maya-reloaded Version: 2.0.0 License: GNU General Public License v2 or later License URI: http://www.gnu.org/licenses/gpl-2.0.html Tags: light, dark, two-columns, right-sidebar, responsive-layout, accessibility-ready, pink Text Domain: maya-reloaded-child */ body{ font-size:18px; } .larger-font{ font-size:18px; } .about-header{ font-size:24px; } /* Header */ .un-header-menu-white .main-menu li a{ color:#EF1066; } </code></pre>
[ { "answer_id": 263290, "author": "rudtek", "author_id": 77767, "author_profile": "https://wordpress.stackexchange.com/users/77767", "pm_score": 0, "selected": false, "text": "<p>The best way to figure out what is going on is to disable your plugins and see if it goes away.</p>\n\n<p>Rename your plugins folder to something else. Does this fix the issue?</p>\n\n<p>If it does rename the plugin folder back to plugins. Now you have to enable 1 by 1 each plugin and check if all still is working.\nWhen all seems okay then at least you found a solution but still have no answer about the 'why was it not working' but it would be too far to dig into that issue but at least now you can take some time to find out what is causing that field to appear.</p>\n\n<p>Are you using x theme? It could be that theme itself so try switching themes as well.</p>\n" }, { "answer_id": 263309, "author": "cjbj", "author_id": 75495, "author_profile": "https://wordpress.stackexchange.com/users/75495", "pm_score": 3, "selected": true, "text": "<p>Yes, this is a <a href=\"https://yoast.com/what-is-cornerstone-content/\" rel=\"nofollow noreferrer\">new Yoast SEO feature</a>. It's a checkbox, so as long a you don't select it in the SEO-metabox, the value will be zero/empty. I presume it's overwritten every time the post is saved, hence it won't delete or accept a value written directly into the database table.</p>\n\n<p>There doesn't seem to be a setting in the dashboard, so in order to disable it you'll have to search the code for a filter or contact Yoast.</p>\n" }, { "answer_id": 263496, "author": "Nathalie", "author_id": 117573, "author_profile": "https://wordpress.stackexchange.com/users/117573", "pm_score": 0, "selected": false, "text": "<p>Yes it seems to be SEO Yoast, any posts done with the updated plugin active will add the text, deactivating the plugin and creating a new post does not produce the unwanted <code>yst_is_cornerstone</code>, however, it still remains on the posts done with the plugin active, how strange and annoying!</p>\n" }, { "answer_id": 263543, "author": "Amjad", "author_id": 34472, "author_profile": "https://wordpress.stackexchange.com/users/34472", "pm_score": 1, "selected": false, "text": "<p>To disable that custom field, go to <strong>Yoast SEO > Dashboard > Features.</strong></p>\n\n<p><a href=\"https://i.stack.imgur.com/DX79A.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/DX79A.png\" alt=\"Pic of screenshot\"></a></p>\n\n<p>Read more about <a href=\"https://yoast.com/what-is-cornerstone-content/#utm_source=dashboard-feature-tab&amp;utm_medium=inline-help&amp;utm_campaign=cornerstone-content&amp;utm_content=4.6\" rel=\"nofollow noreferrer\">cornerstore content</a></p>\n" } ]
2017/04/12
[ "https://wordpress.stackexchange.com/questions/263337", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/39316/" ]
I know this question has been asked before, and I've already referenced the following questions here: [Child Theme Not Overriding Parent Theme](https://wordpress.stackexchange.com/questions/233184/child-theme-not-overriding-parent-theme) [some things in child theme css not overriding parent](https://wordpress.stackexchange.com/questions/92157/some-things-in-child-theme-css-not-overriding-parent) [CSS in child theme not overriding the parent theme [closed]](https://wordpress.stackexchange.com/questions/43122/css-in-child-theme-not-overriding-the-parent-theme) [Function in Child Theme not overriding Parent Theme function [duplicate]](https://wordpress.stackexchange.com/questions/157865/function-in-child-theme-not-overriding-parent-theme-function) None of these address my particular issue. The issue I am having is that the stylesheet for my parent theme isn't located in the traditional `themedirectory/style.css`. They did all the styling in `themedirectory/assets/css/main.css`. So I tried to create the child theme and added the following code to my `functions.php` file: ``` <?php function my_theme_enqueue_styles() { $parent_style = 'maya-reloaded-style'; wp_enqueue_style( $parent_style, get_template_directory_uri() . 'assets/css/main.css' ); wp_enqueue_style( 'child-style', get_stylesheet_directory_uri() . '/style.css', array( $parent_style ), wp_get_theme()->get('Version') ); } add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' ); ?> ``` I updated the directory of the parent theme to the location of the current parent theme, but I still have an issue of my new stylesheet not overwriting the parent's child theme. It seems like the parent's stylesheet is being loaded after the child style sheet. When I inspect the element with Firefox it shows that the parent stylesheet is overwriting the child stylesheet. What am I doing wrong and how can I fix this so the child stylesheet is loaded after the parent stylesheet? **UPDATE** Here is the *PARENT* (main.css) file: ``` /* Theme Name: Maya Reloaded Description: Onepage, Multipage and Mutipurpose WP Theme Theme URI: http://themeforest.net/user/unCommons/portfolio Author: unCommons Team Author URI: http://www.uncommons.pro Version: 1.1 License: GNU General Public License version 3.0 License URI: http://www.gnu.org/licenses/gpl-3.0.html Tags: one-column, two-columns, right-sidebar, fluid-layout, custom-menu, editor-style, featured-images, post-formats, translation-ready */ /* Main Style -> assets/css/main.css */ ``` Here is the *CHILD* (style.css) file: ``` /* Theme Name: Maya Reloaded - Child Theme URI: http:www.girlpowerhour.com/Maya-child Description: Child theme for the Maya Reloaded theme Author: Me Author URI: http:www.virgsolutions.com Template: maya-reloaded Version: 2.0.0 License: GNU General Public License v2 or later License URI: http://www.gnu.org/licenses/gpl-2.0.html Tags: light, dark, two-columns, right-sidebar, responsive-layout, accessibility-ready, pink Text Domain: maya-reloaded-child */ body{ font-size:18px; } .larger-font{ font-size:18px; } .about-header{ font-size:24px; } /* Header */ .un-header-menu-white .main-menu li a{ color:#EF1066; } ```
Yes, this is a [new Yoast SEO feature](https://yoast.com/what-is-cornerstone-content/). It's a checkbox, so as long a you don't select it in the SEO-metabox, the value will be zero/empty. I presume it's overwritten every time the post is saved, hence it won't delete or accept a value written directly into the database table. There doesn't seem to be a setting in the dashboard, so in order to disable it you'll have to search the code for a filter or contact Yoast.
263,348
<p>In WordPress whenever new blog post is created all post details need to be send to third party API. I'm using <strong>save_post</strong> hook for this but not sure whether it's getting called or not This is what I've done so far</p> <pre><code> add_action( 'save_post', 'new_blog_details_send'); function new_blog_details_send( $post_id ) { //getting blog post details// $blog_title = get_the_title( $post_id ); $blog_link = get_permalink( $post_id ); $blog_text = get_post_field('post_content', $post_id); ///Sending data to portal//// $post_url = 'http://example.com/blog_update'; $body = array( 'blog_title' =&gt; $blog_title, 'blog_link' =&gt; $blog_link, 'blog_text' =&gt; $blog_text ); //error_log($body); $request = new WP_Http(); $response = $request-&gt;post( $post_url, array( 'body' =&gt; $body ) ); } </code></pre> <p>Not sure how to log or debug in WordPress. Any help would be appreciated. Thanks in advance.</p>
[ { "answer_id": 263352, "author": "Stender", "author_id": 82677, "author_profile": "https://wordpress.stackexchange.com/users/82677", "pm_score": 2, "selected": false, "text": "<p>A quick way of debugging the save function before redirection - is to</p>\n<pre><code>die(print_r($post_id)); // or var_dump($post_id);\n</code></pre>\n<p>this will stop all PHP from continuing and is fast for small debugging where you don't need an entire log.</p>\n<p>throw that into your function, and see what happens in it - change the variable to see if you are getting what you are expecting.</p>\n<p>EDIT -----------</p>\n<p>what i mean is :</p>\n<pre><code>add_action( 'save_post', 'new_blog_details_send', 10, 1);\nfunction new_blog_details_send( $post_id ) {\n \n wp_die(print_r($post_id)); //just another way of stopping - for wordpress\n\n ///Getting blog post details///\n $blog_title = get_the_title( $post_id );\n $blog_link = get_permalink( $post_id ); \n $blog_text = get_post_field('post_content', $post_id);\n\n ///Sending data to portal////\n $post_url = 'http://example.com/blog_update';\n $body = array(\n 'blog_title' =&gt; $blog_title,\n 'blog_link' =&gt; $blog_link,\n 'blog_text' =&gt; $blog_text\n );\n\n //error_log($body);\n\n $request = new WP_Http();\n $response = $request-&gt;post( $post_url, array( 'body' =&gt; $body ) );\n\n}\n</code></pre>\n<p>If it is still running normally after you put this in, the function is not called.</p>\n" }, { "answer_id": 263354, "author": "Aniruddha Gawade", "author_id": 101818, "author_profile": "https://wordpress.stackexchange.com/users/101818", "pm_score": 0, "selected": false, "text": "<p>Try adding priority and parameter count to your <code>add_action</code> function.</p>\n\n<p>I sometimes get same issue of hook not running when I don't specify parameters when parameters are used.</p>\n\n<pre><code>add_action( 'save_post', 'new_blog_details_send', 10, 1);\n</code></pre>\n\n<p>Where 10 is the priority, and 1 is the \"accepted arguments\" for the function</p>\n" } ]
2017/04/12
[ "https://wordpress.stackexchange.com/questions/263348", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/117465/" ]
In WordPress whenever new blog post is created all post details need to be send to third party API. I'm using **save\_post** hook for this but not sure whether it's getting called or not This is what I've done so far ``` add_action( 'save_post', 'new_blog_details_send'); function new_blog_details_send( $post_id ) { //getting blog post details// $blog_title = get_the_title( $post_id ); $blog_link = get_permalink( $post_id ); $blog_text = get_post_field('post_content', $post_id); ///Sending data to portal//// $post_url = 'http://example.com/blog_update'; $body = array( 'blog_title' => $blog_title, 'blog_link' => $blog_link, 'blog_text' => $blog_text ); //error_log($body); $request = new WP_Http(); $response = $request->post( $post_url, array( 'body' => $body ) ); } ``` Not sure how to log or debug in WordPress. Any help would be appreciated. Thanks in advance.
A quick way of debugging the save function before redirection - is to ``` die(print_r($post_id)); // or var_dump($post_id); ``` this will stop all PHP from continuing and is fast for small debugging where you don't need an entire log. throw that into your function, and see what happens in it - change the variable to see if you are getting what you are expecting. EDIT ----------- what i mean is : ``` add_action( 'save_post', 'new_blog_details_send', 10, 1); function new_blog_details_send( $post_id ) { wp_die(print_r($post_id)); //just another way of stopping - for wordpress ///Getting blog post details/// $blog_title = get_the_title( $post_id ); $blog_link = get_permalink( $post_id ); $blog_text = get_post_field('post_content', $post_id); ///Sending data to portal//// $post_url = 'http://example.com/blog_update'; $body = array( 'blog_title' => $blog_title, 'blog_link' => $blog_link, 'blog_text' => $blog_text ); //error_log($body); $request = new WP_Http(); $response = $request->post( $post_url, array( 'body' => $body ) ); } ``` If it is still running normally after you put this in, the function is not called.
263,349
<p>I have update woo-commerce in latest version 3.0.1 Because of which some of my functions have been closed like confirm password fields on check out page. my function is</p> <pre><code>add_action( 'woocommerce_checkout_init', 'wc_add_confirm_password_checkout', 10, 1 ); function wc_add_confirm_password_checkout( $checkout ) { if ( get_option( 'woocommerce_registration_generate_password' ) == 'no' ) { $checkout-&gt;checkout_fields['account']['account_password2'] = array( 'type' =&gt; 'password', 'label' =&gt; __( 'Verify password', 'woocommerce' ), 'required' =&gt; true, 'placeholder' =&gt; _x( 'Password', 'placeholder', 'woocommerce' ) ); } } // Check the password and confirm password fields match before allow checkout to proceed. add_action( 'woocommerce_after_checkout_validation', 'wc_check_confirm_password_matches_checkout', 10, 2 ); function wc_check_confirm_password_matches_checkout( $posted ) { $checkout = WC()-&gt;checkout; if ( ! is_user_logged_in() &amp;&amp; ( $checkout-&gt;must_create_account || ! empty( $posted['createaccount'] ) ) ) { if ( strcmp( $posted['account_password'], $posted['account_password2'] ) !== 0 ) { wc_add_notice( __( 'Passwords do not match.', 'woocommerce' ), 'error' ); } } } </code></pre> <p>I have added these code on function.php file in current theme. How can i correct my function.</p>
[ { "answer_id": 263984, "author": "Matt Aitch", "author_id": 117890, "author_profile": "https://wordpress.stackexchange.com/users/117890", "pm_score": 3, "selected": true, "text": "<p>Please try the modified code below, working on WordPress 4.7.3 with WooCommerce 3.0.3.</p>\n\n<p>Matt.</p>\n\n<pre><code>/**\n * Add a confirm password field to the checkout registration form.\n */\nfunction o_woocommerce_confirm_password_checkout( $checkout ) {\n if ( get_option( 'woocommerce_registration_generate_password' ) == 'no' ) {\n\n $fields = $checkout-&gt;get_checkout_fields();\n\n $fields['account']['account_confirm_password'] = array(\n 'type' =&gt; 'password',\n 'label' =&gt; __( 'Confirm password', 'woocommerce' ),\n 'required' =&gt; true,\n 'placeholder' =&gt; _x( 'Confirm Password', 'placeholder', 'woocommerce' )\n );\n\n $checkout-&gt;__set( 'checkout_fields', $fields );\n }\n}\nadd_action( 'woocommerce_checkout_init', 'o_woocommerce_confirm_password_checkout', 10, 1 );\n\n/**\n * Validate that the two password fields match.\n */\nfunction o_woocommerce_confirm_password_validation( $posted ) {\n $checkout = WC()-&gt;checkout;\n if ( ! is_user_logged_in() &amp;&amp; ( $checkout-&gt;must_create_account || ! empty( $posted['createaccount'] ) ) ) {\n if ( strcmp( $posted['account_password'], $posted['account_confirm_password'] ) !== 0 ) {\n wc_add_notice( __( 'Passwords do not match.', 'woocommerce' ), 'error' );\n }\n }\n}\nadd_action( 'woocommerce_after_checkout_validation', 'o_woocommerce_confirm_password_validation', 10, 2 );\n</code></pre>\n" }, { "answer_id": 292249, "author": "Canowyrms", "author_id": 135613, "author_profile": "https://wordpress.stackexchange.com/users/135613", "pm_score": 1, "selected": false, "text": "<p>I'm trying this on a couple different sites, both are running WordPress 4.9.2. One site is running WooCommerce 3.1.2 and the other is WooCommerce 3.2.1.</p>\n\n<p>I tried using Matt Aitch's code, but for some reason or another, it wasn't working for me. Here is the solution I came up with (all of this code resides in your theme's functions.php file):</p>\n\n<pre><code>// Adds password-confirmation to user registration page (/my-account/)\nadd_filter( 'woocommerce_register_form', 'pixel_registration_password_repeat', 9 );\n// Priority 10 will probably work for you, but in my situation, \n// a reCAPTCHA element loads between the password boxes, so I used 9.\nfunction pixel_registration_password_repeat() {\n ?&gt;\n &lt;p class=\"woocommerce-form-row woocommerce-form-row--wide form-row form-row-wide\"&gt;\n &lt;label for=\"password_confirm\"&gt;&lt;?php _e( 'Confirm Password', 'woocommerce' ); ?&gt; &lt;span class=\"required\"&gt;*&lt;/span&gt;&lt;/label&gt;\n &lt;input type=\"password\" class=\"input-text\" name=\"password_confirm\" id=\"password_confirm\"&gt;\n &lt;/p&gt;\n &lt;?php\n}\n\n\n// Adds password-confirmation to user registration during checkout phase\nadd_filter( 'woocommerce_checkout_fields', 'pixel_checkout_registration_password_repeat', 10, 1 );\nfunction pixel_checkout_registration_password_repeat( $fields ) {\n if ( 'no' === get_option( 'woocommerce_registration_generate_password' ) ) {\n $fields['account']['account_password_confirm'] = array(\n 'type' =&gt; 'password',\n 'label' =&gt; __( 'Confirm password', 'woocommerce' ),\n 'required' =&gt; true,\n 'placeholder' =&gt; esc_attr__( 'Confirm password', 'woocommerce' )\n );\n }\n return $fields;\n}\n\n\n// Form-specific password validation step.\nadd_filter( 'woocommerce_registration_errors', 'pixel_validate_registration_passwords', 10, 3 );\nfunction pixel_validate_registration_passwords( $errors, $username, $email ) {\n global $woocommerce;\n extract( $_POST );\n\n if ( isset( $password ) || ! empty( $password ) ) {\n // This code runs for new user registration on the /my-account/ page.\n if ( strcmp( $password, $password_confirm ) !== 0 ) {\n return new WP_error( 'registration-error', __( 'Passwords do not match', 'woocommerce' ) );\n }\n } else if ( isset( $account_password ) || ! empty( $account_password ) ) {\n // This code runs for new user registration during checkout process.\n if ( strcmp( $account_password, $account_password_confirm ) !== 0 ) {\n return new WP_error( 'registration-error', __( 'Passwords do not match', 'woocommerce' ) );\n }\n }\n\n return $errors;\n}\n</code></pre>\n" }, { "answer_id": 381107, "author": "James Miller", "author_id": 141358, "author_profile": "https://wordpress.stackexchange.com/users/141358", "pm_score": 2, "selected": false, "text": "<p>I had an issue on latest WordPress 5.6 and Woocommerce 4.8.\nThe call in the line below is deprecated.</p>\n<pre><code>$fields = $checkout-&gt;get_checkout_fields();\n</code></pre>\n<p>This is by now a working version. But the <code>$_POST</code> access is not the best solution. A more clean way would be to access the <code>password_confirm</code> value from the <code>$posted</code> variable in the last function <code>sn_woocommerce_confirm_password_validation</code>.</p>\n<pre><code>/**\n * Add a confirm password field to the checkout registration form.\n */\nfunction sn_woocommerce_confirm_password_checkout( $checkout ) {\n if ( get_option( 'woocommerce_registration_generate_password' ) == 'no' ) {\n\n woocommerce_form_field(\n 'account_password_confirm',\n array(\n 'type' =&gt; 'password',\n 'label' =&gt; __( 'Passwort confirmation', 'woocommerce' ),\n 'required' =&gt; true,\n 'placeholder' =&gt; _x( 'Passwort repeat', 'placeholder', 'woocommerce' )\n ),\n $checkout-&gt;get_value( 'account_password_confirm' )\n );\n\n }\n}\n//add_action( 'woocommerce_checkout_init', 'sn_woocommerce_confirm_password_checkout', 10, 1 );\nadd_action( 'woocommerce_after_order_notes', 'sn_woocommerce_confirm_password_checkout', 10, 1 );\n\nfunction sn_woocommerce_save_password_confirm( $order_id ) {\n if ( ! empty( $_POST['account_password_confirm'] ) ) {\n update_post_meta( $order_id, 'account_password_confirm', sanitize_text_field( $_POST['account_password_confirm'] ) );\n }\n}\nadd_action( 'woocommerce_checkout_update_order_meta', 'sn_woocommerce_save_password_confirm');\n\n/**\n * Validate that the two password fields match.\n */\nfunction sn_woocommerce_confirm_password_validation( $posted ) {\n $checkout = WC()-&gt;checkout;\n if ( ! is_user_logged_in() &amp;&amp; ( $checkout-&gt;must_create_account || ! empty( $posted['createaccount'] ) ) ) {\n if ( strcmp( $posted['account_password'], $_POST['account_password_confirm'] ) !== 0 ) {\n wc_add_notice( __( 'Passwords are not the same.', 'woocommerce' ), 'error' );\n }\n }\n}\nadd_action( 'woocommerce_after_checkout_validation', 'sn_woocommerce_confirm_password_validation', 10, 2 );\n</code></pre>\n" } ]
2017/04/12
[ "https://wordpress.stackexchange.com/questions/263349", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/98743/" ]
I have update woo-commerce in latest version 3.0.1 Because of which some of my functions have been closed like confirm password fields on check out page. my function is ``` add_action( 'woocommerce_checkout_init', 'wc_add_confirm_password_checkout', 10, 1 ); function wc_add_confirm_password_checkout( $checkout ) { if ( get_option( 'woocommerce_registration_generate_password' ) == 'no' ) { $checkout->checkout_fields['account']['account_password2'] = array( 'type' => 'password', 'label' => __( 'Verify password', 'woocommerce' ), 'required' => true, 'placeholder' => _x( 'Password', 'placeholder', 'woocommerce' ) ); } } // Check the password and confirm password fields match before allow checkout to proceed. add_action( 'woocommerce_after_checkout_validation', 'wc_check_confirm_password_matches_checkout', 10, 2 ); function wc_check_confirm_password_matches_checkout( $posted ) { $checkout = WC()->checkout; if ( ! is_user_logged_in() && ( $checkout->must_create_account || ! empty( $posted['createaccount'] ) ) ) { if ( strcmp( $posted['account_password'], $posted['account_password2'] ) !== 0 ) { wc_add_notice( __( 'Passwords do not match.', 'woocommerce' ), 'error' ); } } } ``` I have added these code on function.php file in current theme. How can i correct my function.
Please try the modified code below, working on WordPress 4.7.3 with WooCommerce 3.0.3. Matt. ``` /** * Add a confirm password field to the checkout registration form. */ function o_woocommerce_confirm_password_checkout( $checkout ) { if ( get_option( 'woocommerce_registration_generate_password' ) == 'no' ) { $fields = $checkout->get_checkout_fields(); $fields['account']['account_confirm_password'] = array( 'type' => 'password', 'label' => __( 'Confirm password', 'woocommerce' ), 'required' => true, 'placeholder' => _x( 'Confirm Password', 'placeholder', 'woocommerce' ) ); $checkout->__set( 'checkout_fields', $fields ); } } add_action( 'woocommerce_checkout_init', 'o_woocommerce_confirm_password_checkout', 10, 1 ); /** * Validate that the two password fields match. */ function o_woocommerce_confirm_password_validation( $posted ) { $checkout = WC()->checkout; if ( ! is_user_logged_in() && ( $checkout->must_create_account || ! empty( $posted['createaccount'] ) ) ) { if ( strcmp( $posted['account_password'], $posted['account_confirm_password'] ) !== 0 ) { wc_add_notice( __( 'Passwords do not match.', 'woocommerce' ), 'error' ); } } } add_action( 'woocommerce_after_checkout_validation', 'o_woocommerce_confirm_password_validation', 10, 2 ); ```
263,355
<p>I was pulling something from <code>https://CJSHayward.com/books/</code> and found that it did not have any of the dynamically arranged titles. When I went to edit the page, I found a surprise.</p> <p>I had originally entered a hand-typed:</p> <pre><code>&lt;script src="/wp-content/javascripts/wrapped-book-table.cgi"&gt;&lt;/script&gt; </code></pre> <p>However, while the SCRIPT tag was still there, it was mangled:</p> <pre><code>&lt;script src="/wp-content/javascripts/wrapped-book-table.cgi" type="mce-no/type" data-mce-src="/wp-content/javascripts/wrapped-book-table.cgi"&gt;&lt;/script&gt; </code></pre> <p>What converted the first into the second one, and what does "mce" refer to? This is not something I would have entered, and the type of "mce-no/type" probably defeated the JavaScript being treated in JavaScript.</p> <p>(And what can I do to prevent the transformaation from recurring?)</p>
[ { "answer_id": 263984, "author": "Matt Aitch", "author_id": 117890, "author_profile": "https://wordpress.stackexchange.com/users/117890", "pm_score": 3, "selected": true, "text": "<p>Please try the modified code below, working on WordPress 4.7.3 with WooCommerce 3.0.3.</p>\n\n<p>Matt.</p>\n\n<pre><code>/**\n * Add a confirm password field to the checkout registration form.\n */\nfunction o_woocommerce_confirm_password_checkout( $checkout ) {\n if ( get_option( 'woocommerce_registration_generate_password' ) == 'no' ) {\n\n $fields = $checkout-&gt;get_checkout_fields();\n\n $fields['account']['account_confirm_password'] = array(\n 'type' =&gt; 'password',\n 'label' =&gt; __( 'Confirm password', 'woocommerce' ),\n 'required' =&gt; true,\n 'placeholder' =&gt; _x( 'Confirm Password', 'placeholder', 'woocommerce' )\n );\n\n $checkout-&gt;__set( 'checkout_fields', $fields );\n }\n}\nadd_action( 'woocommerce_checkout_init', 'o_woocommerce_confirm_password_checkout', 10, 1 );\n\n/**\n * Validate that the two password fields match.\n */\nfunction o_woocommerce_confirm_password_validation( $posted ) {\n $checkout = WC()-&gt;checkout;\n if ( ! is_user_logged_in() &amp;&amp; ( $checkout-&gt;must_create_account || ! empty( $posted['createaccount'] ) ) ) {\n if ( strcmp( $posted['account_password'], $posted['account_confirm_password'] ) !== 0 ) {\n wc_add_notice( __( 'Passwords do not match.', 'woocommerce' ), 'error' );\n }\n }\n}\nadd_action( 'woocommerce_after_checkout_validation', 'o_woocommerce_confirm_password_validation', 10, 2 );\n</code></pre>\n" }, { "answer_id": 292249, "author": "Canowyrms", "author_id": 135613, "author_profile": "https://wordpress.stackexchange.com/users/135613", "pm_score": 1, "selected": false, "text": "<p>I'm trying this on a couple different sites, both are running WordPress 4.9.2. One site is running WooCommerce 3.1.2 and the other is WooCommerce 3.2.1.</p>\n\n<p>I tried using Matt Aitch's code, but for some reason or another, it wasn't working for me. Here is the solution I came up with (all of this code resides in your theme's functions.php file):</p>\n\n<pre><code>// Adds password-confirmation to user registration page (/my-account/)\nadd_filter( 'woocommerce_register_form', 'pixel_registration_password_repeat', 9 );\n// Priority 10 will probably work for you, but in my situation, \n// a reCAPTCHA element loads between the password boxes, so I used 9.\nfunction pixel_registration_password_repeat() {\n ?&gt;\n &lt;p class=\"woocommerce-form-row woocommerce-form-row--wide form-row form-row-wide\"&gt;\n &lt;label for=\"password_confirm\"&gt;&lt;?php _e( 'Confirm Password', 'woocommerce' ); ?&gt; &lt;span class=\"required\"&gt;*&lt;/span&gt;&lt;/label&gt;\n &lt;input type=\"password\" class=\"input-text\" name=\"password_confirm\" id=\"password_confirm\"&gt;\n &lt;/p&gt;\n &lt;?php\n}\n\n\n// Adds password-confirmation to user registration during checkout phase\nadd_filter( 'woocommerce_checkout_fields', 'pixel_checkout_registration_password_repeat', 10, 1 );\nfunction pixel_checkout_registration_password_repeat( $fields ) {\n if ( 'no' === get_option( 'woocommerce_registration_generate_password' ) ) {\n $fields['account']['account_password_confirm'] = array(\n 'type' =&gt; 'password',\n 'label' =&gt; __( 'Confirm password', 'woocommerce' ),\n 'required' =&gt; true,\n 'placeholder' =&gt; esc_attr__( 'Confirm password', 'woocommerce' )\n );\n }\n return $fields;\n}\n\n\n// Form-specific password validation step.\nadd_filter( 'woocommerce_registration_errors', 'pixel_validate_registration_passwords', 10, 3 );\nfunction pixel_validate_registration_passwords( $errors, $username, $email ) {\n global $woocommerce;\n extract( $_POST );\n\n if ( isset( $password ) || ! empty( $password ) ) {\n // This code runs for new user registration on the /my-account/ page.\n if ( strcmp( $password, $password_confirm ) !== 0 ) {\n return new WP_error( 'registration-error', __( 'Passwords do not match', 'woocommerce' ) );\n }\n } else if ( isset( $account_password ) || ! empty( $account_password ) ) {\n // This code runs for new user registration during checkout process.\n if ( strcmp( $account_password, $account_password_confirm ) !== 0 ) {\n return new WP_error( 'registration-error', __( 'Passwords do not match', 'woocommerce' ) );\n }\n }\n\n return $errors;\n}\n</code></pre>\n" }, { "answer_id": 381107, "author": "James Miller", "author_id": 141358, "author_profile": "https://wordpress.stackexchange.com/users/141358", "pm_score": 2, "selected": false, "text": "<p>I had an issue on latest WordPress 5.6 and Woocommerce 4.8.\nThe call in the line below is deprecated.</p>\n<pre><code>$fields = $checkout-&gt;get_checkout_fields();\n</code></pre>\n<p>This is by now a working version. But the <code>$_POST</code> access is not the best solution. A more clean way would be to access the <code>password_confirm</code> value from the <code>$posted</code> variable in the last function <code>sn_woocommerce_confirm_password_validation</code>.</p>\n<pre><code>/**\n * Add a confirm password field to the checkout registration form.\n */\nfunction sn_woocommerce_confirm_password_checkout( $checkout ) {\n if ( get_option( 'woocommerce_registration_generate_password' ) == 'no' ) {\n\n woocommerce_form_field(\n 'account_password_confirm',\n array(\n 'type' =&gt; 'password',\n 'label' =&gt; __( 'Passwort confirmation', 'woocommerce' ),\n 'required' =&gt; true,\n 'placeholder' =&gt; _x( 'Passwort repeat', 'placeholder', 'woocommerce' )\n ),\n $checkout-&gt;get_value( 'account_password_confirm' )\n );\n\n }\n}\n//add_action( 'woocommerce_checkout_init', 'sn_woocommerce_confirm_password_checkout', 10, 1 );\nadd_action( 'woocommerce_after_order_notes', 'sn_woocommerce_confirm_password_checkout', 10, 1 );\n\nfunction sn_woocommerce_save_password_confirm( $order_id ) {\n if ( ! empty( $_POST['account_password_confirm'] ) ) {\n update_post_meta( $order_id, 'account_password_confirm', sanitize_text_field( $_POST['account_password_confirm'] ) );\n }\n}\nadd_action( 'woocommerce_checkout_update_order_meta', 'sn_woocommerce_save_password_confirm');\n\n/**\n * Validate that the two password fields match.\n */\nfunction sn_woocommerce_confirm_password_validation( $posted ) {\n $checkout = WC()-&gt;checkout;\n if ( ! is_user_logged_in() &amp;&amp; ( $checkout-&gt;must_create_account || ! empty( $posted['createaccount'] ) ) ) {\n if ( strcmp( $posted['account_password'], $_POST['account_password_confirm'] ) !== 0 ) {\n wc_add_notice( __( 'Passwords are not the same.', 'woocommerce' ), 'error' );\n }\n }\n}\nadd_action( 'woocommerce_after_checkout_validation', 'sn_woocommerce_confirm_password_validation', 10, 2 );\n</code></pre>\n" } ]
2017/04/12
[ "https://wordpress.stackexchange.com/questions/263355", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/87471/" ]
I was pulling something from `https://CJSHayward.com/books/` and found that it did not have any of the dynamically arranged titles. When I went to edit the page, I found a surprise. I had originally entered a hand-typed: ``` <script src="/wp-content/javascripts/wrapped-book-table.cgi"></script> ``` However, while the SCRIPT tag was still there, it was mangled: ``` <script src="/wp-content/javascripts/wrapped-book-table.cgi" type="mce-no/type" data-mce-src="/wp-content/javascripts/wrapped-book-table.cgi"></script> ``` What converted the first into the second one, and what does "mce" refer to? This is not something I would have entered, and the type of "mce-no/type" probably defeated the JavaScript being treated in JavaScript. (And what can I do to prevent the transformaation from recurring?)
Please try the modified code below, working on WordPress 4.7.3 with WooCommerce 3.0.3. Matt. ``` /** * Add a confirm password field to the checkout registration form. */ function o_woocommerce_confirm_password_checkout( $checkout ) { if ( get_option( 'woocommerce_registration_generate_password' ) == 'no' ) { $fields = $checkout->get_checkout_fields(); $fields['account']['account_confirm_password'] = array( 'type' => 'password', 'label' => __( 'Confirm password', 'woocommerce' ), 'required' => true, 'placeholder' => _x( 'Confirm Password', 'placeholder', 'woocommerce' ) ); $checkout->__set( 'checkout_fields', $fields ); } } add_action( 'woocommerce_checkout_init', 'o_woocommerce_confirm_password_checkout', 10, 1 ); /** * Validate that the two password fields match. */ function o_woocommerce_confirm_password_validation( $posted ) { $checkout = WC()->checkout; if ( ! is_user_logged_in() && ( $checkout->must_create_account || ! empty( $posted['createaccount'] ) ) ) { if ( strcmp( $posted['account_password'], $posted['account_confirm_password'] ) !== 0 ) { wc_add_notice( __( 'Passwords do not match.', 'woocommerce' ), 'error' ); } } } add_action( 'woocommerce_after_checkout_validation', 'o_woocommerce_confirm_password_validation', 10, 2 ); ```
263,447
<p>I'm trying to setup a custom <code>WP_Comment_Query</code> which is ordered by a meta key. (It might be worth mentioning that these comments are being retrieved with AJAX.)</p> <p>It all works fine, until I add in pagination into the query args. </p> <pre><code>$orderby = 'top-comments'; $args = array( 'post_id' =&gt; $post_id, 'type' =&gt; 'comment', 'status' =&gt; 'approve', 'hierarchical' =&gt; true ); if ( $orderby == 'top-comments' ) { $args['meta_key'] = 'comment_rating'; $args['orderby'] = 'meta_value_num'; $args['order'] = 'ASC'; } // $comments_query = new WP_Comment_Query; // $comments = $comments_query-&gt;query($args); // Works fine up until I add the pagination args $number = 5; $paged = 1; $args['number'] = $number; $args['paged'] = $paged; $comments_query = new WP_Comment_Query; $comments = $comments_query-&gt;query($args); // Gets the 5 latest comments, then orders those by meta_key </code></pre> <p>The results without the pagination args works perfect, and orders the comments exactly how I want it.</p> <p>However, once the number argument is set, it will retrieve the newest 5 comments, and then order them by <code>meta_key =&gt; 'comment_rating'</code>.</p> <p>The behaviour I expect is WP_Comment_Query <strong>first</strong> applying the orderby, and <strong>then</strong> returning the top 5 results.</p> <p>What am I doing wrong?</p>
[ { "answer_id": 263940, "author": "cjbj", "author_id": 75495, "author_profile": "https://wordpress.stackexchange.com/users/75495", "pm_score": 2, "selected": false, "text": "<p>If you take a look at the <a href=\"https://developer.wordpress.org/reference/classes/wp_comment_query/\" rel=\"nofollow noreferrer\"><code>wp_comment_query</code></a> class, you'll see there is no parameter <code>paged</code>. If you then look at <a href=\"https://developer.wordpress.org/reference/functions/wp_list_comments/\" rel=\"nofollow noreferrer\"><code>wp_list_comments</code></a>, which does allow pagination, you'll see that it calls a <a href=\"https://developer.wordpress.org/reference/classes/walker/paged_walk/\" rel=\"nofollow noreferrer\">lengthy walker function</a> to achieve comments pagination.</p>\n\n<p>So, it you want to do comments pagination yourself, you're up to some nontrivial programming. The basis will be the <code>number</code> and <code>offset</code> parameters available with <code>wp_comments_query</code>. If you want five comments per page you will need parameters like this:</p>\n\n<pre><code>page 1: offset=0, number=5\npage 2: offset=5, number=5\npage 2: offset=10, number=5\n</code></pre>\n\n<p>Basically, you'll have to get the page from the <code>query_var</code> of your page, then calculate the desired offset. Beware that there also is no <code>max_num_pages</code> parameter in <code>wp_comment_query</code>, so it will be difficult to know how many comments there are in your selection.</p>\n\n<p>It might be easier to just retrieve the full comment list every time and solve the pagination in PHP rather than in the query.</p>\n" }, { "answer_id": 263980, "author": "Swen", "author_id": 22588, "author_profile": "https://wordpress.stackexchange.com/users/22588", "pm_score": 3, "selected": true, "text": "<p>The goal was to paginate comments, showing comments with the highest <code>comment_rating</code> meta value first.</p>\n\n<p>Thanks to the answer of cjbj and the comments by Milo and birgire I figured out the rather unintuitive solution to the issue.</p>\n\n<p>By using <code>number</code>and <code>offset</code> I was able to make the results in the proper order, but pagination was strange, and each 5 posts were seemingly \"flipped\" on every page.</p>\n\n<p>Here is my workaround, resulting in a list of comments, starting with the highest rated first, and the lowest rated last.</p>\n\n<pre><code>$orderby = 'top-comments';\n\n$args = array(\n 'post_id' =&gt; $post_id,\n 'type' =&gt; 'comment',\n 'status' =&gt; 'approve',\n 'hierarchical' =&gt; true\n);\n\nif ( $orderby == 'top-comments' ) {\n $args['meta_key'] = 'comment_rating';\n $args['orderby'] = 'meta_value_num';\n $args['order'] = 'ASC';\n}\n\n// 5 Comments per page\n$comments_per_page = $number = 5; \n\n// Get the comment count to calculate the offset\n$comment_count = wp_count_comments($post_id)-&gt;approved;\n\n// Currently page 1 (set with AJAX in my case)\n$page = 1;\n\n// Rather unintuitively, we start with the total amount of comments and subtract\n// from that number \n// This is nessacary so that comments are displayed in the right order\n// (highest rated at the top, lowest rated at the bottom)\n\n// Calculate offset\n$offset = $comments_count - ($comments_per_page * $page);\n\n// Calculate offset for last page (to prevent comments being shown twice)\nif ( $offset &lt; 0 ) {\n // Calculate remaining amount of comments (always less than 5)\n $comments_last_page = $comments_count % $comments_per_page;\n\n // New offset calculated from the amount of remaining comments\n $offset = $offset + $comments_per_page - $comments_last_page;\n\n // Set how many comments the last page shows\n $number = $comments_last_page; \n}\n\n// Then we pass the $number and the $offset to our query args\n$args['number'] = $number;\n$args['offset'] = $offset;\n\n$comments_query = new WP_Comment_Query;\n$comments = $comments_query-&gt;query($args);\n\n// Result: 5 comments, starting with the highest rating at the top, and the\n// lowest rated at the bottom\n</code></pre>\n" } ]
2017/04/12
[ "https://wordpress.stackexchange.com/questions/263447", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/22588/" ]
I'm trying to setup a custom `WP_Comment_Query` which is ordered by a meta key. (It might be worth mentioning that these comments are being retrieved with AJAX.) It all works fine, until I add in pagination into the query args. ``` $orderby = 'top-comments'; $args = array( 'post_id' => $post_id, 'type' => 'comment', 'status' => 'approve', 'hierarchical' => true ); if ( $orderby == 'top-comments' ) { $args['meta_key'] = 'comment_rating'; $args['orderby'] = 'meta_value_num'; $args['order'] = 'ASC'; } // $comments_query = new WP_Comment_Query; // $comments = $comments_query->query($args); // Works fine up until I add the pagination args $number = 5; $paged = 1; $args['number'] = $number; $args['paged'] = $paged; $comments_query = new WP_Comment_Query; $comments = $comments_query->query($args); // Gets the 5 latest comments, then orders those by meta_key ``` The results without the pagination args works perfect, and orders the comments exactly how I want it. However, once the number argument is set, it will retrieve the newest 5 comments, and then order them by `meta_key => 'comment_rating'`. The behaviour I expect is WP\_Comment\_Query **first** applying the orderby, and **then** returning the top 5 results. What am I doing wrong?
The goal was to paginate comments, showing comments with the highest `comment_rating` meta value first. Thanks to the answer of cjbj and the comments by Milo and birgire I figured out the rather unintuitive solution to the issue. By using `number`and `offset` I was able to make the results in the proper order, but pagination was strange, and each 5 posts were seemingly "flipped" on every page. Here is my workaround, resulting in a list of comments, starting with the highest rated first, and the lowest rated last. ``` $orderby = 'top-comments'; $args = array( 'post_id' => $post_id, 'type' => 'comment', 'status' => 'approve', 'hierarchical' => true ); if ( $orderby == 'top-comments' ) { $args['meta_key'] = 'comment_rating'; $args['orderby'] = 'meta_value_num'; $args['order'] = 'ASC'; } // 5 Comments per page $comments_per_page = $number = 5; // Get the comment count to calculate the offset $comment_count = wp_count_comments($post_id)->approved; // Currently page 1 (set with AJAX in my case) $page = 1; // Rather unintuitively, we start with the total amount of comments and subtract // from that number // This is nessacary so that comments are displayed in the right order // (highest rated at the top, lowest rated at the bottom) // Calculate offset $offset = $comments_count - ($comments_per_page * $page); // Calculate offset for last page (to prevent comments being shown twice) if ( $offset < 0 ) { // Calculate remaining amount of comments (always less than 5) $comments_last_page = $comments_count % $comments_per_page; // New offset calculated from the amount of remaining comments $offset = $offset + $comments_per_page - $comments_last_page; // Set how many comments the last page shows $number = $comments_last_page; } // Then we pass the $number and the $offset to our query args $args['number'] = $number; $args['offset'] = $offset; $comments_query = new WP_Comment_Query; $comments = $comments_query->query($args); // Result: 5 comments, starting with the highest rating at the top, and the // lowest rated at the bottom ```
263,448
<p>I'm building a custom theme and I want to create a helper class for handling creation of metaboxes in admin panel. I have my class declared like this:</p> <p> <pre><code>namespace ci\wp; Metaboxes::init(); class Metaboxes { private static $instance; private static $post; private static $metaboxesPath = TEMPLATEPATH . "/config/metaboxes/"; static function init() { global $post; self::$post = &amp;$post; add_action( 'add_meta_boxes', [ __CLASS__, 'addMetabox' ], 10, 5 ); } // ADD METABOX static function addMetabox($id, $title, $post_type, $position, $priority) { if (file_exists(self::$metaboxesPath.$id.'.php')) { require_once(self::$metaboxesPath.$id.'.php'); add_meta_box($id, $title, 'do_'.$id, $post_type, $position, $priority); } } [...] </code></pre> <p>The problem is that when I want to use the addMetabox method, by writing <code>\ci\wp\Metaboxes::addMetabox('front_page_slide_settings', 'Slide settings', 'page', 'normal', 'high');</code> I get the following error:</p> <p><code>Fatal error: Uncaught Error: Call to undefined function ci\wp\add_meta_box() in [...]</code></p> <p>I tried several different methods of using add_action inside the class but no matter if it's a static class, singleton with add_action run at instantiation or a normal class with add_action in constructor, it always results in the said error.</p> <p>Is there a way to make it work? What am I doing wrong?</p>
[ { "answer_id": 263489, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 2, "selected": false, "text": "<p>You're actually calling the <code>add_meta_box()</code> function before it's defined, when you run this directly:</p>\n\n<pre><code>\\ci\\wp\\Metaboxes::addMetabox(\n 'front_page_slide_settings', \n 'Slide settings', \n 'page', \n 'normal', \n 'high'\n);\n</code></pre>\n\n<p>You don't mention where you run it, but it's too early or you run it in the front-end, where <code>add_meta_box()</code> is not defined.</p>\n\n<p>The <code>add_meta_box()</code> function is defined within this file:</p>\n\n<pre><code>/** WordPress Template Administration API */\nrequire_once(ABSPATH . 'wp-admin/includes/template.php');\n</code></pre>\n\n<p>Make sure to run your problematic snippet afterwards, e.g. within the <code>add_meta_boxes</code> action, like you do within the <code>Metaboxes::init()</code> call. </p>\n\n<p>The core <code>init</code> action, as an example, fires before that <em>Template Administration API</em> is loaded.</p>\n" }, { "answer_id": 263585, "author": "NoviQ", "author_id": 33112, "author_profile": "https://wordpress.stackexchange.com/users/33112", "pm_score": 0, "selected": false, "text": "<p>Thank you for help. I figure out exactly what I missed.</p>\n\n<p>I simply forgot to wrap all calls to the <code>addMetabox</code> static method inside a function that is hooked to <code>admin_init</code>. After I did that, everything work as expected. I don't even need to hook to <code>add_meta_boxes</code> inside the Metaboxes class.</p>\n\n<hr>\n\n<p>UPDATE: after spending some time figuring out how to quickly make other things like saving new post meta, it turned out that trying to simplify things like that using methods like that actually makes them more complicated. Adding metaboxes on admin_init hook makes it impossible to check edited post ID as at that moment the post var has no data. Lesson learned.</p>\n" } ]
2017/04/12
[ "https://wordpress.stackexchange.com/questions/263448", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/33112/" ]
I'm building a custom theme and I want to create a helper class for handling creation of metaboxes in admin panel. I have my class declared like this: ``` namespace ci\wp; Metaboxes::init(); class Metaboxes { private static $instance; private static $post; private static $metaboxesPath = TEMPLATEPATH . "/config/metaboxes/"; static function init() { global $post; self::$post = &$post; add_action( 'add_meta_boxes', [ __CLASS__, 'addMetabox' ], 10, 5 ); } // ADD METABOX static function addMetabox($id, $title, $post_type, $position, $priority) { if (file_exists(self::$metaboxesPath.$id.'.php')) { require_once(self::$metaboxesPath.$id.'.php'); add_meta_box($id, $title, 'do_'.$id, $post_type, $position, $priority); } } [...] ``` The problem is that when I want to use the addMetabox method, by writing `\ci\wp\Metaboxes::addMetabox('front_page_slide_settings', 'Slide settings', 'page', 'normal', 'high');` I get the following error: `Fatal error: Uncaught Error: Call to undefined function ci\wp\add_meta_box() in [...]` I tried several different methods of using add\_action inside the class but no matter if it's a static class, singleton with add\_action run at instantiation or a normal class with add\_action in constructor, it always results in the said error. Is there a way to make it work? What am I doing wrong?
You're actually calling the `add_meta_box()` function before it's defined, when you run this directly: ``` \ci\wp\Metaboxes::addMetabox( 'front_page_slide_settings', 'Slide settings', 'page', 'normal', 'high' ); ``` You don't mention where you run it, but it's too early or you run it in the front-end, where `add_meta_box()` is not defined. The `add_meta_box()` function is defined within this file: ``` /** WordPress Template Administration API */ require_once(ABSPATH . 'wp-admin/includes/template.php'); ``` Make sure to run your problematic snippet afterwards, e.g. within the `add_meta_boxes` action, like you do within the `Metaboxes::init()` call. The core `init` action, as an example, fires before that *Template Administration API* is loaded.
263,451
<p>I am trying to create a loop for a custom post type that first calculates how many posts it contains. If it only contains one post, it should simply display the content area of the post. If the post contains more than 1 post it should display the excerpts of all the posts in the loop. Has anyone figured this out?</p>
[ { "answer_id": 263452, "author": "Abdul Awal Uzzal", "author_id": 31449, "author_profile": "https://wordpress.stackexchange.com/users/31449", "pm_score": 1, "selected": false, "text": "<p>Please try this code &amp; let me know the result (I've not tested)</p>\n\n<pre><code>&lt;?php\n$post_query = new WP_Query('post_type=post'); // replace the post type with your post type key\n$total_posts_found = $post_query-&gt;found_posts;\n\nif($total_posts_found &lt; 2 &amp;&amp; $total_posts_found &gt; 0){\n if($post_query-&gt;have_posts()) : while($post_query-&gt;have_posts()) : $post_query-&gt;the_post();\n echo '&lt;h1&gt;'get_the_title().'&lt;/h1&gt;';\n echo get_the_content();\n endwhile;\n endif;\n wp_reset_postdata();\n} else {\n if($post_query-&gt;have_posts()) : while($post_query-&gt;have_posts()) : $post_query-&gt;the_post();\n echo '&lt;h1&gt;'get_the_title().'&lt;/h1&gt;';\n echo get_the_excerpt();\n endwhile;\n endif;\n wp_reset_postdata();\n}\n?&gt;\n</code></pre>\n" }, { "answer_id": 263455, "author": "Michael", "author_id": 4884, "author_profile": "https://wordpress.stackexchange.com/users/4884", "pm_score": 2, "selected": false, "text": "<p><a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Properties\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Class_Reference/WP_Query#Properties</a></p>\n\n<p><code>found_posts</code> is the total number of posts returned by the query.</p>\n\n<p>example code:</p>\n\n<pre><code>&lt;?php\n$args = array( 'post_type' =&gt; 'your_custom' );\n$custom_query = new WP_Query( $args );\n\nif( $custom_query-&gt;have_posts() ) {\n $number_of_posts = $custom_query-&gt;found_posts; \n\n while( $custom_query-&gt;have_posts() ) { \n $custom_query-&gt;the_post();\n\n if( $number_of_posts == 1 ) { \n the_content(); \n } else { \n the_excerpt(); \n }\n\n } \n\n wp_reset_postdata();\n\n}\n?&gt;\n</code></pre>\n" } ]
2017/04/13
[ "https://wordpress.stackexchange.com/questions/263451", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/117542/" ]
I am trying to create a loop for a custom post type that first calculates how many posts it contains. If it only contains one post, it should simply display the content area of the post. If the post contains more than 1 post it should display the excerpts of all the posts in the loop. Has anyone figured this out?
<https://codex.wordpress.org/Class_Reference/WP_Query#Properties> `found_posts` is the total number of posts returned by the query. example code: ``` <?php $args = array( 'post_type' => 'your_custom' ); $custom_query = new WP_Query( $args ); if( $custom_query->have_posts() ) { $number_of_posts = $custom_query->found_posts; while( $custom_query->have_posts() ) { $custom_query->the_post(); if( $number_of_posts == 1 ) { the_content(); } else { the_excerpt(); } } wp_reset_postdata(); } ?> ```
263,466
<p>In Plugins > Add New screen, the plugin table gets automatically filtered as I type the name of a plugin in the search field. Is it possible to disable this functionality and have the table update only after I hit return?</p> <p>The answer may lie in wp-admin/includes/plugin-install.php and/or wp-admin/includes/ajax-actions.php: wp_ajax_install_plugin().</p>
[ { "answer_id": 263452, "author": "Abdul Awal Uzzal", "author_id": 31449, "author_profile": "https://wordpress.stackexchange.com/users/31449", "pm_score": 1, "selected": false, "text": "<p>Please try this code &amp; let me know the result (I've not tested)</p>\n\n<pre><code>&lt;?php\n$post_query = new WP_Query('post_type=post'); // replace the post type with your post type key\n$total_posts_found = $post_query-&gt;found_posts;\n\nif($total_posts_found &lt; 2 &amp;&amp; $total_posts_found &gt; 0){\n if($post_query-&gt;have_posts()) : while($post_query-&gt;have_posts()) : $post_query-&gt;the_post();\n echo '&lt;h1&gt;'get_the_title().'&lt;/h1&gt;';\n echo get_the_content();\n endwhile;\n endif;\n wp_reset_postdata();\n} else {\n if($post_query-&gt;have_posts()) : while($post_query-&gt;have_posts()) : $post_query-&gt;the_post();\n echo '&lt;h1&gt;'get_the_title().'&lt;/h1&gt;';\n echo get_the_excerpt();\n endwhile;\n endif;\n wp_reset_postdata();\n}\n?&gt;\n</code></pre>\n" }, { "answer_id": 263455, "author": "Michael", "author_id": 4884, "author_profile": "https://wordpress.stackexchange.com/users/4884", "pm_score": 2, "selected": false, "text": "<p><a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Properties\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Class_Reference/WP_Query#Properties</a></p>\n\n<p><code>found_posts</code> is the total number of posts returned by the query.</p>\n\n<p>example code:</p>\n\n<pre><code>&lt;?php\n$args = array( 'post_type' =&gt; 'your_custom' );\n$custom_query = new WP_Query( $args );\n\nif( $custom_query-&gt;have_posts() ) {\n $number_of_posts = $custom_query-&gt;found_posts; \n\n while( $custom_query-&gt;have_posts() ) { \n $custom_query-&gt;the_post();\n\n if( $number_of_posts == 1 ) { \n the_content(); \n } else { \n the_excerpt(); \n }\n\n } \n\n wp_reset_postdata();\n\n}\n?&gt;\n</code></pre>\n" } ]
2017/04/13
[ "https://wordpress.stackexchange.com/questions/263466", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/14380/" ]
In Plugins > Add New screen, the plugin table gets automatically filtered as I type the name of a plugin in the search field. Is it possible to disable this functionality and have the table update only after I hit return? The answer may lie in wp-admin/includes/plugin-install.php and/or wp-admin/includes/ajax-actions.php: wp\_ajax\_install\_plugin().
<https://codex.wordpress.org/Class_Reference/WP_Query#Properties> `found_posts` is the total number of posts returned by the query. example code: ``` <?php $args = array( 'post_type' => 'your_custom' ); $custom_query = new WP_Query( $args ); if( $custom_query->have_posts() ) { $number_of_posts = $custom_query->found_posts; while( $custom_query->have_posts() ) { $custom_query->the_post(); if( $number_of_posts == 1 ) { the_content(); } else { the_excerpt(); } } wp_reset_postdata(); } ?> ```
263,470
<p>I'm trying to figure out how to let Wordpress update on my server, without needing FTP credentials. In <code>/etc/php/7.0/fpm/pool.d/www.conf</code> I have:</p> <pre><code>listen.owner = www-data listen.group = www-data </code></pre> <p>The problem I think is the way VestaCP is setup with the files:</p> <pre><code>root@com:/home/rachel/web/site.co.uk/public_shtml# ls -lh total 243M drwxrwxr-x 11 rachel rachel 4.0K Feb 3 2016 admin drwxrwxr-x 2 rachel rachel 4.0K Apr 12 09:14 cgi-bin drwxrwxr-x 3 rachel rachel 4.0K Jan 28 2016 dir -rw-rw-r-- 1 rachel rachel 418 Sep 25 2013 index.php -rw-r--r-- 1 rachel rachel 2.1K Apr 6 09:15 optimize.cgi drwxr-x--x 2 rachel rachel 4.0K Apr 12 09:12 public_shtml </code></pre> <p>the "owner" of them is actually the user's account username. I'm <strong>sure</strong> this must be possible (otherwise every file has to be owned by www-data, which causes all kinds of other issues)</p> <p>Am I just being stupid?</p> <p><strong>UPDATE:</strong></p> <p>As suggested, I've tried:</p> <p><code>sudo usermod -aG www-data rachel</code></p> <p>Unfortunately I still get the error:</p> <pre><code>PASS: Your WordPress install can communicate with WordPress.org securely. PASS: No version control systems were detected. FAIL: Your installation of WordPress prompts for FTP credentials to perform updates. (Your site is performing updates over FTP due to file ownership. Talk to your hosting company.) </code></pre>
[ { "answer_id": 263479, "author": "Niels van Renselaar", "author_id": 67313, "author_profile": "https://wordpress.stackexchange.com/users/67313", "pm_score": 1, "selected": false, "text": "<p>Shouldn't u add rachel to the www-data group?</p>\n\n<pre><code>sudo usermod -aG www-data rachel\n</code></pre>\n\n<p>More details <a href=\"https://stackoverflow.com/a/19620585/1173445\">https://stackoverflow.com/a/19620585/1173445</a></p>\n" }, { "answer_id": 263512, "author": "ciaika", "author_id": 48497, "author_profile": "https://wordpress.stackexchange.com/users/48497", "pm_score": 0, "selected": false, "text": "<p>Try to run these commands:</p>\n\n<pre>sudo chown www-data:www-data /home/rachel/web/site.co.uk/public_shtml -R\n\nsudo chmod g+w /home/rachel/web/site.co.uk/public_shtml -R</pre>\n" } ]
2017/04/13
[ "https://wordpress.stackexchange.com/questions/263470", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/74617/" ]
I'm trying to figure out how to let Wordpress update on my server, without needing FTP credentials. In `/etc/php/7.0/fpm/pool.d/www.conf` I have: ``` listen.owner = www-data listen.group = www-data ``` The problem I think is the way VestaCP is setup with the files: ``` root@com:/home/rachel/web/site.co.uk/public_shtml# ls -lh total 243M drwxrwxr-x 11 rachel rachel 4.0K Feb 3 2016 admin drwxrwxr-x 2 rachel rachel 4.0K Apr 12 09:14 cgi-bin drwxrwxr-x 3 rachel rachel 4.0K Jan 28 2016 dir -rw-rw-r-- 1 rachel rachel 418 Sep 25 2013 index.php -rw-r--r-- 1 rachel rachel 2.1K Apr 6 09:15 optimize.cgi drwxr-x--x 2 rachel rachel 4.0K Apr 12 09:12 public_shtml ``` the "owner" of them is actually the user's account username. I'm **sure** this must be possible (otherwise every file has to be owned by www-data, which causes all kinds of other issues) Am I just being stupid? **UPDATE:** As suggested, I've tried: `sudo usermod -aG www-data rachel` Unfortunately I still get the error: ``` PASS: Your WordPress install can communicate with WordPress.org securely. PASS: No version control systems were detected. FAIL: Your installation of WordPress prompts for FTP credentials to perform updates. (Your site is performing updates over FTP due to file ownership. Talk to your hosting company.) ```
Shouldn't u add rachel to the www-data group? ``` sudo usermod -aG www-data rachel ``` More details <https://stackoverflow.com/a/19620585/1173445>
263,492
<p>I am trying to load CSS and Javscripts through the functions. CSS are loading, but dont know what mistake has been done that javascripts and Jquery are not loading through the functions method.</p> <p>I tried by directly loading scripts through the head section and it worked, but by functions method it is not loading. I am producing the excerpts of the code here →</p> <pre><code> /* Register scripts. */ wp_register_script( 'custom', JS . '/jquery-3.1.1.js'); wp_register_script( 'custom', JS . '/custom.js'); </code></pre> <p>Do you think that there is any mistake commited in this also →</p> <pre><code>/*-------------------------------------------*/ /* 1. CONSTANTS */ /*-------------------------------------------*/ define( 'THEMEROOT', get_stylesheet_directory_uri() ); define( 'IMAGES', THEMEROOT . '/img' ); define( 'JS', THEMEROOT . '/js' ); </code></pre> <p>The live WP site link can be found <a href="http://codepen.trafficopedia.com/site01/" rel="nofollow noreferrer">here</a> for any direct troubleshooting.</p> <p>Try to click the hamburger menu and then the scripts will not load thats why the hamburger menu is not animating.</p> <p><strong>The Complete Function →</strong></p> <pre><code>if ( ! function_exists( 'klogeto_scripts' ) ) { function klogeto_scripts() { /* Register scripts. */ // wp_register_script( 'jquery', JS . '/jquery-3.1.1.js'); // wp_register_script( 'custom', JS . '/custom.js', array(), '20151215', true); // wp_enqueue_script( 'custom' ); wp_register_script( 'custom-js', get_template_directory_uri() . 'js/custom.js', array(), '20151215', true ); wp_enqueue_script( 'custom-js' ); /* Load the stylesheets. */ wp_enqueue_style( 'style', THEMEROOT . '/css/style.css' ); wp_enqueue_style( 'responsive', THEMEROOT . '/css/responsive.css' ); wp_enqueue_style( 'fontawesome', 'https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css' ); } add_action('wp_enqueue_scripts','klogeto_scripts'); </code></pre> <p>}</p>
[ { "answer_id": 263494, "author": "Frits", "author_id": 93169, "author_profile": "https://wordpress.stackexchange.com/users/93169", "pm_score": 1, "selected": false, "text": "<p>Once you register your script, you need to enqueue it.</p>\n\n<p>The below assumes you are using a theme:</p>\n\n<pre><code>wp_register_script( 'custom-js', get_template_directory_uri() . '/custom.js', array(), '20151215', true ); \nwp_enqueue_script( 'custom-js' );\n</code></pre>\n\n<p>I would also suggest using WordPress's built-in jQuery file.</p>\n\n<p><strong>EDIT</strong></p>\n\n<p>The complete function should look like this:</p>\n\n<pre><code>function my_custom_scripts() {\n wp_register_script( 'custom-js', get_template_directory_uri() . '/custom.js', array(), '20151215', true ); \n wp_enqueue_script( 'custom-js' );\n}\nadd_action( 'wp_enqueue_scripts', 'my_custom_scripts' );\n</code></pre>\n" }, { "answer_id": 263498, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 3, "selected": true, "text": "<p>There are several fundamental problems with what you're trying to do that prevent you reaching your goal</p>\n\n<h2>The Problems</h2>\n\n<h3>Naming</h3>\n\n<p>You register 2 scripts, but you name them both 'custom'. How is WordPress supposed to know which script you meant when you later tell it to display 'custom'?</p>\n\n<pre><code>/* Register scripts. */\nwp_register_script( 'custom', JS . '/jquery-3.1.1.js');\n\n// does this overwrite the previous line? ¯\\_(ツ)_/¯\nwp_register_script( 'custom', JS . '/custom.js'); \n</code></pre>\n\n<p>So lets fix that by giving them different names ( and proper indenting ):</p>\n\n<pre><code>/* Register scripts. */\nwp_register_script( 'wpnovice-jquery', JS . '/jquery-3.1.1.js');\nwp_register_script( 'wpnovice-custom', JS . '/custom.js');\n</code></pre>\n\n<p>Notice that I prefixed each, <code>custom</code> is a super generic term, and it's possible it's being used already.</p>\n\n<h3>WP Already Comes With JQuery!</h3>\n\n<p>Never bundle a library that already comes with WordPress. Doing what you did could lead to multiple copies and versions of jQuery being present on the frontend. Instead, tell WP that jQuery is required for your script:</p>\n\n<pre><code>/* Register scripts. */\nwp_register_script( 'wpnovice-custom', JS . '/custom.js', array( 'jquery' ) ); \n</code></pre>\n\n<h3>Registration != Enqueing</h3>\n\n<p>Registering your script tells WordPress they exist, but not what to do with them. WordPress already registers a lot of scripts, yet these don't appear on the frontend of every WordPress site.</p>\n\n<p>It's the difference between teaching somebody how to build a house, and somebody actually building that house.</p>\n\n<p>So, after registering, you need to call <code>wp_enqueue_script</code> to tell WordPress how to add that script to your page</p>\n\n<pre><code>/* Register scripts. */\nwp_register_script( 'wpnovice-custom', JS . '/custom.js', array( 'jquery' ) );\nwp_enqueue_script( 'wpnovice-custom' );\n</code></pre>\n\n<h3>Timing</h3>\n\n<p>Even with the newest version of that code, it may not work! This is because timing and location are important. In the same way that asking for your steak medium rare after it's been cooked doesn't work, asking WP to print scripts when it's already done the script printing won't work either.</p>\n\n<p>As a general piece of advice, don't put code in the global scope sitting in a file, instead wrap it in an action or hook, so that it runs when it's supposed to ( and can be unhooked when needed ).</p>\n\n<p>Here we want the <code>wp_enqueue_scripts</code> hook/action. Here's an example taken from the Core WP docs:</p>\n\n<pre><code>function themeslug_enqueue_script() {\n wp_enqueue_script( 'my-js', 'filename.js', false );\n}\nadd_action( 'wp_enqueue_scripts', 'themeslug_enqueue_script' );\n</code></pre>\n\n<h3>A Final Note on Constants</h3>\n\n<pre><code>/*-------------------------------------------*/\n/* 1. CONSTANTS */\n/*-------------------------------------------*/\ndefine( 'THEMEROOT', get_stylesheet_directory_uri() );\ndefine( 'IMAGES', THEMEROOT . '/img' );\ndefine( 'JS', THEMEROOT . '/js' );\n</code></pre>\n\n<p>I would advise against these, they're super generic names, and pollute the global namespace. In this case they may be misleading or cause problems.</p>\n\n<p>This version of the register script call, is explicit, and there's no ambiguity about wether it references the correct URL or not:</p>\n\n<pre><code>// register script\nwp_register_script( 'wpnovice-custom', get_stylesheet_directory_uri() . '/js/custom.js', array( 'jquery' ) );\n</code></pre>\n" }, { "answer_id": 263517, "author": "MagniGeeks Technologies", "author_id": 116950, "author_profile": "https://wordpress.stackexchange.com/users/116950", "pm_score": 0, "selected": false, "text": "<p>First your site has some js error. You can see your site in chrome console tab and see there is an error like Uncaught </p>\n\n<pre><code>TypeError: $ is not a function at custom.js:1\n</code></pre>\n\n<p>Regarding adding the js in your site you have done like </p>\n\n<pre><code>wp_register_script( 'custom', JS . '/jquery-3.1.1.js');\nwp_register_script( 'custom', JS . '/custom.js'); \n</code></pre>\n\n<p>Its totally wrong. You don't need to add external jQuery in wordpress. Wordpress has already that file.</p>\n\n<p><strong>Where is wp_enqueue_script?</strong></p>\n\n<p>wp_enqueue_script and wp_register_script is different. Please go through these below link to know about them</p>\n\n<p><a href=\"https://jhtechservices.com/wordpress-wp_enqueue_script-vs-wp_register_script/\" rel=\"nofollow noreferrer\">https://jhtechservices.com/wordpress-wp_enqueue_script-vs-wp_register_script/</a></p>\n\n<p><a href=\"https://wordpress.stackexchange.com/questions/82490/%20when-should-i-use-wp-register-script-with-wp-enqueue-script-vs-just-wp-enque\">https://wordpress.stackexchange.com/questions/82490/\nwhen-should-i-use-wp-register-script-with-wp-enqueue-script-vs-just-wp-enque</a></p>\n\n<p><a href=\"https://wordpress.stackexchange.com/questions/24453/wp-enqueue-script-vs-wp-register-script\">wp_enqueue_script vs. wp_register_script</a></p>\n\n<p>You should do like this </p>\n\n<pre><code>wp_register_script( 'custom-js', get_template_directory_uri() . '/custom.js', array(jquery), '1.0', true ); \nwp_enqueue_script( 'custom-js' ); \n</code></pre>\n" } ]
2017/04/13
[ "https://wordpress.stackexchange.com/questions/263492", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/105791/" ]
I am trying to load CSS and Javscripts through the functions. CSS are loading, but dont know what mistake has been done that javascripts and Jquery are not loading through the functions method. I tried by directly loading scripts through the head section and it worked, but by functions method it is not loading. I am producing the excerpts of the code here → ``` /* Register scripts. */ wp_register_script( 'custom', JS . '/jquery-3.1.1.js'); wp_register_script( 'custom', JS . '/custom.js'); ``` Do you think that there is any mistake commited in this also → ``` /*-------------------------------------------*/ /* 1. CONSTANTS */ /*-------------------------------------------*/ define( 'THEMEROOT', get_stylesheet_directory_uri() ); define( 'IMAGES', THEMEROOT . '/img' ); define( 'JS', THEMEROOT . '/js' ); ``` The live WP site link can be found [here](http://codepen.trafficopedia.com/site01/) for any direct troubleshooting. Try to click the hamburger menu and then the scripts will not load thats why the hamburger menu is not animating. **The Complete Function →** ``` if ( ! function_exists( 'klogeto_scripts' ) ) { function klogeto_scripts() { /* Register scripts. */ // wp_register_script( 'jquery', JS . '/jquery-3.1.1.js'); // wp_register_script( 'custom', JS . '/custom.js', array(), '20151215', true); // wp_enqueue_script( 'custom' ); wp_register_script( 'custom-js', get_template_directory_uri() . 'js/custom.js', array(), '20151215', true ); wp_enqueue_script( 'custom-js' ); /* Load the stylesheets. */ wp_enqueue_style( 'style', THEMEROOT . '/css/style.css' ); wp_enqueue_style( 'responsive', THEMEROOT . '/css/responsive.css' ); wp_enqueue_style( 'fontawesome', 'https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css' ); } add_action('wp_enqueue_scripts','klogeto_scripts'); ``` }
There are several fundamental problems with what you're trying to do that prevent you reaching your goal The Problems ------------ ### Naming You register 2 scripts, but you name them both 'custom'. How is WordPress supposed to know which script you meant when you later tell it to display 'custom'? ``` /* Register scripts. */ wp_register_script( 'custom', JS . '/jquery-3.1.1.js'); // does this overwrite the previous line? ¯\_(ツ)_/¯ wp_register_script( 'custom', JS . '/custom.js'); ``` So lets fix that by giving them different names ( and proper indenting ): ``` /* Register scripts. */ wp_register_script( 'wpnovice-jquery', JS . '/jquery-3.1.1.js'); wp_register_script( 'wpnovice-custom', JS . '/custom.js'); ``` Notice that I prefixed each, `custom` is a super generic term, and it's possible it's being used already. ### WP Already Comes With JQuery! Never bundle a library that already comes with WordPress. Doing what you did could lead to multiple copies and versions of jQuery being present on the frontend. Instead, tell WP that jQuery is required for your script: ``` /* Register scripts. */ wp_register_script( 'wpnovice-custom', JS . '/custom.js', array( 'jquery' ) ); ``` ### Registration != Enqueing Registering your script tells WordPress they exist, but not what to do with them. WordPress already registers a lot of scripts, yet these don't appear on the frontend of every WordPress site. It's the difference between teaching somebody how to build a house, and somebody actually building that house. So, after registering, you need to call `wp_enqueue_script` to tell WordPress how to add that script to your page ``` /* Register scripts. */ wp_register_script( 'wpnovice-custom', JS . '/custom.js', array( 'jquery' ) ); wp_enqueue_script( 'wpnovice-custom' ); ``` ### Timing Even with the newest version of that code, it may not work! This is because timing and location are important. In the same way that asking for your steak medium rare after it's been cooked doesn't work, asking WP to print scripts when it's already done the script printing won't work either. As a general piece of advice, don't put code in the global scope sitting in a file, instead wrap it in an action or hook, so that it runs when it's supposed to ( and can be unhooked when needed ). Here we want the `wp_enqueue_scripts` hook/action. Here's an example taken from the Core WP docs: ``` function themeslug_enqueue_script() { wp_enqueue_script( 'my-js', 'filename.js', false ); } add_action( 'wp_enqueue_scripts', 'themeslug_enqueue_script' ); ``` ### A Final Note on Constants ``` /*-------------------------------------------*/ /* 1. CONSTANTS */ /*-------------------------------------------*/ define( 'THEMEROOT', get_stylesheet_directory_uri() ); define( 'IMAGES', THEMEROOT . '/img' ); define( 'JS', THEMEROOT . '/js' ); ``` I would advise against these, they're super generic names, and pollute the global namespace. In this case they may be misleading or cause problems. This version of the register script call, is explicit, and there's no ambiguity about wether it references the correct URL or not: ``` // register script wp_register_script( 'wpnovice-custom', get_stylesheet_directory_uri() . '/js/custom.js', array( 'jquery' ) ); ```
263,493
<h2>I Have Wordpress Multisite as Following</h2> <ol> <li><p>multisite on domain.com </p></li> <li><p>multisite on sub1.domain.com</p></li> <li><p>multisite on sub2.domain.com</p></li> <li><p>multisite on sub3.domain.com</p> <p><strong>X multisite on subx.domain.com</strong></p></li> </ol> <hr> <ul> <li><p>All Sites are on Same Database. ( If There Is Way to Use Different Database it Will also Work )</p></li> <li><p>I am using domain.com's user and usermeta table for all other subx.domain.com by adding following code on all other multisite </p></li> </ul> <hr> <pre><code>define( 'CUSTOM_USER_TABLE', $table_prefix.'my_users' ); define( 'CUSTOM_USER_META_TABLE', $table_prefix.'my_usermeta' ); </code></pre> <hr> <p>and using</p> <ul> <li>" User Session Synchronizer " for Handling Login-Logout Cookies</li> </ul> <hr> <ul> <li>Everything Works Fine Only Problem I am facing is </li> <li>my user role is not synced what I mean is </li> </ul> <hr> <p><strong>If Someone Create account at domain.com or any subx.domain.com account is also created at all other subx.domain.com</strong></p> <p><strong>but</strong></p> <p><strong>Any other subx.domain.com Multisite Don't have user role so they can't do Nothing on any other Multisite</strong></p> <hr> <p><strong>What I Want to Do ?</strong></p> <ul> <li>I want to Duplicate same user role at every site in Real Time.</li> </ul> <hr> <p>OR</p> <hr> <ul> <li>I want to use same user and user meta for all site meaning that everysite will use same usermeta capabilities it will be more useful for me because I want to use mycred plugin and I don't want any issues** ( More Useful )</li> </ul> <hr> <h2>EDIT</h2> <p>So for example I have account with editor role at network site I also have account on other network site but I am not editor there even I don't have any role there my any network site needs to be same role because my multiple multisite network works in that way</p> <p><strong>if you would say why I or anyone need that kind of setup ?</strong></p> <ul> <li>Ans: I have similar site as stack overflow it is totally different from stack overflow but the way it works is same so if you sign up on any sub site of stack overflow you will have access to all subsite with same account and but I also want role to be same &amp; also want global point system </li> </ul>
[ { "answer_id": 263506, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 2, "selected": false, "text": "<blockquote>\n <p>I want to use same user and user meta for all site meaning that\n everysite will use same usermeta capabilities it will be more useful\n for me because I want to use mycred plugin and I don't want any\n issues** ( More Useful )</p>\n</blockquote>\n\n<p>This is the crux of the problem, specifically:</p>\n\n<blockquote>\n <p>everysite will use same usermeta capabilities</p>\n</blockquote>\n\n<p>Every site is already using the same user and user meta, the problem is that roles and capabilities are not stored in user meta! They have a separate table</p>\n\n<h2>So What if I shared the roles tables too?</h2>\n\n<p>That won't work. If the roles table says you have editor status on site #3, we now have a problem because you have multiple multisite installs. Does it mean site #3 on sub1.domain.com? Does it mean site #3 on sub2.domain.com? There's no way of knowing</p>\n\n<h2>The Problem Runs Deeper Though</h2>\n\n<p>Roles and Capabilities are not install-wide, they're site/blog-wide. I can be an editor on a blog, but an admin on another blog within the same multisite install.</p>\n\n<p>For example, WordPress.com is a giant multisite install. I can create a site and be an administrator of that site, but I don't have admin access to your site.</p>\n\n<p>By default, if I log into a site, I do not have a user role, which is intentional.</p>\n\n<h2>The Misleading Super Admin Functionality</h2>\n\n<p>Super Administrators aren't roles. Each blog has an options table, but there's another options table that exists across an entire multisite. Inside this is an option with a list of User IDs, this is what determines if you're a super admin or not.</p>\n\n<p>If your User ID appears in this option, you can do pretty much anything, and it will override and assume you have a capability. It's a little more involved than that, but that's a good approximation. You won't find a super admin role in the roles table.</p>\n\n<h2>So How Do I Build A System Where I Give a User A Role That is Everywhere?</h2>\n\n<p>A universal role, that you set once, that's set everywhere? This functionality doesn't come out of the box, and is counter to how standard WordPress works ( and may have unanticipated side effects ).</p>\n\n<p>At a fundamental level, what you've been building is single sign on, but through a fragile system of shared user tables.</p>\n\n<p>So you will need:</p>\n\n<ul>\n<li>Somewhere to store the role set for the user</li>\n<li>Code to read that and set it programmatically, ignoring the user table</li>\n<li>Code to provide a User interface for setting the role</li>\n<li>A list of what roles you want, if a plugin adds new roles then those will not be usable unless it's added to all sites across all installs</li>\n</ul>\n\n<p>I would suggest storing the role in user meta, and using the user edit profile screen. You will also need code to check the roles and capabilities to prevent users changing their own roles. Pay very careful attention to this code as it will be a critical security failure point.</p>\n\n<p>Sadly, doing this may be either difficult, or expensive:</p>\n\n<ul>\n<li>The <code>WP_User</code> object doesn't provide easy filters, it may be necessary to note down a role and all its capabilities and provide your own WP_User replacement, this could well cause compatibility problems</li>\n<li>You could check on every page load if the users role matches what it's meant to be, and set it if it isn't. This would be more expensive, but more reliable and more compatible</li>\n</ul>\n\n<p>I would note though, that all of this is going to be costly to maintain. Your setup has pushed you into a corner of high technical debt, and this is one of the costs.</p>\n\n<h2>How Other People Do It</h2>\n\n<p>When you rebuild the system in the future, consider a SSO/Single sign on system. Federated login such as those provided by OAuth or SAML is the longterm answer here. IN that scenario you would provide the authentication level to the site when the user logs in ( the login may be a seamless redirect if the user has already authenticated with the SSO provider ), then set the appropriate role when the user is passed back to the site.</p>\n\n<p>It is true, that you would no longer be sharing user tables across installs, but any information that needs to be synchronised would be set at the central SSO provider and pushed to the relevant sites.</p>\n" }, { "answer_id": 264074, "author": "Maharshi", "author_id": 117067, "author_profile": "https://wordpress.stackexchange.com/users/117067", "pm_score": 1, "selected": true, "text": "<p>I just got this on Web this works for me it need some work </p>\n\n<hr>\n\n<p>kinsta.com/blog/share-logins-wordpress</p>\n" } ]
2017/04/13
[ "https://wordpress.stackexchange.com/questions/263493", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/117067/" ]
I Have Wordpress Multisite as Following --------------------------------------- 1. multisite on domain.com 2. multisite on sub1.domain.com 3. multisite on sub2.domain.com 4. multisite on sub3.domain.com **X multisite on subx.domain.com** --- * All Sites are on Same Database. ( If There Is Way to Use Different Database it Will also Work ) * I am using domain.com's user and usermeta table for all other subx.domain.com by adding following code on all other multisite --- ``` define( 'CUSTOM_USER_TABLE', $table_prefix.'my_users' ); define( 'CUSTOM_USER_META_TABLE', $table_prefix.'my_usermeta' ); ``` --- and using * " User Session Synchronizer " for Handling Login-Logout Cookies --- * Everything Works Fine Only Problem I am facing is * my user role is not synced what I mean is --- **If Someone Create account at domain.com or any subx.domain.com account is also created at all other subx.domain.com** **but** **Any other subx.domain.com Multisite Don't have user role so they can't do Nothing on any other Multisite** --- **What I Want to Do ?** * I want to Duplicate same user role at every site in Real Time. --- OR --- * I want to use same user and user meta for all site meaning that everysite will use same usermeta capabilities it will be more useful for me because I want to use mycred plugin and I don't want any issues\*\* ( More Useful ) --- EDIT ---- So for example I have account with editor role at network site I also have account on other network site but I am not editor there even I don't have any role there my any network site needs to be same role because my multiple multisite network works in that way **if you would say why I or anyone need that kind of setup ?** * Ans: I have similar site as stack overflow it is totally different from stack overflow but the way it works is same so if you sign up on any sub site of stack overflow you will have access to all subsite with same account and but I also want role to be same & also want global point system
I just got this on Web this works for me it need some work --- kinsta.com/blog/share-logins-wordpress
263,521
<p>I want to remove a menu sub-item. But i cant'find the right item to delete. It is a plug caled "New User Approve". And the slug is :/wp-admin/users.php?page=new-user-approve-admin</p> <p>I don't want to disable the plugin and the functions, just the sub-menu item.</p> <p>I don't come further than: </p> <pre><code> add_action( 'admin_menu', 'remove_admin_menus' ); </code></pre> <p>add_action( 'admin_menu', 'remove_admin_submenus' );</p> <p>//Remove top level admin menus function remove_admin_menus() {</p> <p>}</p> <p>//Remove sub level admin menus function remove_admin_submenus() { remove_submenu_page( 'users.php', 'users.php?page=new-user-approve-admin' );</p> <p>}</p> <p>or</p> <pre><code>function remove_submenu() { remove_submenu_page( 'users.php', 'users.php?page=new-user-approve-admin' ); </code></pre> <p>}</p> <p>add_action( 'admin_menu', 'remove_submenu', 999 );</p>
[ { "answer_id": 263524, "author": "joetek", "author_id": 62298, "author_profile": "https://wordpress.stackexchange.com/users/62298", "pm_score": -1, "selected": true, "text": "<p>You'd want to add this code:</p>\n\n<pre><code>add_action( 'admin_menu', 'remove_admin_menus', 999 );\nfunction remove_admin_menus() {\n remove_submenu_page( 'users.php', 'new-user-approve-admin' );\n}\n</code></pre>\n" }, { "answer_id": 263536, "author": "ciaika", "author_id": 48497, "author_profile": "https://wordpress.stackexchange.com/users/48497", "pm_score": 0, "selected": false, "text": "<p>This one will work for sure, tested it, add the code into the \"functions.php\" file from the main or child theme folder (or plugin, in case you are using it in a plugin):</p>\n\n<pre>add_action( 'admin_menu', 'custom_remove_admin_submenus', 999 );\nfunction custom_remove_admin_submenus() {\n remove_submenu_page( 'users.php', 'new-user-approve-admin' );\n}</pre>\n" } ]
2017/04/13
[ "https://wordpress.stackexchange.com/questions/263521", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/57885/" ]
I want to remove a menu sub-item. But i cant'find the right item to delete. It is a plug caled "New User Approve". And the slug is :/wp-admin/users.php?page=new-user-approve-admin I don't want to disable the plugin and the functions, just the sub-menu item. I don't come further than: ``` add_action( 'admin_menu', 'remove_admin_menus' ); ``` add\_action( 'admin\_menu', 'remove\_admin\_submenus' ); //Remove top level admin menus function remove\_admin\_menus() { } //Remove sub level admin menus function remove\_admin\_submenus() { remove\_submenu\_page( 'users.php', 'users.php?page=new-user-approve-admin' ); } or ``` function remove_submenu() { remove_submenu_page( 'users.php', 'users.php?page=new-user-approve-admin' ); ``` } add\_action( 'admin\_menu', 'remove\_submenu', 999 );
You'd want to add this code: ``` add_action( 'admin_menu', 'remove_admin_menus', 999 ); function remove_admin_menus() { remove_submenu_page( 'users.php', 'new-user-approve-admin' ); } ```
263,527
<p>I have created custom template (Sell items) for pages. I want to display posts from specific category on page using that custom template. That is working perfectly but only if there are at least one post in the category. If there is nothing it will give following error.</p> <p>What might be wrong?</p> <p><em>Notice: Undefined offset: 0 in /home/usernamethis/public_html/5423565/wp-includes/class-wp-query.php on line 3152</em></p> <p>Here is the code. Html ripped out for better reading:</p> <pre><code>&lt;?php /* Template Name: Sell items Template Post Type: post */ get_header(); global $post; ?&gt; &lt;?php if(have_posts()) : ?&gt; &lt;?php while(have_posts()) : the_post(); ?&gt; &lt;!-- THIS IS WHERE PAGE CONTENT IS DISPLAYED --&gt; &lt;?php the_content(); ?&gt; &lt;!-- THIS IS WHERE PAGE CONTENT IS DISPLAYED --&gt; &lt;?php $args = array( 'numberposts' =&gt; 20, 'category_name' =&gt; 'sell-items' ); $posts = get_posts( $args ); ?&gt; &lt;?php if(!empty($posts) &amp;&amp; count($posts)&gt;0) : ?&gt; &lt;?php foreach( $posts as $post ): setup_postdata($post);?&gt; &lt;li&gt;&lt;a href="&lt;?php the_permalink(); ?&gt;"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;&lt;/li&gt; &lt;?php endforeach; wp_reset_postdata(); ?&gt; &lt;?php endif; ?&gt; &lt;?php endwhile; ?&gt; &lt;?php else: ?&gt; Not found &lt;?php endif; ?&gt; </code></pre>
[ { "answer_id": 263529, "author": "ciaika", "author_id": 48497, "author_profile": "https://wordpress.stackexchange.com/users/48497", "pm_score": 1, "selected": false, "text": "<p>You can use WP_Query instead the get_posts() function:</p>\n\n<pre>\n $args = array( 'numberposts' => 20, 'category_name' => 'sell-items' ); \n $wp_query = new WP_Query($args);\n\nif ($wp_query->have_posts()) : while($wp_query->have_posts()) : $wp_query->the_post();\n\necho '&lt;li>&lt;a href=\"'.get_the_permalink().'\">'.get_the_title().'&lt;/a>&lt;/li>';\n endwhile;\n endif;</pre>\n" }, { "answer_id": 263530, "author": "WebElaine", "author_id": 102815, "author_profile": "https://wordpress.stackexchange.com/users/102815", "pm_score": 0, "selected": false, "text": "<p>It looks like your endif and endwhile are misplaced. Try this:</p>\n\n<pre><code>&lt;?php\n/*\nTemplate Name: Sell items\nTemplate Post Type: post\n*/\nget_header(); \nglobal $post;\n?&gt;\n\n&lt;?php if(have_posts()) : ?&gt;\n&lt;?php while(have_posts()) : the_post(); ?&gt;\n\n&lt;!-- THIS IS WHERE PAGE CONTENT IS DISPLAYED --&gt;\n&lt;?php the_content(); ?&gt;\n&lt;!-- THIS IS WHERE PAGE CONTENT IS DISPLAYED --&gt;\n&lt;?php endwhile; ?&gt;\n&lt;?php endif; ?&gt;\n\n&lt;?php\n$args = array( 'numberposts' =&gt; 20, 'category_name' =&gt; 'sell-items' ); \n$posts = get_posts( $args ); \n?&gt;\n\n&lt;?php if(!empty($posts) &amp;&amp; count($posts)&gt;0) : ?&gt;\n\n&lt;?php\nforeach( $posts as $post ): \nsetup_postdata($post);?&gt; \n&lt;li&gt;&lt;a href=\"&lt;?php the_permalink(); ?&gt;\"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;&lt;/li&gt;\n&lt;?php \nendforeach; \nwp_reset_postdata();\n?&gt;\n\n&lt;?php else: ?&gt;\n\nNot found\n&lt;?php endif; ?&gt;\n</code></pre>\n" } ]
2017/04/13
[ "https://wordpress.stackexchange.com/questions/263527", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/92020/" ]
I have created custom template (Sell items) for pages. I want to display posts from specific category on page using that custom template. That is working perfectly but only if there are at least one post in the category. If there is nothing it will give following error. What might be wrong? *Notice: Undefined offset: 0 in /home/usernamethis/public\_html/5423565/wp-includes/class-wp-query.php on line 3152* Here is the code. Html ripped out for better reading: ``` <?php /* Template Name: Sell items Template Post Type: post */ get_header(); global $post; ?> <?php if(have_posts()) : ?> <?php while(have_posts()) : the_post(); ?> <!-- THIS IS WHERE PAGE CONTENT IS DISPLAYED --> <?php the_content(); ?> <!-- THIS IS WHERE PAGE CONTENT IS DISPLAYED --> <?php $args = array( 'numberposts' => 20, 'category_name' => 'sell-items' ); $posts = get_posts( $args ); ?> <?php if(!empty($posts) && count($posts)>0) : ?> <?php foreach( $posts as $post ): setup_postdata($post);?> <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li> <?php endforeach; wp_reset_postdata(); ?> <?php endif; ?> <?php endwhile; ?> <?php else: ?> Not found <?php endif; ?> ```
You can use WP\_Query instead the get\_posts() function: ``` $args = array( 'numberposts' => 20, 'category_name' => 'sell-items' ); $wp_query = new WP_Query($args); if ($wp_query->have_posts()) : while($wp_query->have_posts()) : $wp_query->the_post(); echo '<li><a href="'.get_the_permalink().'">'.get_the_title().'</a></li>'; endwhile; endif; ```
263,558
<p>I am already filtering some custom posts depending on a querystring in pre_get_posts:</p> <pre><code>if( $query-&gt;is_main_query() ) { if( is_post_type_archive( 'events' ) ) { if ($_GET['status']) { $retrieved_status = $_GET['status']; $query-&gt;set('meta_key', 'event_status'); $query-&gt;set('meta_value', $retrieved_status); } } } </code></pre> <p>I would then also like to sort by a different custom field, but I can't use something like below because it rewrites the meta_key:</p> <pre><code>$query-&gt;set('orderby', 'meta_value'); $query-&gt;set('meta_key', 'event_date'); $query-&gt;set('order', 'DESC'); </code></pre> <p>How could I structure this to get the desired effect? Thanks!</p>
[ { "answer_id": 264745, "author": "Howdy_McGee", "author_id": 7355, "author_profile": "https://wordpress.stackexchange.com/users/7355", "pm_score": 2, "selected": false, "text": "<p>WP_Query has a case for this called a <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Custom_Field_Parameters\" rel=\"nofollow noreferrer\">Meta Query</a> where you can pass as many complex arguments as necessary:</p>\n\n<pre><code>$query = new WP_Query array(\n 'meta_query' =&gt; array(\n 'relation' =&gt; 'AND', // OR is the default relation parameter, if this is excluded\n array(\n 'key' =&gt; 'meta_key_one',\n 'value' =&gt; 'meta_value_one',\n 'compare' =&gt; '&lt;=',\n ),\n array(\n 'key' =&gt; 'meta_key_two',\n 'value' =&gt; 'meta_value_two',\n 'compare' =&gt; '&lt;=',\n ),\n ),\n) );\n</code></pre>\n\n<p>The above says:</p>\n\n<pre><code>SELECT\n All Posts\n WHERE\n Meta Keys Value One is Less Than or Equal to Passed Value One\n AND\n Meta Keys Value Two is Less Than or Equal to Passed Value Two\n</code></pre>\n" }, { "answer_id": 264747, "author": "Yamona", "author_id": 68492, "author_profile": "https://wordpress.stackexchange.com/users/68492", "pm_score": 3, "selected": true, "text": "<p>Use WP_Query to select any post based on meta key and value. You can also sort posts \nEx:</p>\n\n<pre><code>$args = array(\n 'post_type' =&gt; 'events',\n 'orderby' =&gt; 'meta_value_num', //probably you will need this because the value is date\n 'meta_key' =&gt; 'event_date',\n 'meta_query' =&gt; array(\n 'relation' =&gt; 'AND',\n array(\n 'key' =&gt; 'event_status',\n 'value' =&gt; $retrieved_status, \n 'compare' =&gt; '=',\n ),\n array(\n 'key' =&gt; 'other_key',\n 'value' =&gt; 'other_value',\n 'type' =&gt; 'numeric', //for example\n 'compare' =&gt; 'BETWEEN', //for example\n ),\n ),\n);\n$query = new WP_Query( $args );\n</code></pre>\n\n<p>See <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters\" rel=\"nofollow noreferrer\">Order &amp; Orderby Parameters</a> &amp; for <code>meta_value_num</code> see <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Custom_Field_Parameters\" rel=\"nofollow noreferrer\">Custom Field Parameters</a></p>\n" } ]
2017/04/13
[ "https://wordpress.stackexchange.com/questions/263558", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/108897/" ]
I am already filtering some custom posts depending on a querystring in pre\_get\_posts: ``` if( $query->is_main_query() ) { if( is_post_type_archive( 'events' ) ) { if ($_GET['status']) { $retrieved_status = $_GET['status']; $query->set('meta_key', 'event_status'); $query->set('meta_value', $retrieved_status); } } } ``` I would then also like to sort by a different custom field, but I can't use something like below because it rewrites the meta\_key: ``` $query->set('orderby', 'meta_value'); $query->set('meta_key', 'event_date'); $query->set('order', 'DESC'); ``` How could I structure this to get the desired effect? Thanks!
Use WP\_Query to select any post based on meta key and value. You can also sort posts Ex: ``` $args = array( 'post_type' => 'events', 'orderby' => 'meta_value_num', //probably you will need this because the value is date 'meta_key' => 'event_date', 'meta_query' => array( 'relation' => 'AND', array( 'key' => 'event_status', 'value' => $retrieved_status, 'compare' => '=', ), array( 'key' => 'other_key', 'value' => 'other_value', 'type' => 'numeric', //for example 'compare' => 'BETWEEN', //for example ), ), ); $query = new WP_Query( $args ); ``` See [Order & Orderby Parameters](https://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters) & for `meta_value_num` see [Custom Field Parameters](https://codex.wordpress.org/Class_Reference/WP_Query#Custom_Field_Parameters)
263,574
<p>I have to display a button that links to a tag, but I have to hide the button if tag doesn't exists to avoid broken links.</p> <p>How can I check if a specific tag exists inside wp database?</p> <p><strong>This is what I have so far:</strong></p> <pre><code> $tag_path = '/tag/testing/'; if( !$page = get_page_by_path( $tag_path ) ){ //hide button link } else { //show button link } </code></pre>
[ { "answer_id": 263575, "author": "Abdul Awal Uzzal", "author_id": 31449, "author_profile": "https://wordpress.stackexchange.com/users/31449", "pm_score": 4, "selected": true, "text": "<p>I think you're looking for <a href=\"https://codex.wordpress.org/Function_Reference/term_exists\" rel=\"noreferrer\"><code>term_exists</code></a> function.</p>\n\n<p>Example Code:</p>\n\n<pre><code>&lt;?php\n$term = term_exists('tag1', 'post_tag');\nif ($term !== 0 &amp;&amp; $term !== null) {\n echo \"'tag1' post_tag exists!\";\n} else {\n echo \"'tag1' post_tag does not exist!\";\n}\n?&gt;\n</code></pre>\n" }, { "answer_id": 353421, "author": "Jahirul Islam Mamun", "author_id": 57851, "author_profile": "https://wordpress.stackexchange.com/users/57851", "pm_score": 0, "selected": false, "text": "<p>I think you can check <code>has_tag</code></p>\n\n<pre><code>if(has_tag('tag_name')) {\n // do something\n} else {\n // do something\n}\n</code></pre>\n\n<p>Ref - <a href=\"https://developer.wordpress.org/reference/functions/has_tag/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/has_tag/</a></p>\n" } ]
2017/04/13
[ "https://wordpress.stackexchange.com/questions/263574", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/18693/" ]
I have to display a button that links to a tag, but I have to hide the button if tag doesn't exists to avoid broken links. How can I check if a specific tag exists inside wp database? **This is what I have so far:** ``` $tag_path = '/tag/testing/'; if( !$page = get_page_by_path( $tag_path ) ){ //hide button link } else { //show button link } ```
I think you're looking for [`term_exists`](https://codex.wordpress.org/Function_Reference/term_exists) function. Example Code: ``` <?php $term = term_exists('tag1', 'post_tag'); if ($term !== 0 && $term !== null) { echo "'tag1' post_tag exists!"; } else { echo "'tag1' post_tag does not exist!"; } ?> ```
263,595
<p>Please help if any one can.I tried it to create uploads folder manually and then upload media in upload folder but then i can not get my media file in WordPress dashboard media file.</p>
[ { "answer_id": 263575, "author": "Abdul Awal Uzzal", "author_id": 31449, "author_profile": "https://wordpress.stackexchange.com/users/31449", "pm_score": 4, "selected": true, "text": "<p>I think you're looking for <a href=\"https://codex.wordpress.org/Function_Reference/term_exists\" rel=\"noreferrer\"><code>term_exists</code></a> function.</p>\n\n<p>Example Code:</p>\n\n<pre><code>&lt;?php\n$term = term_exists('tag1', 'post_tag');\nif ($term !== 0 &amp;&amp; $term !== null) {\n echo \"'tag1' post_tag exists!\";\n} else {\n echo \"'tag1' post_tag does not exist!\";\n}\n?&gt;\n</code></pre>\n" }, { "answer_id": 353421, "author": "Jahirul Islam Mamun", "author_id": 57851, "author_profile": "https://wordpress.stackexchange.com/users/57851", "pm_score": 0, "selected": false, "text": "<p>I think you can check <code>has_tag</code></p>\n\n<pre><code>if(has_tag('tag_name')) {\n // do something\n} else {\n // do something\n}\n</code></pre>\n\n<p>Ref - <a href=\"https://developer.wordpress.org/reference/functions/has_tag/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/has_tag/</a></p>\n" } ]
2017/04/14
[ "https://wordpress.stackexchange.com/questions/263595", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/117635/" ]
Please help if any one can.I tried it to create uploads folder manually and then upload media in upload folder but then i can not get my media file in WordPress dashboard media file.
I think you're looking for [`term_exists`](https://codex.wordpress.org/Function_Reference/term_exists) function. Example Code: ``` <?php $term = term_exists('tag1', 'post_tag'); if ($term !== 0 && $term !== null) { echo "'tag1' post_tag exists!"; } else { echo "'tag1' post_tag does not exist!"; } ?> ```
263,598
<p>I want to adjust or edit below codes to show all custom post types without showing page numbers. I just want to show all items in one page. I don't want to keep pagination here. What thing I need to edit or add in this below codes?</p> <pre><code>// show all active coupons for this store and setup pagination $paged = (get_query_var('paged')) ? get_query_var('paged') : 1; query_posts( array( 'post_type' =&gt; APP_POST_TYPE, 'post_status' =&gt; 'publish', APP_TAX_STORE =&gt; $term-&gt;slug, 'ignore_sticky_posts' =&gt; 1, 'paged' =&gt; $paged ) ); </code></pre>
[ { "answer_id": 263575, "author": "Abdul Awal Uzzal", "author_id": 31449, "author_profile": "https://wordpress.stackexchange.com/users/31449", "pm_score": 4, "selected": true, "text": "<p>I think you're looking for <a href=\"https://codex.wordpress.org/Function_Reference/term_exists\" rel=\"noreferrer\"><code>term_exists</code></a> function.</p>\n\n<p>Example Code:</p>\n\n<pre><code>&lt;?php\n$term = term_exists('tag1', 'post_tag');\nif ($term !== 0 &amp;&amp; $term !== null) {\n echo \"'tag1' post_tag exists!\";\n} else {\n echo \"'tag1' post_tag does not exist!\";\n}\n?&gt;\n</code></pre>\n" }, { "answer_id": 353421, "author": "Jahirul Islam Mamun", "author_id": 57851, "author_profile": "https://wordpress.stackexchange.com/users/57851", "pm_score": 0, "selected": false, "text": "<p>I think you can check <code>has_tag</code></p>\n\n<pre><code>if(has_tag('tag_name')) {\n // do something\n} else {\n // do something\n}\n</code></pre>\n\n<p>Ref - <a href=\"https://developer.wordpress.org/reference/functions/has_tag/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/has_tag/</a></p>\n" } ]
2017/04/14
[ "https://wordpress.stackexchange.com/questions/263598", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/117256/" ]
I want to adjust or edit below codes to show all custom post types without showing page numbers. I just want to show all items in one page. I don't want to keep pagination here. What thing I need to edit or add in this below codes? ``` // show all active coupons for this store and setup pagination $paged = (get_query_var('paged')) ? get_query_var('paged') : 1; query_posts( array( 'post_type' => APP_POST_TYPE, 'post_status' => 'publish', APP_TAX_STORE => $term->slug, 'ignore_sticky_posts' => 1, 'paged' => $paged ) ); ```
I think you're looking for [`term_exists`](https://codex.wordpress.org/Function_Reference/term_exists) function. Example Code: ``` <?php $term = term_exists('tag1', 'post_tag'); if ($term !== 0 && $term !== null) { echo "'tag1' post_tag exists!"; } else { echo "'tag1' post_tag does not exist!"; } ?> ```
263,611
<p>I've successfully change the HTML for <code>archive-product.php</code> and <code>content-product.php</code> pages. Once I updated to the latest Wordpress I found that all the changes I made just gone.</p> <p>I notice this issue is mentioned everywhere I searched for custom theme development. However, I'm not sure how to do this for WooCommerce pages. </p> <p>First of all, I don't find templates option in admin panel (maybe my theme problem).</p> <p>Second, how do I tell WooCommerce to use my custom template? </p> <p>Third, I'm not sure what to place inside my custom design.</p> <p>This is how I customized <code>archive-product.php</code> page.</p> <pre><code>get_header( 'shop' ); ?&gt; &lt;div class="row"&gt; &lt;div class="small-12 medium-12 large-12 columns text-left"&gt; &lt;!--breadcrumb--&gt; &lt;?php /** * woocommerce_before_main_content hook. * * @hooked woocommerce_output_content_wrapper - 10 (outputs opening divs for the content) * @hooked woocommerce_breadcrumb - 20 * @hooked WC_Structured_Data::generate_website_data() - 30 */ do_action( 'woocommerce_before_main_content' ); ?&gt; &lt;/div&gt; &lt;header class="small-12 medium-6 large-6 columns text-left woocommerce-products-header collapse"&gt; &lt;!--title--&gt; &lt;?php if ( apply_filters( 'woocommerce_show_page_title', true ) ) : ?&gt; &lt;h1 class="woocommerce-products-header__title page-title"&gt;&lt;?php woocommerce_page_title(); ?&gt;&lt;/h1&gt; &lt;?php endif; ?&gt; &lt;?php /** * woocommerce_archive_description hook. * * @hooked woocommerce_taxonomy_archive_description - 10 * @hooked woocommerce_product_archive_description - 10 */ do_action( 'woocommerce_archive_description' ); ?&gt; &lt;/header&gt; &lt;div class="small-12 medium-6 large-6 columns collapse"&gt; &lt;?php if ( have_posts() ) : ?&gt; &lt;?php /** * woocommerce_before_shop_loop hook. * * @hooked woocommerce_result_count - 20 * @hooked woocommerce_catalog_ordering - 30 */ do_action( 'woocommerce_before_shop_loop' ); ?&gt; &lt;?php endif; ?&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="row small-up-2 large-up-4"&gt; &lt;?php if ( have_posts() ) : ?&gt; &lt;?php #woocommerce_product_loop_start(); ?&gt;&lt;!--removes ul--&gt; &lt;?php woocommerce_product_subcategories(); ?&gt; &lt;?php while ( have_posts() ) : the_post(); ?&gt; &lt;?php /** * woocommerce_shop_loop hook. * * @hooked WC_Structured_Data::generate_product_data() - 10 */ do_action( 'woocommerce_shop_loop' ); ?&gt; &lt;?php wc_get_template_part( 'content', 'product' ); ?&gt; &lt;?php endwhile; // end of the loop. ?&gt; &lt;?php #woocommerce_product_loop_end(); ?&gt; &lt;?php /** * woocommerce_after_shop_loop hook. * * @hooked woocommerce_pagination - 10 */ do_action( 'woocommerce_after_shop_loop' ); ?&gt; &lt;?php elseif ( ! woocommerce_product_subcategories( array( 'before' =&gt; woocommerce_product_loop_start( false ), 'after' =&gt; woocommerce_product_loop_end( false ) ) ) ) : ?&gt; &lt;?php /** * woocommerce_no_products_found hook. * * @hooked wc_no_products_found - 10 */ do_action( 'woocommerce_no_products_found' ); ?&gt; &lt;?php endif; ?&gt; &lt;/div&gt; &lt;?php get_footer( 'shop' ); ?&gt; </code></pre> <p>Do share with me any reference for this. As I'm unsure which one to follow and not clear on the exact steps.</p> <p>As per advised, </p> <p>I created one folder called <code>woocommerce</code> inside my theme and placed the template files like below:</p> <pre><code>my_theme/woocommerce/templates/archive-product.php my_theme/woocommerce/templates/content-product.php </code></pre> <p>However its still pointing to the plugin files.</p>
[ { "answer_id": 263612, "author": "Aditya Batra", "author_id": 109696, "author_profile": "https://wordpress.stackexchange.com/users/109696", "pm_score": 0, "selected": false, "text": "<p>Create a woocommerce folder on your root folder and copy the template from the woocommerce plugin (in template folder) to the root folder/woocommerce folder. Edit them to avoid changes on update. Also, the file in the root woocommerce folder must be in the same pattern that are in woocommerce plugin/template folder.</p>\n\n<p>Follow the below link for more details on woocommerce template customization. <a href=\"https://code.tutsplus.com/articles/an-introduction-to-theming-woocommerce-for-wordpress--wp-31577\" rel=\"nofollow noreferrer\">https://code.tutsplus.com/articles/an-introduction-to-theming-woocommerce-for-wordpress--wp-31577</a></p>\n" }, { "answer_id": 263613, "author": "BlueSuiter", "author_id": 92665, "author_profile": "https://wordpress.stackexchange.com/users/92665", "pm_score": 3, "selected": true, "text": "<p>Make it like this::</p>\n\n<pre><code>my_theme/woocommerce/archive-product.php\nmy_theme/woocommerce/content-product.php\n</code></pre>\n" } ]
2017/04/14
[ "https://wordpress.stackexchange.com/questions/263611", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/117641/" ]
I've successfully change the HTML for `archive-product.php` and `content-product.php` pages. Once I updated to the latest Wordpress I found that all the changes I made just gone. I notice this issue is mentioned everywhere I searched for custom theme development. However, I'm not sure how to do this for WooCommerce pages. First of all, I don't find templates option in admin panel (maybe my theme problem). Second, how do I tell WooCommerce to use my custom template? Third, I'm not sure what to place inside my custom design. This is how I customized `archive-product.php` page. ``` get_header( 'shop' ); ?> <div class="row"> <div class="small-12 medium-12 large-12 columns text-left"> <!--breadcrumb--> <?php /** * woocommerce_before_main_content hook. * * @hooked woocommerce_output_content_wrapper - 10 (outputs opening divs for the content) * @hooked woocommerce_breadcrumb - 20 * @hooked WC_Structured_Data::generate_website_data() - 30 */ do_action( 'woocommerce_before_main_content' ); ?> </div> <header class="small-12 medium-6 large-6 columns text-left woocommerce-products-header collapse"> <!--title--> <?php if ( apply_filters( 'woocommerce_show_page_title', true ) ) : ?> <h1 class="woocommerce-products-header__title page-title"><?php woocommerce_page_title(); ?></h1> <?php endif; ?> <?php /** * woocommerce_archive_description hook. * * @hooked woocommerce_taxonomy_archive_description - 10 * @hooked woocommerce_product_archive_description - 10 */ do_action( 'woocommerce_archive_description' ); ?> </header> <div class="small-12 medium-6 large-6 columns collapse"> <?php if ( have_posts() ) : ?> <?php /** * woocommerce_before_shop_loop hook. * * @hooked woocommerce_result_count - 20 * @hooked woocommerce_catalog_ordering - 30 */ do_action( 'woocommerce_before_shop_loop' ); ?> <?php endif; ?> </div> </div> <div class="row small-up-2 large-up-4"> <?php if ( have_posts() ) : ?> <?php #woocommerce_product_loop_start(); ?><!--removes ul--> <?php woocommerce_product_subcategories(); ?> <?php while ( have_posts() ) : the_post(); ?> <?php /** * woocommerce_shop_loop hook. * * @hooked WC_Structured_Data::generate_product_data() - 10 */ do_action( 'woocommerce_shop_loop' ); ?> <?php wc_get_template_part( 'content', 'product' ); ?> <?php endwhile; // end of the loop. ?> <?php #woocommerce_product_loop_end(); ?> <?php /** * woocommerce_after_shop_loop hook. * * @hooked woocommerce_pagination - 10 */ do_action( 'woocommerce_after_shop_loop' ); ?> <?php elseif ( ! woocommerce_product_subcategories( array( 'before' => woocommerce_product_loop_start( false ), 'after' => woocommerce_product_loop_end( false ) ) ) ) : ?> <?php /** * woocommerce_no_products_found hook. * * @hooked wc_no_products_found - 10 */ do_action( 'woocommerce_no_products_found' ); ?> <?php endif; ?> </div> <?php get_footer( 'shop' ); ?> ``` Do share with me any reference for this. As I'm unsure which one to follow and not clear on the exact steps. As per advised, I created one folder called `woocommerce` inside my theme and placed the template files like below: ``` my_theme/woocommerce/templates/archive-product.php my_theme/woocommerce/templates/content-product.php ``` However its still pointing to the plugin files.
Make it like this:: ``` my_theme/woocommerce/archive-product.php my_theme/woocommerce/content-product.php ```
263,671
<p>I'm trying to input the numer of the post next to it, but in the reverse order, which means</p> <p>not </p> <p>1 2 3 4</p> <p>but</p> <p>4 3 2 1 .</p> <p>I have succeeded into doing it in the "right" order with this : </p> <pre><code>&lt;?php if (have_posts()) : while (have_posts()) : the_post(); ?&gt; &lt;?php echo $wp_query-&gt;current_post + 1; ?&gt; </code></pre> <p>but I can't figure out how to do the opposite. Morethough, when I have my posts in several pages, it breaks aka</p> <p>PAGE 1 : 1234 PAGE 2 : 1234 (should be 5678)</p> <p>I have tried this : </p> <pre><code>&lt;?php echo $wp_query-&gt;found_posts - $wp_query-&gt;current_post ?&gt; </code></pre> <p>which inputs 8765 and then the next page 8765 instead of 4321...</p>
[ { "answer_id": 263672, "author": "Howdy_McGee", "author_id": 7355, "author_profile": "https://wordpress.stackexchange.com/users/7355", "pm_score": 0, "selected": false, "text": "<p>Strange question. You can create a secondary query or run a hook into <a href=\"https://developer.wordpress.org/reference/hooks/pre_get_posts/\" rel=\"nofollow noreferrer\">pre_get_posts</a> but the general idea is you would <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters\" rel=\"nofollow noreferrer\">order by ID</a> in Descending Order:</p>\n\n<pre><code>$query = new WP_Query( array(\n 'orderby' =&gt; array( 'ID' =&gt; 'DESC' ),\n) );\n</code></pre>\n\n<p>You could also probably run <a href=\"http://php.net/manual/en/function.array-reverse.php\" rel=\"nofollow noreferrer\">array_reverse()</a> on the original query's <code>posts</code> array but I tend not to mess with the original WP Query Object.</p>\n" }, { "answer_id": 263675, "author": "Abdul Awal Uzzal", "author_id": 31449, "author_profile": "https://wordpress.stackexchange.com/users/31449", "pm_score": 0, "selected": false, "text": "<p>Here you go...</p>\n\n<pre><code>&lt;?php\n$per_page = 4;\n$post_query = new WP_Query('post_type=post&amp;posts_per_page='.$per_page);\n$total_found_posts = $post_query-&gt;found_posts;\n\nif($total_found_posts &gt;= $per_page){\n $count_from = $per_page;\n} elseif ($total_found_posts &lt; $per_page){\n $count_from = $total_found_posts;\n}\n\nif (have_posts()) : while (have_posts()) : the_post();\n\nthe_title();\n\necho 'Serial #'. $count_from--; \n\nendwhile;\nendif;\nwp_reset_postdata();\n?&gt;\n</code></pre>\n" }, { "answer_id": 263686, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 2, "selected": true, "text": "<p>To print a decreasing counter for the main home query, without sticky posts, you can try:</p>\n\n<pre><code>// current page number - paged is 0 on the home page, we use 1 instead\n$_current_page = is_paged() ? get_query_var( 'paged', 1 ) : 1; \n\n// posts per page\n$_ppp = get_query_var( 'posts_per_page', get_option( 'posts_per_page' ) );\n\n// current post index on the current page\n$_current_post = $wp_query-&gt;current_post;\n\n// total number of found posts\n$_total_posts = $wp_query-&gt;found_posts;\n\n// Decreasing counter \necho $counter = $_total_posts - ( $_current_page - 1 ) * $_ppp - $_current_post;\n</code></pre>\n\n<p><strong>Example:</strong></p>\n\n<p>For total of 10 posts, with 4 posts per page, the decreasing counter should be:</p>\n\n<pre><code>Page 1: \n 10 - ( 1 - 1 ) * 4 - 0 = 10\n 10 - ( 1 - 1 ) * 4 - 1 = 9\n 10 - ( 1 - 1 ) * 4 - 2 = 8\n 10 - ( 1 - 1 ) * 4 - 3 = 7\n\nPage 2: \n 10 - ( 2 - 1 ) * 4 - 0 = 6\n 10 - ( 2 - 1 ) * 4 - 1 = 5\n 10 - ( 2 - 1 ) * 4 - 2 = 4\n 10 - ( 2 - 1 ) * 4 - 3 = 3\n\nPage 3: \n 10 - ( 3 - 1 ) * 4 - 0 = 2\n 10 - ( 3 - 1 ) * 4 - 1 = 1\n</code></pre>\n\n<p>or:</p>\n\n<pre><code>Page 1: 10,9,8,7\nPage 2: 6,5,4,3\nPage 3: 2,1\n</code></pre>\n\n<p><strong>Update:</strong></p>\n\n<p>To support sticky posts we can adjust the above counter with:</p>\n\n<pre><code>// Decreasing counter \necho $counter = $_total_posts\n + $sticky_offset \n - ( $_current_page - 1 ) * $_ppp \n - $_current_post;\n</code></pre>\n\n<p>where we define:</p>\n\n<pre><code>$sticky_offset = is_home() &amp;&amp; ! is_paged() &amp;&amp; $_total_posts &gt; $_ppp \n ? $wp_query-&gt;post_count - $_ppp \n : 0;\n</code></pre>\n\n<p>Note that there can be three cases of sticky posts: </p>\n\n<ol>\n<li>all sticky posts come from the first (home) page. (The number of displayed posts on the homepage is the same as without sticky posts).</li>\n<li>negative of 1) </li>\n<li>mixed 1) and 2)</li>\n</ol>\n\n<p>Our adjustments should handle all three cases.</p>\n" } ]
2017/04/14
[ "https://wordpress.stackexchange.com/questions/263671", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/83660/" ]
I'm trying to input the numer of the post next to it, but in the reverse order, which means not 1 2 3 4 but 4 3 2 1 . I have succeeded into doing it in the "right" order with this : ``` <?php if (have_posts()) : while (have_posts()) : the_post(); ?> <?php echo $wp_query->current_post + 1; ?> ``` but I can't figure out how to do the opposite. Morethough, when I have my posts in several pages, it breaks aka PAGE 1 : 1234 PAGE 2 : 1234 (should be 5678) I have tried this : ``` <?php echo $wp_query->found_posts - $wp_query->current_post ?> ``` which inputs 8765 and then the next page 8765 instead of 4321...
To print a decreasing counter for the main home query, without sticky posts, you can try: ``` // current page number - paged is 0 on the home page, we use 1 instead $_current_page = is_paged() ? get_query_var( 'paged', 1 ) : 1; // posts per page $_ppp = get_query_var( 'posts_per_page', get_option( 'posts_per_page' ) ); // current post index on the current page $_current_post = $wp_query->current_post; // total number of found posts $_total_posts = $wp_query->found_posts; // Decreasing counter echo $counter = $_total_posts - ( $_current_page - 1 ) * $_ppp - $_current_post; ``` **Example:** For total of 10 posts, with 4 posts per page, the decreasing counter should be: ``` Page 1: 10 - ( 1 - 1 ) * 4 - 0 = 10 10 - ( 1 - 1 ) * 4 - 1 = 9 10 - ( 1 - 1 ) * 4 - 2 = 8 10 - ( 1 - 1 ) * 4 - 3 = 7 Page 2: 10 - ( 2 - 1 ) * 4 - 0 = 6 10 - ( 2 - 1 ) * 4 - 1 = 5 10 - ( 2 - 1 ) * 4 - 2 = 4 10 - ( 2 - 1 ) * 4 - 3 = 3 Page 3: 10 - ( 3 - 1 ) * 4 - 0 = 2 10 - ( 3 - 1 ) * 4 - 1 = 1 ``` or: ``` Page 1: 10,9,8,7 Page 2: 6,5,4,3 Page 3: 2,1 ``` **Update:** To support sticky posts we can adjust the above counter with: ``` // Decreasing counter echo $counter = $_total_posts + $sticky_offset - ( $_current_page - 1 ) * $_ppp - $_current_post; ``` where we define: ``` $sticky_offset = is_home() && ! is_paged() && $_total_posts > $_ppp ? $wp_query->post_count - $_ppp : 0; ``` Note that there can be three cases of sticky posts: 1. all sticky posts come from the first (home) page. (The number of displayed posts on the homepage is the same as without sticky posts). 2. negative of 1) 3. mixed 1) and 2) Our adjustments should handle all three cases.
263,678
<p>I have tried numerous ways to prevent the browser's back button from allowing someone from using it to go back into a visitors logged out profile. The codes I used were supposed to prevent the browser from caching data from the last page visited after logout. They don't work. Wordpress logs the visitor out once they click the logged out button, yes this portion wors. Unfortunately, you can see the last page visited by the person who was logged on. The session is destroyed but the cache still holds the info for the last page visited. If you click any link on the profile page you will be brought back to the login page. You were not supposed to have been able to leave this login page without logging in. What code can use to force the browser to delete the data in the cache so the someone can not view info from a loggedout profile. Javascript would pose a security risk. Yes, I know that you can not delete the browser's history, but there must be a secure code for this. Wordpress comes with file that destroys the session but I can't find that file in the twenty sixteen code. Also, these codes do not work:</p> <pre><code> if(!isset($_SESSION['logged_in'])) : header("Location: login.php"); unset($_SESSION['logged_in']); session_destroy(); </code></pre> <p>Can you Pleeease help!!!</p>
[ { "answer_id": 263672, "author": "Howdy_McGee", "author_id": 7355, "author_profile": "https://wordpress.stackexchange.com/users/7355", "pm_score": 0, "selected": false, "text": "<p>Strange question. You can create a secondary query or run a hook into <a href=\"https://developer.wordpress.org/reference/hooks/pre_get_posts/\" rel=\"nofollow noreferrer\">pre_get_posts</a> but the general idea is you would <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters\" rel=\"nofollow noreferrer\">order by ID</a> in Descending Order:</p>\n\n<pre><code>$query = new WP_Query( array(\n 'orderby' =&gt; array( 'ID' =&gt; 'DESC' ),\n) );\n</code></pre>\n\n<p>You could also probably run <a href=\"http://php.net/manual/en/function.array-reverse.php\" rel=\"nofollow noreferrer\">array_reverse()</a> on the original query's <code>posts</code> array but I tend not to mess with the original WP Query Object.</p>\n" }, { "answer_id": 263675, "author": "Abdul Awal Uzzal", "author_id": 31449, "author_profile": "https://wordpress.stackexchange.com/users/31449", "pm_score": 0, "selected": false, "text": "<p>Here you go...</p>\n\n<pre><code>&lt;?php\n$per_page = 4;\n$post_query = new WP_Query('post_type=post&amp;posts_per_page='.$per_page);\n$total_found_posts = $post_query-&gt;found_posts;\n\nif($total_found_posts &gt;= $per_page){\n $count_from = $per_page;\n} elseif ($total_found_posts &lt; $per_page){\n $count_from = $total_found_posts;\n}\n\nif (have_posts()) : while (have_posts()) : the_post();\n\nthe_title();\n\necho 'Serial #'. $count_from--; \n\nendwhile;\nendif;\nwp_reset_postdata();\n?&gt;\n</code></pre>\n" }, { "answer_id": 263686, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 2, "selected": true, "text": "<p>To print a decreasing counter for the main home query, without sticky posts, you can try:</p>\n\n<pre><code>// current page number - paged is 0 on the home page, we use 1 instead\n$_current_page = is_paged() ? get_query_var( 'paged', 1 ) : 1; \n\n// posts per page\n$_ppp = get_query_var( 'posts_per_page', get_option( 'posts_per_page' ) );\n\n// current post index on the current page\n$_current_post = $wp_query-&gt;current_post;\n\n// total number of found posts\n$_total_posts = $wp_query-&gt;found_posts;\n\n// Decreasing counter \necho $counter = $_total_posts - ( $_current_page - 1 ) * $_ppp - $_current_post;\n</code></pre>\n\n<p><strong>Example:</strong></p>\n\n<p>For total of 10 posts, with 4 posts per page, the decreasing counter should be:</p>\n\n<pre><code>Page 1: \n 10 - ( 1 - 1 ) * 4 - 0 = 10\n 10 - ( 1 - 1 ) * 4 - 1 = 9\n 10 - ( 1 - 1 ) * 4 - 2 = 8\n 10 - ( 1 - 1 ) * 4 - 3 = 7\n\nPage 2: \n 10 - ( 2 - 1 ) * 4 - 0 = 6\n 10 - ( 2 - 1 ) * 4 - 1 = 5\n 10 - ( 2 - 1 ) * 4 - 2 = 4\n 10 - ( 2 - 1 ) * 4 - 3 = 3\n\nPage 3: \n 10 - ( 3 - 1 ) * 4 - 0 = 2\n 10 - ( 3 - 1 ) * 4 - 1 = 1\n</code></pre>\n\n<p>or:</p>\n\n<pre><code>Page 1: 10,9,8,7\nPage 2: 6,5,4,3\nPage 3: 2,1\n</code></pre>\n\n<p><strong>Update:</strong></p>\n\n<p>To support sticky posts we can adjust the above counter with:</p>\n\n<pre><code>// Decreasing counter \necho $counter = $_total_posts\n + $sticky_offset \n - ( $_current_page - 1 ) * $_ppp \n - $_current_post;\n</code></pre>\n\n<p>where we define:</p>\n\n<pre><code>$sticky_offset = is_home() &amp;&amp; ! is_paged() &amp;&amp; $_total_posts &gt; $_ppp \n ? $wp_query-&gt;post_count - $_ppp \n : 0;\n</code></pre>\n\n<p>Note that there can be three cases of sticky posts: </p>\n\n<ol>\n<li>all sticky posts come from the first (home) page. (The number of displayed posts on the homepage is the same as without sticky posts).</li>\n<li>negative of 1) </li>\n<li>mixed 1) and 2)</li>\n</ol>\n\n<p>Our adjustments should handle all three cases.</p>\n" } ]
2017/04/15
[ "https://wordpress.stackexchange.com/questions/263678", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/117689/" ]
I have tried numerous ways to prevent the browser's back button from allowing someone from using it to go back into a visitors logged out profile. The codes I used were supposed to prevent the browser from caching data from the last page visited after logout. They don't work. Wordpress logs the visitor out once they click the logged out button, yes this portion wors. Unfortunately, you can see the last page visited by the person who was logged on. The session is destroyed but the cache still holds the info for the last page visited. If you click any link on the profile page you will be brought back to the login page. You were not supposed to have been able to leave this login page without logging in. What code can use to force the browser to delete the data in the cache so the someone can not view info from a loggedout profile. Javascript would pose a security risk. Yes, I know that you can not delete the browser's history, but there must be a secure code for this. Wordpress comes with file that destroys the session but I can't find that file in the twenty sixteen code. Also, these codes do not work: ``` if(!isset($_SESSION['logged_in'])) : header("Location: login.php"); unset($_SESSION['logged_in']); session_destroy(); ``` Can you Pleeease help!!!
To print a decreasing counter for the main home query, without sticky posts, you can try: ``` // current page number - paged is 0 on the home page, we use 1 instead $_current_page = is_paged() ? get_query_var( 'paged', 1 ) : 1; // posts per page $_ppp = get_query_var( 'posts_per_page', get_option( 'posts_per_page' ) ); // current post index on the current page $_current_post = $wp_query->current_post; // total number of found posts $_total_posts = $wp_query->found_posts; // Decreasing counter echo $counter = $_total_posts - ( $_current_page - 1 ) * $_ppp - $_current_post; ``` **Example:** For total of 10 posts, with 4 posts per page, the decreasing counter should be: ``` Page 1: 10 - ( 1 - 1 ) * 4 - 0 = 10 10 - ( 1 - 1 ) * 4 - 1 = 9 10 - ( 1 - 1 ) * 4 - 2 = 8 10 - ( 1 - 1 ) * 4 - 3 = 7 Page 2: 10 - ( 2 - 1 ) * 4 - 0 = 6 10 - ( 2 - 1 ) * 4 - 1 = 5 10 - ( 2 - 1 ) * 4 - 2 = 4 10 - ( 2 - 1 ) * 4 - 3 = 3 Page 3: 10 - ( 3 - 1 ) * 4 - 0 = 2 10 - ( 3 - 1 ) * 4 - 1 = 1 ``` or: ``` Page 1: 10,9,8,7 Page 2: 6,5,4,3 Page 3: 2,1 ``` **Update:** To support sticky posts we can adjust the above counter with: ``` // Decreasing counter echo $counter = $_total_posts + $sticky_offset - ( $_current_page - 1 ) * $_ppp - $_current_post; ``` where we define: ``` $sticky_offset = is_home() && ! is_paged() && $_total_posts > $_ppp ? $wp_query->post_count - $_ppp : 0; ``` Note that there can be three cases of sticky posts: 1. all sticky posts come from the first (home) page. (The number of displayed posts on the homepage is the same as without sticky posts). 2. negative of 1) 3. mixed 1) and 2) Our adjustments should handle all three cases.
263,690
<p>Is there significant risk in not keeping a theme updated?</p> <p>We have various themes which we have purchased and modified. It would be a lot of work to install theme updates and re-implement our changes. Do themes, not kept updated, pose a significant security risk?</p>
[ { "answer_id": 263672, "author": "Howdy_McGee", "author_id": 7355, "author_profile": "https://wordpress.stackexchange.com/users/7355", "pm_score": 0, "selected": false, "text": "<p>Strange question. You can create a secondary query or run a hook into <a href=\"https://developer.wordpress.org/reference/hooks/pre_get_posts/\" rel=\"nofollow noreferrer\">pre_get_posts</a> but the general idea is you would <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters\" rel=\"nofollow noreferrer\">order by ID</a> in Descending Order:</p>\n\n<pre><code>$query = new WP_Query( array(\n 'orderby' =&gt; array( 'ID' =&gt; 'DESC' ),\n) );\n</code></pre>\n\n<p>You could also probably run <a href=\"http://php.net/manual/en/function.array-reverse.php\" rel=\"nofollow noreferrer\">array_reverse()</a> on the original query's <code>posts</code> array but I tend not to mess with the original WP Query Object.</p>\n" }, { "answer_id": 263675, "author": "Abdul Awal Uzzal", "author_id": 31449, "author_profile": "https://wordpress.stackexchange.com/users/31449", "pm_score": 0, "selected": false, "text": "<p>Here you go...</p>\n\n<pre><code>&lt;?php\n$per_page = 4;\n$post_query = new WP_Query('post_type=post&amp;posts_per_page='.$per_page);\n$total_found_posts = $post_query-&gt;found_posts;\n\nif($total_found_posts &gt;= $per_page){\n $count_from = $per_page;\n} elseif ($total_found_posts &lt; $per_page){\n $count_from = $total_found_posts;\n}\n\nif (have_posts()) : while (have_posts()) : the_post();\n\nthe_title();\n\necho 'Serial #'. $count_from--; \n\nendwhile;\nendif;\nwp_reset_postdata();\n?&gt;\n</code></pre>\n" }, { "answer_id": 263686, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 2, "selected": true, "text": "<p>To print a decreasing counter for the main home query, without sticky posts, you can try:</p>\n\n<pre><code>// current page number - paged is 0 on the home page, we use 1 instead\n$_current_page = is_paged() ? get_query_var( 'paged', 1 ) : 1; \n\n// posts per page\n$_ppp = get_query_var( 'posts_per_page', get_option( 'posts_per_page' ) );\n\n// current post index on the current page\n$_current_post = $wp_query-&gt;current_post;\n\n// total number of found posts\n$_total_posts = $wp_query-&gt;found_posts;\n\n// Decreasing counter \necho $counter = $_total_posts - ( $_current_page - 1 ) * $_ppp - $_current_post;\n</code></pre>\n\n<p><strong>Example:</strong></p>\n\n<p>For total of 10 posts, with 4 posts per page, the decreasing counter should be:</p>\n\n<pre><code>Page 1: \n 10 - ( 1 - 1 ) * 4 - 0 = 10\n 10 - ( 1 - 1 ) * 4 - 1 = 9\n 10 - ( 1 - 1 ) * 4 - 2 = 8\n 10 - ( 1 - 1 ) * 4 - 3 = 7\n\nPage 2: \n 10 - ( 2 - 1 ) * 4 - 0 = 6\n 10 - ( 2 - 1 ) * 4 - 1 = 5\n 10 - ( 2 - 1 ) * 4 - 2 = 4\n 10 - ( 2 - 1 ) * 4 - 3 = 3\n\nPage 3: \n 10 - ( 3 - 1 ) * 4 - 0 = 2\n 10 - ( 3 - 1 ) * 4 - 1 = 1\n</code></pre>\n\n<p>or:</p>\n\n<pre><code>Page 1: 10,9,8,7\nPage 2: 6,5,4,3\nPage 3: 2,1\n</code></pre>\n\n<p><strong>Update:</strong></p>\n\n<p>To support sticky posts we can adjust the above counter with:</p>\n\n<pre><code>// Decreasing counter \necho $counter = $_total_posts\n + $sticky_offset \n - ( $_current_page - 1 ) * $_ppp \n - $_current_post;\n</code></pre>\n\n<p>where we define:</p>\n\n<pre><code>$sticky_offset = is_home() &amp;&amp; ! is_paged() &amp;&amp; $_total_posts &gt; $_ppp \n ? $wp_query-&gt;post_count - $_ppp \n : 0;\n</code></pre>\n\n<p>Note that there can be three cases of sticky posts: </p>\n\n<ol>\n<li>all sticky posts come from the first (home) page. (The number of displayed posts on the homepage is the same as without sticky posts).</li>\n<li>negative of 1) </li>\n<li>mixed 1) and 2)</li>\n</ol>\n\n<p>Our adjustments should handle all three cases.</p>\n" } ]
2017/04/15
[ "https://wordpress.stackexchange.com/questions/263690", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/117705/" ]
Is there significant risk in not keeping a theme updated? We have various themes which we have purchased and modified. It would be a lot of work to install theme updates and re-implement our changes. Do themes, not kept updated, pose a significant security risk?
To print a decreasing counter for the main home query, without sticky posts, you can try: ``` // current page number - paged is 0 on the home page, we use 1 instead $_current_page = is_paged() ? get_query_var( 'paged', 1 ) : 1; // posts per page $_ppp = get_query_var( 'posts_per_page', get_option( 'posts_per_page' ) ); // current post index on the current page $_current_post = $wp_query->current_post; // total number of found posts $_total_posts = $wp_query->found_posts; // Decreasing counter echo $counter = $_total_posts - ( $_current_page - 1 ) * $_ppp - $_current_post; ``` **Example:** For total of 10 posts, with 4 posts per page, the decreasing counter should be: ``` Page 1: 10 - ( 1 - 1 ) * 4 - 0 = 10 10 - ( 1 - 1 ) * 4 - 1 = 9 10 - ( 1 - 1 ) * 4 - 2 = 8 10 - ( 1 - 1 ) * 4 - 3 = 7 Page 2: 10 - ( 2 - 1 ) * 4 - 0 = 6 10 - ( 2 - 1 ) * 4 - 1 = 5 10 - ( 2 - 1 ) * 4 - 2 = 4 10 - ( 2 - 1 ) * 4 - 3 = 3 Page 3: 10 - ( 3 - 1 ) * 4 - 0 = 2 10 - ( 3 - 1 ) * 4 - 1 = 1 ``` or: ``` Page 1: 10,9,8,7 Page 2: 6,5,4,3 Page 3: 2,1 ``` **Update:** To support sticky posts we can adjust the above counter with: ``` // Decreasing counter echo $counter = $_total_posts + $sticky_offset - ( $_current_page - 1 ) * $_ppp - $_current_post; ``` where we define: ``` $sticky_offset = is_home() && ! is_paged() && $_total_posts > $_ppp ? $wp_query->post_count - $_ppp : 0; ``` Note that there can be three cases of sticky posts: 1. all sticky posts come from the first (home) page. (The number of displayed posts on the homepage is the same as without sticky posts). 2. negative of 1) 3. mixed 1) and 2) Our adjustments should handle all three cases.
263,713
<p>I don't want to use the dropdown menu for sub/child pages on my Wordpress site, I want the pages to be listed in the sidebar on the parent page.</p> <p>This is the code I'm got so far (below), however it doesn't display anything in the sidebar so I'd appreciate some help!</p> <p>This is in my functions.php:</p> <pre><code>function wpb_list_child_pages() { global $post; if ( is_page() &amp;&amp; $post-&gt;post_parent ) $childpages = wp_list_pages( 'sort_column=menu_order&amp;title_li=&amp;child_of=' . $post-&gt;post_parent . '&amp;echo=0' ); else $childpages = wp_list_pages( 'sort_column=menu_order&amp;title_li=&amp;child_of=' . $post-&gt;ID . '&amp;echo=0' ); if ( $childpages ) { $string = '&lt;ul&gt;' . $childpages . '&lt;/ul&gt;'; } return $string; } add_shortcode('wpb_childpages', 'wpb_list_child_pages'); </code></pre> <p>and this is the call in the page.php (also tried sidebar.php):</p> <pre><code>&lt;?php wpb_list_child_pages(); ?&gt; </code></pre> <p>Any ideas what's going wrong?!</p> <p>On another note, I thought the parent page should be listed in the navigation to so it's easy to get back to (even though it's in the main nav). Is there a way of making the first list item the parent page?</p> <p>And yet another note, the only way I could find to turn off/hide the dropdown without CSS was to create a custom menu in Appearance > Menu and turn off the children. Is there another, better way?</p> <p>Thanks in advance!</p> <p><strong>EDIT</strong></p> <p>I just thought I'd add an update to show the markup I'm trying to output. I realised I need to get the title/parent page in there too! Here's the example markup:</p> <pre><code>&lt;nav class="page-nav"&gt; &lt;h3&gt;Navigation Title&lt;/h3&gt; &lt;ul&gt; &lt;li&gt;&lt;a href="#"&gt;Parent page&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Child page #1&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Child page #2&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Child page #3&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/nav&gt; </code></pre>
[ { "answer_id": 263755, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 2, "selected": true, "text": "<p>When trying to output a function's content, you have to notice whether you want to pass the data to another function (or something else which you want to feed), or you want to directly print it to the browser.</p>\n\n<p>If you use <code>return</code>, your function will return the data, so you can use them in a secondary function as below:</p>\n\n<p><code>second_function(first_function($input));</code></p>\n\n<p>If you want to simply print the content to the browser, use either <code>echo</code> or <code>print_r</code> instead of <code>return</code>. It's recommended to use <code>echo</code> in your case. However, do not use <code>echo</code> while making shortcode functions. It will output the text in the ways you don't want to.</p>\n\n<p>Back to our WordPress problem, shall we?</p>\n\n<p>For the provided structure, use the following function:</p>\n\n<pre><code>function wpb_list_child_pages() { \n\n global $post; \n\n if ( is_page() &amp;&amp; $post-&gt;post_parent )\n $childpages = wp_list_pages( 'sort_column=menu_order&amp;title_li=&amp;child_of=' . $post-&gt;post_parent . '&amp;echo=0' );\n else\n $childpages = wp_list_pages( 'sort_column=menu_order&amp;title_li=&amp;child_of=' . $post-&gt;ID . '&amp;echo=0' );\n if ( $childpages ) {\n $string = '\n &lt;nav class=\"page-nav\"&gt;\n &lt;h3&gt;Navigation Title&lt;/h3&gt;\n &lt;ul&gt;\n &lt;li&gt;&lt;a href=\"'.get_permalink($post-&gt;post_parent).'\"&gt;'.get_the_title($post-&gt;post_parent).'&lt;/a&gt;&lt;/li&gt;'\n .$childpages.\n '&lt;/ul&gt;\n &lt;/nav&gt;';\n }\n return $string;\n}\n\nadd_shortcode('wpb_childpages', 'wpb_list_child_pages');\n</code></pre>\n\n<p>Now, use this function to output your menu to wherever you wish:</p>\n\n<p><code>&lt;?php echo wpb_list_child_pages(); ?&gt;</code></p>\n\n<p>or do the shortcode:</p>\n\n<p><code>echo do_shortcode( ' [wpb_childpages] ' );</code></p>\n\n<p>or even use the shortcode in a text widget:</p>\n\n<p><code>[wpb_childpages]</code></p>\n\n<p>All producing the same result.</p>\n" }, { "answer_id": 310350, "author": "Niket Kale", "author_id": 147984, "author_profile": "https://wordpress.stackexchange.com/users/147984", "pm_score": -1, "selected": false, "text": "<p>Just put this code in your custom css menu of theme</p>\n\n<p>.children {display:none;}</p>\n\n<p>Or use the Flexi page plugin which will only show sub pages on any page when the root page is open in browser.</p>\n" } ]
2017/04/15
[ "https://wordpress.stackexchange.com/questions/263713", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/116827/" ]
I don't want to use the dropdown menu for sub/child pages on my Wordpress site, I want the pages to be listed in the sidebar on the parent page. This is the code I'm got so far (below), however it doesn't display anything in the sidebar so I'd appreciate some help! This is in my functions.php: ``` function wpb_list_child_pages() { global $post; if ( is_page() && $post->post_parent ) $childpages = wp_list_pages( 'sort_column=menu_order&title_li=&child_of=' . $post->post_parent . '&echo=0' ); else $childpages = wp_list_pages( 'sort_column=menu_order&title_li=&child_of=' . $post->ID . '&echo=0' ); if ( $childpages ) { $string = '<ul>' . $childpages . '</ul>'; } return $string; } add_shortcode('wpb_childpages', 'wpb_list_child_pages'); ``` and this is the call in the page.php (also tried sidebar.php): ``` <?php wpb_list_child_pages(); ?> ``` Any ideas what's going wrong?! On another note, I thought the parent page should be listed in the navigation to so it's easy to get back to (even though it's in the main nav). Is there a way of making the first list item the parent page? And yet another note, the only way I could find to turn off/hide the dropdown without CSS was to create a custom menu in Appearance > Menu and turn off the children. Is there another, better way? Thanks in advance! **EDIT** I just thought I'd add an update to show the markup I'm trying to output. I realised I need to get the title/parent page in there too! Here's the example markup: ``` <nav class="page-nav"> <h3>Navigation Title</h3> <ul> <li><a href="#">Parent page</a></li> <li><a href="#">Child page #1</a></li> <li><a href="#">Child page #2</a></li> <li><a href="#">Child page #3</a></li> </ul> </nav> ```
When trying to output a function's content, you have to notice whether you want to pass the data to another function (or something else which you want to feed), or you want to directly print it to the browser. If you use `return`, your function will return the data, so you can use them in a secondary function as below: `second_function(first_function($input));` If you want to simply print the content to the browser, use either `echo` or `print_r` instead of `return`. It's recommended to use `echo` in your case. However, do not use `echo` while making shortcode functions. It will output the text in the ways you don't want to. Back to our WordPress problem, shall we? For the provided structure, use the following function: ``` function wpb_list_child_pages() { global $post; if ( is_page() && $post->post_parent ) $childpages = wp_list_pages( 'sort_column=menu_order&title_li=&child_of=' . $post->post_parent . '&echo=0' ); else $childpages = wp_list_pages( 'sort_column=menu_order&title_li=&child_of=' . $post->ID . '&echo=0' ); if ( $childpages ) { $string = ' <nav class="page-nav"> <h3>Navigation Title</h3> <ul> <li><a href="'.get_permalink($post->post_parent).'">'.get_the_title($post->post_parent).'</a></li>' .$childpages. '</ul> </nav>'; } return $string; } add_shortcode('wpb_childpages', 'wpb_list_child_pages'); ``` Now, use this function to output your menu to wherever you wish: `<?php echo wpb_list_child_pages(); ?>` or do the shortcode: `echo do_shortcode( ' [wpb_childpages] ' );` or even use the shortcode in a text widget: `[wpb_childpages]` All producing the same result.
263,718
<p>I have registered a new post type and made a custom template to display it. According to WP´s latest support for CPT templates, all it takes to make it available for any given CPT is to place this header on the template file:</p> <pre><code>/** * Template Name: Single Book * Template Post Type: book */ </code></pre> <p>Then, following the template hierarchy, I named my template <code>single-book.php</code>. And alright, now I have this template available for the 'book' post type. It works. Cool!</p> <p>However, for some reason, I still need to <strong>manually select it within the post attribute section every time I create a new book</strong> as the <strong>default selection is the standard template for posts</strong>. (when the default should be my custom template after naming it as stated above, right? Unless I´m missing something...)</p> <p>So, the way it is, if by any chance I / the user forgets to change it, the CPT will obviously NOT display properly on the front-end as it isn´t using the template made for it.</p> <p>I must prevent that from happening and, as I´ll be working with plenty CPTs, I need the ability to choose from 2 approaches when registering a CPT:</p> <p>1- <strong>Determining which template is selected by default on the post attribute section.</strong> (ideal for CPTs that can use a range of custom templates depending on the circumstance, but making sure the default selection is appropriate and NOT any other standard template);</p> <p>2- <strong>Making the post attribute section DISAPPEAR for CPTs that should ONLY use a specific custom template.</strong> (while making sure that´s the one being used).</p> <p>I´ve done extensive research and couldn´t find anything at all on how to go about this.</p> <p>Yet, I suspect this not only can be easily achieved without much hassle but also that it has to do with some parameter within the post type array when registering it.</p> <p>I´m not sure, but maybe something along the lines of:</p> <pre><code>add_theme_support('custom-post', array ( 'book'=&gt; array ( 'singular' =&gt; ... , 'plural' =&gt; ... , 'supports' =&gt; array(...), 'some-parameter-to-set-default-template' =&gt; ... , 'some-parameter-to-disable-post-attribute-selection' =&gt; ... ), ) ); </code></pre> <p>Can anyone help?</p>
[ { "answer_id": 263755, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 2, "selected": true, "text": "<p>When trying to output a function's content, you have to notice whether you want to pass the data to another function (or something else which you want to feed), or you want to directly print it to the browser.</p>\n\n<p>If you use <code>return</code>, your function will return the data, so you can use them in a secondary function as below:</p>\n\n<p><code>second_function(first_function($input));</code></p>\n\n<p>If you want to simply print the content to the browser, use either <code>echo</code> or <code>print_r</code> instead of <code>return</code>. It's recommended to use <code>echo</code> in your case. However, do not use <code>echo</code> while making shortcode functions. It will output the text in the ways you don't want to.</p>\n\n<p>Back to our WordPress problem, shall we?</p>\n\n<p>For the provided structure, use the following function:</p>\n\n<pre><code>function wpb_list_child_pages() { \n\n global $post; \n\n if ( is_page() &amp;&amp; $post-&gt;post_parent )\n $childpages = wp_list_pages( 'sort_column=menu_order&amp;title_li=&amp;child_of=' . $post-&gt;post_parent . '&amp;echo=0' );\n else\n $childpages = wp_list_pages( 'sort_column=menu_order&amp;title_li=&amp;child_of=' . $post-&gt;ID . '&amp;echo=0' );\n if ( $childpages ) {\n $string = '\n &lt;nav class=\"page-nav\"&gt;\n &lt;h3&gt;Navigation Title&lt;/h3&gt;\n &lt;ul&gt;\n &lt;li&gt;&lt;a href=\"'.get_permalink($post-&gt;post_parent).'\"&gt;'.get_the_title($post-&gt;post_parent).'&lt;/a&gt;&lt;/li&gt;'\n .$childpages.\n '&lt;/ul&gt;\n &lt;/nav&gt;';\n }\n return $string;\n}\n\nadd_shortcode('wpb_childpages', 'wpb_list_child_pages');\n</code></pre>\n\n<p>Now, use this function to output your menu to wherever you wish:</p>\n\n<p><code>&lt;?php echo wpb_list_child_pages(); ?&gt;</code></p>\n\n<p>or do the shortcode:</p>\n\n<p><code>echo do_shortcode( ' [wpb_childpages] ' );</code></p>\n\n<p>or even use the shortcode in a text widget:</p>\n\n<p><code>[wpb_childpages]</code></p>\n\n<p>All producing the same result.</p>\n" }, { "answer_id": 310350, "author": "Niket Kale", "author_id": 147984, "author_profile": "https://wordpress.stackexchange.com/users/147984", "pm_score": -1, "selected": false, "text": "<p>Just put this code in your custom css menu of theme</p>\n\n<p>.children {display:none;}</p>\n\n<p>Or use the Flexi page plugin which will only show sub pages on any page when the root page is open in browser.</p>\n" } ]
2017/04/15
[ "https://wordpress.stackexchange.com/questions/263718", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/115596/" ]
I have registered a new post type and made a custom template to display it. According to WP´s latest support for CPT templates, all it takes to make it available for any given CPT is to place this header on the template file: ``` /** * Template Name: Single Book * Template Post Type: book */ ``` Then, following the template hierarchy, I named my template `single-book.php`. And alright, now I have this template available for the 'book' post type. It works. Cool! However, for some reason, I still need to **manually select it within the post attribute section every time I create a new book** as the **default selection is the standard template for posts**. (when the default should be my custom template after naming it as stated above, right? Unless I´m missing something...) So, the way it is, if by any chance I / the user forgets to change it, the CPT will obviously NOT display properly on the front-end as it isn´t using the template made for it. I must prevent that from happening and, as I´ll be working with plenty CPTs, I need the ability to choose from 2 approaches when registering a CPT: 1- **Determining which template is selected by default on the post attribute section.** (ideal for CPTs that can use a range of custom templates depending on the circumstance, but making sure the default selection is appropriate and NOT any other standard template); 2- **Making the post attribute section DISAPPEAR for CPTs that should ONLY use a specific custom template.** (while making sure that´s the one being used). I´ve done extensive research and couldn´t find anything at all on how to go about this. Yet, I suspect this not only can be easily achieved without much hassle but also that it has to do with some parameter within the post type array when registering it. I´m not sure, but maybe something along the lines of: ``` add_theme_support('custom-post', array ( 'book'=> array ( 'singular' => ... , 'plural' => ... , 'supports' => array(...), 'some-parameter-to-set-default-template' => ... , 'some-parameter-to-disable-post-attribute-selection' => ... ), ) ); ``` Can anyone help?
When trying to output a function's content, you have to notice whether you want to pass the data to another function (or something else which you want to feed), or you want to directly print it to the browser. If you use `return`, your function will return the data, so you can use them in a secondary function as below: `second_function(first_function($input));` If you want to simply print the content to the browser, use either `echo` or `print_r` instead of `return`. It's recommended to use `echo` in your case. However, do not use `echo` while making shortcode functions. It will output the text in the ways you don't want to. Back to our WordPress problem, shall we? For the provided structure, use the following function: ``` function wpb_list_child_pages() { global $post; if ( is_page() && $post->post_parent ) $childpages = wp_list_pages( 'sort_column=menu_order&title_li=&child_of=' . $post->post_parent . '&echo=0' ); else $childpages = wp_list_pages( 'sort_column=menu_order&title_li=&child_of=' . $post->ID . '&echo=0' ); if ( $childpages ) { $string = ' <nav class="page-nav"> <h3>Navigation Title</h3> <ul> <li><a href="'.get_permalink($post->post_parent).'">'.get_the_title($post->post_parent).'</a></li>' .$childpages. '</ul> </nav>'; } return $string; } add_shortcode('wpb_childpages', 'wpb_list_child_pages'); ``` Now, use this function to output your menu to wherever you wish: `<?php echo wpb_list_child_pages(); ?>` or do the shortcode: `echo do_shortcode( ' [wpb_childpages] ' );` or even use the shortcode in a text widget: `[wpb_childpages]` All producing the same result.
263,730
<p>Designer new to wordpress here. I want to take the featured image on a post and make it a hero image for the post single page. </p> <p>The way I would normally do this is to create a div, set width to 100%, height to whatever vh I want, and then set background to the image url in the CSS with background size set to cover. </p> <p>So how I'm trying to do this in Wordpress is like this:</p> <pre><code>&lt;section class="hero" style="background: url('&lt;?php echo $hero_image['url'];?&gt; ');" xmlns="http://www.w3.org/1999/html"&gt; </code></pre> <p>But that comes out a little wonky because setting background with inline styles overrides all the CSS back to default element stuff. Any ideas on how to do this better? Preferably without any plugins, as I'm trying to learn how to do as much in code as possible. Though I do already have Advanced Custom Fields and Custom Post Type UI installed and I'm using those extensively. </p>
[ { "answer_id": 263755, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 2, "selected": true, "text": "<p>When trying to output a function's content, you have to notice whether you want to pass the data to another function (or something else which you want to feed), or you want to directly print it to the browser.</p>\n\n<p>If you use <code>return</code>, your function will return the data, so you can use them in a secondary function as below:</p>\n\n<p><code>second_function(first_function($input));</code></p>\n\n<p>If you want to simply print the content to the browser, use either <code>echo</code> or <code>print_r</code> instead of <code>return</code>. It's recommended to use <code>echo</code> in your case. However, do not use <code>echo</code> while making shortcode functions. It will output the text in the ways you don't want to.</p>\n\n<p>Back to our WordPress problem, shall we?</p>\n\n<p>For the provided structure, use the following function:</p>\n\n<pre><code>function wpb_list_child_pages() { \n\n global $post; \n\n if ( is_page() &amp;&amp; $post-&gt;post_parent )\n $childpages = wp_list_pages( 'sort_column=menu_order&amp;title_li=&amp;child_of=' . $post-&gt;post_parent . '&amp;echo=0' );\n else\n $childpages = wp_list_pages( 'sort_column=menu_order&amp;title_li=&amp;child_of=' . $post-&gt;ID . '&amp;echo=0' );\n if ( $childpages ) {\n $string = '\n &lt;nav class=\"page-nav\"&gt;\n &lt;h3&gt;Navigation Title&lt;/h3&gt;\n &lt;ul&gt;\n &lt;li&gt;&lt;a href=\"'.get_permalink($post-&gt;post_parent).'\"&gt;'.get_the_title($post-&gt;post_parent).'&lt;/a&gt;&lt;/li&gt;'\n .$childpages.\n '&lt;/ul&gt;\n &lt;/nav&gt;';\n }\n return $string;\n}\n\nadd_shortcode('wpb_childpages', 'wpb_list_child_pages');\n</code></pre>\n\n<p>Now, use this function to output your menu to wherever you wish:</p>\n\n<p><code>&lt;?php echo wpb_list_child_pages(); ?&gt;</code></p>\n\n<p>or do the shortcode:</p>\n\n<p><code>echo do_shortcode( ' [wpb_childpages] ' );</code></p>\n\n<p>or even use the shortcode in a text widget:</p>\n\n<p><code>[wpb_childpages]</code></p>\n\n<p>All producing the same result.</p>\n" }, { "answer_id": 310350, "author": "Niket Kale", "author_id": 147984, "author_profile": "https://wordpress.stackexchange.com/users/147984", "pm_score": -1, "selected": false, "text": "<p>Just put this code in your custom css menu of theme</p>\n\n<p>.children {display:none;}</p>\n\n<p>Or use the Flexi page plugin which will only show sub pages on any page when the root page is open in browser.</p>\n" } ]
2017/04/16
[ "https://wordpress.stackexchange.com/questions/263730", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/117679/" ]
Designer new to wordpress here. I want to take the featured image on a post and make it a hero image for the post single page. The way I would normally do this is to create a div, set width to 100%, height to whatever vh I want, and then set background to the image url in the CSS with background size set to cover. So how I'm trying to do this in Wordpress is like this: ``` <section class="hero" style="background: url('<?php echo $hero_image['url'];?> ');" xmlns="http://www.w3.org/1999/html"> ``` But that comes out a little wonky because setting background with inline styles overrides all the CSS back to default element stuff. Any ideas on how to do this better? Preferably without any plugins, as I'm trying to learn how to do as much in code as possible. Though I do already have Advanced Custom Fields and Custom Post Type UI installed and I'm using those extensively.
When trying to output a function's content, you have to notice whether you want to pass the data to another function (or something else which you want to feed), or you want to directly print it to the browser. If you use `return`, your function will return the data, so you can use them in a secondary function as below: `second_function(first_function($input));` If you want to simply print the content to the browser, use either `echo` or `print_r` instead of `return`. It's recommended to use `echo` in your case. However, do not use `echo` while making shortcode functions. It will output the text in the ways you don't want to. Back to our WordPress problem, shall we? For the provided structure, use the following function: ``` function wpb_list_child_pages() { global $post; if ( is_page() && $post->post_parent ) $childpages = wp_list_pages( 'sort_column=menu_order&title_li=&child_of=' . $post->post_parent . '&echo=0' ); else $childpages = wp_list_pages( 'sort_column=menu_order&title_li=&child_of=' . $post->ID . '&echo=0' ); if ( $childpages ) { $string = ' <nav class="page-nav"> <h3>Navigation Title</h3> <ul> <li><a href="'.get_permalink($post->post_parent).'">'.get_the_title($post->post_parent).'</a></li>' .$childpages. '</ul> </nav>'; } return $string; } add_shortcode('wpb_childpages', 'wpb_list_child_pages'); ``` Now, use this function to output your menu to wherever you wish: `<?php echo wpb_list_child_pages(); ?>` or do the shortcode: `echo do_shortcode( ' [wpb_childpages] ' );` or even use the shortcode in a text widget: `[wpb_childpages]` All producing the same result.
263,747
<p>After about 3 days of searching and tinkering, I'm stuck. I'm not a coder, but I like to try.</p> <p>I have a short code that gets a horoscope from a table in my WordPress database (I created the table). However, I have since discovered that short codes don't allow "echo" or "print" to show the output correct. Instead of showing up on the page where I placed the short code, it appears at the top of the page because the short code is executed earlier.</p> <p>I just don't know how to take the $result and output it to the webpage. </p> <p>This is the short code and PHP:</p> <pre><code>function fl_aries_co_today_shortcode() { global $wpdb; $results = $wpdb-&gt;get_results("SELECT horoscope FROM wpaa_scope_co WHERE date = CURDATE() AND sign = 'aries'"); foreach($results as $r) { echo "&lt;p&gt;".$r-&gt;horoscope."&lt;/p&gt;"; } } add_shortcode( 'fl_aries_co_today','fl_aries_co_today_shortcode' ); </code></pre> <p>Echo doesn't work within short codes. How do I get the horoscope to appear as text on the page?</p> <p>(I know that I could learn to use a template page, but the short code option is just so quick and handy.)</p>
[ { "answer_id": 263755, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 2, "selected": true, "text": "<p>When trying to output a function's content, you have to notice whether you want to pass the data to another function (or something else which you want to feed), or you want to directly print it to the browser.</p>\n\n<p>If you use <code>return</code>, your function will return the data, so you can use them in a secondary function as below:</p>\n\n<p><code>second_function(first_function($input));</code></p>\n\n<p>If you want to simply print the content to the browser, use either <code>echo</code> or <code>print_r</code> instead of <code>return</code>. It's recommended to use <code>echo</code> in your case. However, do not use <code>echo</code> while making shortcode functions. It will output the text in the ways you don't want to.</p>\n\n<p>Back to our WordPress problem, shall we?</p>\n\n<p>For the provided structure, use the following function:</p>\n\n<pre><code>function wpb_list_child_pages() { \n\n global $post; \n\n if ( is_page() &amp;&amp; $post-&gt;post_parent )\n $childpages = wp_list_pages( 'sort_column=menu_order&amp;title_li=&amp;child_of=' . $post-&gt;post_parent . '&amp;echo=0' );\n else\n $childpages = wp_list_pages( 'sort_column=menu_order&amp;title_li=&amp;child_of=' . $post-&gt;ID . '&amp;echo=0' );\n if ( $childpages ) {\n $string = '\n &lt;nav class=\"page-nav\"&gt;\n &lt;h3&gt;Navigation Title&lt;/h3&gt;\n &lt;ul&gt;\n &lt;li&gt;&lt;a href=\"'.get_permalink($post-&gt;post_parent).'\"&gt;'.get_the_title($post-&gt;post_parent).'&lt;/a&gt;&lt;/li&gt;'\n .$childpages.\n '&lt;/ul&gt;\n &lt;/nav&gt;';\n }\n return $string;\n}\n\nadd_shortcode('wpb_childpages', 'wpb_list_child_pages');\n</code></pre>\n\n<p>Now, use this function to output your menu to wherever you wish:</p>\n\n<p><code>&lt;?php echo wpb_list_child_pages(); ?&gt;</code></p>\n\n<p>or do the shortcode:</p>\n\n<p><code>echo do_shortcode( ' [wpb_childpages] ' );</code></p>\n\n<p>or even use the shortcode in a text widget:</p>\n\n<p><code>[wpb_childpages]</code></p>\n\n<p>All producing the same result.</p>\n" }, { "answer_id": 310350, "author": "Niket Kale", "author_id": 147984, "author_profile": "https://wordpress.stackexchange.com/users/147984", "pm_score": -1, "selected": false, "text": "<p>Just put this code in your custom css menu of theme</p>\n\n<p>.children {display:none;}</p>\n\n<p>Or use the Flexi page plugin which will only show sub pages on any page when the root page is open in browser.</p>\n" } ]
2017/04/16
[ "https://wordpress.stackexchange.com/questions/263747", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/117744/" ]
After about 3 days of searching and tinkering, I'm stuck. I'm not a coder, but I like to try. I have a short code that gets a horoscope from a table in my WordPress database (I created the table). However, I have since discovered that short codes don't allow "echo" or "print" to show the output correct. Instead of showing up on the page where I placed the short code, it appears at the top of the page because the short code is executed earlier. I just don't know how to take the $result and output it to the webpage. This is the short code and PHP: ``` function fl_aries_co_today_shortcode() { global $wpdb; $results = $wpdb->get_results("SELECT horoscope FROM wpaa_scope_co WHERE date = CURDATE() AND sign = 'aries'"); foreach($results as $r) { echo "<p>".$r->horoscope."</p>"; } } add_shortcode( 'fl_aries_co_today','fl_aries_co_today_shortcode' ); ``` Echo doesn't work within short codes. How do I get the horoscope to appear as text on the page? (I know that I could learn to use a template page, but the short code option is just so quick and handy.)
When trying to output a function's content, you have to notice whether you want to pass the data to another function (or something else which you want to feed), or you want to directly print it to the browser. If you use `return`, your function will return the data, so you can use them in a secondary function as below: `second_function(first_function($input));` If you want to simply print the content to the browser, use either `echo` or `print_r` instead of `return`. It's recommended to use `echo` in your case. However, do not use `echo` while making shortcode functions. It will output the text in the ways you don't want to. Back to our WordPress problem, shall we? For the provided structure, use the following function: ``` function wpb_list_child_pages() { global $post; if ( is_page() && $post->post_parent ) $childpages = wp_list_pages( 'sort_column=menu_order&title_li=&child_of=' . $post->post_parent . '&echo=0' ); else $childpages = wp_list_pages( 'sort_column=menu_order&title_li=&child_of=' . $post->ID . '&echo=0' ); if ( $childpages ) { $string = ' <nav class="page-nav"> <h3>Navigation Title</h3> <ul> <li><a href="'.get_permalink($post->post_parent).'">'.get_the_title($post->post_parent).'</a></li>' .$childpages. '</ul> </nav>'; } return $string; } add_shortcode('wpb_childpages', 'wpb_list_child_pages'); ``` Now, use this function to output your menu to wherever you wish: `<?php echo wpb_list_child_pages(); ?>` or do the shortcode: `echo do_shortcode( ' [wpb_childpages] ' );` or even use the shortcode in a text widget: `[wpb_childpages]` All producing the same result.
263,795
<p>I recently dramatically changed the structure of my site and I'm getting errors from pages that existed on the past (and they will probably) exist on the future again.</p> <p>eg: </p> <p>in the past I had 44 pages (<code>example.com/manual-cat/how-to/page/44/</code>) and right now I only have posts to have <code>39 pages</code>, but I will probably have more pages in the future.</p> <p>How can I temporarily redirect <strong>ONLY</strong> if the page doesn't exists?</p> <p>The reason I need to do this automatically is that I have 100 plus categories with errors and it would be impossible to manage this manually by doing individual redirects.</p> <p>If this had to be done on the server side, please be aware that I'm on nginx.</p>
[ { "answer_id": 263796, "author": "Max", "author_id": 115933, "author_profile": "https://wordpress.stackexchange.com/users/115933", "pm_score": -1, "selected": false, "text": "<p>You can use and edit .htaccess file</p>\n\n<pre><code># Redirect old file path to new file path\nRedirect /manual-cat/how-to/page/44/ http://example.com/newdirectory/newfile.html\n</code></pre>\n" }, { "answer_id": 263798, "author": "Jeff Mattson", "author_id": 93714, "author_profile": "https://wordpress.stackexchange.com/users/93714", "pm_score": 0, "selected": false, "text": "<p>In your .htaccess try:</p>\n\n<pre><code>&lt;IfModule mod_rewrite.c&gt;\nRewriteEngine On\n\nRewriteCond %{REQUEST_FILENAME} -f [OR]\nRewriteCond %{REQUEST_FILENAME} -d\nRewriteRule ^(.+) - [PT,L]\n\nRewriteRule ^match/this/(.*)$ somewhere/else/$1 [L]\n&lt;/IfModule&gt;\n</code></pre>\n\n<p>So if it doesn't hit a file or a directory it will go to the rewrite rule at the bottom. </p>\n\n<p>For nginx:</p>\n\n<pre><code># nginx configuration\nlocation / {\nif (-e $request_filename){\nrewrite ^/match/this/(.*)$ /somewhere/else/$1 break;\n}\n}\n</code></pre>\n" }, { "answer_id": 263800, "author": "fuxia", "author_id": 73, "author_profile": "https://wordpress.stackexchange.com/users/73", "pm_score": 4, "selected": true, "text": "<p>You can detect non-existent pages only with WordPress. Normal URLs don't point to a physical resource, their path is mapped internally to database content instead.</p>\n\n<p>That means you need a WP hook that fires only when no content has been found for an URL. That hook is <code>404_template</code>. This is called when WP trys to include the 404 template from your theme (or the <code>index.php</code> if there is no <code>404.php</code>).</p>\n\n<p>You can use it for redirects, because no output has been sent at this time.</p>\n\n<p>Create a custom plugin, and add your redirection rules in that.</p>\n\n<p>Here is an example:</p>\n\n<pre><code>&lt;?php # -*- coding: utf-8 -*-\n/**\n * Plugin Name: Custom Redirects\n */\n\nadd_filter( '404_template', function( $template ) {\n\n $request = filter_input( INPUT_SERVER, 'REQUEST_URI', FILTER_SANITIZE_STRING );\n\n if ( ! $request ) {\n return $template;\n }\n\n $static = [\n '/old/path/1/' =&gt; 'new/path/1/',\n '/old/path/2/' =&gt; 'new/path/2/',\n '/old/path/3/' =&gt; 'new/path/3/',\n ];\n\n if ( isset ( $static[ $request ] ) ) {\n wp_redirect( $static[ $request ], 301 );\n exit;\n }\n\n $regex = [\n '/pattern/1/(\\d+)/' =&gt; '/target/1/$1/',\n '/pattern/2/([a-z]+)/' =&gt; '/target/2/$1/',\n ];\n\n foreach( $regex as $pattern =&gt; $replacement ) {\n if ( ! preg_match( $pattern, $request ) ) {\n continue;\n }\n\n $url = preg_replace( $pattern, $replacement, $request );\n wp_redirect( $url, 301 );\n exit;\n }\n\n // not our business, let WP do the rest.\n return $template;\n\n}, -4000 ); // hook in quite early\n</code></pre>\n\n<p>You are of course not limited to a simple map. I have versions of that plugin with quite some very complex for some clients, and you could even build an UI to create that map in the admin backend … but in most cases, this simple approach will do what you want.</p>\n" } ]
2017/04/16
[ "https://wordpress.stackexchange.com/questions/263795", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/18693/" ]
I recently dramatically changed the structure of my site and I'm getting errors from pages that existed on the past (and they will probably) exist on the future again. eg: in the past I had 44 pages (`example.com/manual-cat/how-to/page/44/`) and right now I only have posts to have `39 pages`, but I will probably have more pages in the future. How can I temporarily redirect **ONLY** if the page doesn't exists? The reason I need to do this automatically is that I have 100 plus categories with errors and it would be impossible to manage this manually by doing individual redirects. If this had to be done on the server side, please be aware that I'm on nginx.
You can detect non-existent pages only with WordPress. Normal URLs don't point to a physical resource, their path is mapped internally to database content instead. That means you need a WP hook that fires only when no content has been found for an URL. That hook is `404_template`. This is called when WP trys to include the 404 template from your theme (or the `index.php` if there is no `404.php`). You can use it for redirects, because no output has been sent at this time. Create a custom plugin, and add your redirection rules in that. Here is an example: ``` <?php # -*- coding: utf-8 -*- /** * Plugin Name: Custom Redirects */ add_filter( '404_template', function( $template ) { $request = filter_input( INPUT_SERVER, 'REQUEST_URI', FILTER_SANITIZE_STRING ); if ( ! $request ) { return $template; } $static = [ '/old/path/1/' => 'new/path/1/', '/old/path/2/' => 'new/path/2/', '/old/path/3/' => 'new/path/3/', ]; if ( isset ( $static[ $request ] ) ) { wp_redirect( $static[ $request ], 301 ); exit; } $regex = [ '/pattern/1/(\d+)/' => '/target/1/$1/', '/pattern/2/([a-z]+)/' => '/target/2/$1/', ]; foreach( $regex as $pattern => $replacement ) { if ( ! preg_match( $pattern, $request ) ) { continue; } $url = preg_replace( $pattern, $replacement, $request ); wp_redirect( $url, 301 ); exit; } // not our business, let WP do the rest. return $template; }, -4000 ); // hook in quite early ``` You are of course not limited to a simple map. I have versions of that plugin with quite some very complex for some clients, and you could even build an UI to create that map in the admin backend … but in most cases, this simple approach will do what you want.
263,804
<p>I have a form to create new post and I pass my post_category into post creating array, but it not insert into that category , it insert into Uncategorized category.And I want to see the post using the menu that I created using categories. </p> <p>I pass may data to following array to create post.Its working but it insert post into Uncategorized(default) category. any solution?</p> <pre><code> $post = array('post_type'=&gt;'post', 'post_author'=&gt;$author, 'post_status'=&gt;'publish', 'post_title' =&gt; 'Test Title', 'post_category' =&gt; '679' ); </code></pre>
[ { "answer_id": 263810, "author": "mayersdesign", "author_id": 106965, "author_profile": "https://wordpress.stackexchange.com/users/106965", "pm_score": 1, "selected": false, "text": "<p>The post_category parameter has to be an array, try this:</p>\n\n<pre><code>$post = array('post_type'=&gt;'post',\n 'post_author'=&gt;$author,\n 'post_status'=&gt;'publish',\n 'post_title' =&gt; 'Test Title',\n 'post_category' =&gt; array('679')\n);\n</code></pre>\n\n<p>Ref: <a href=\"http://codex.wordpress.org/Function_Reference/wp_insert_post#Parameters\" rel=\"nofollow noreferrer\">http://codex.wordpress.org/Function_Reference/wp_insert_post#Parameters</a></p>\n\n<p>If that doesn't work for you, try using category_name:</p>\n\n<pre><code>'category_name' =&gt; 'category_name',\n</code></pre>\n" }, { "answer_id": 263863, "author": "Preshan Pradeepa", "author_id": 117616, "author_profile": "https://wordpress.stackexchange.com/users/117616", "pm_score": 1, "selected": true, "text": "<p>Issue is in following line</p>\n\n<blockquote>\n <p>'post_category' => array('679')</p>\n</blockquote>\n\n<p>Use <code>'post_category' =&gt; array(679)</code> without single quote.</p>\n" } ]
2017/04/17
[ "https://wordpress.stackexchange.com/questions/263804", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/117616/" ]
I have a form to create new post and I pass my post\_category into post creating array, but it not insert into that category , it insert into Uncategorized category.And I want to see the post using the menu that I created using categories. I pass may data to following array to create post.Its working but it insert post into Uncategorized(default) category. any solution? ``` $post = array('post_type'=>'post', 'post_author'=>$author, 'post_status'=>'publish', 'post_title' => 'Test Title', 'post_category' => '679' ); ```
Issue is in following line > > 'post\_category' => array('679') > > > Use `'post_category' => array(679)` without single quote.
263,813
<p>I'm trying to use tags of the single post, as meta keywords.</p> <p>I tried using this:</p> <pre><code>&lt;meta name="keywords" content="&lt;?php the_tags('',',','');?&gt;test&lt;?php }?&gt;"/&gt; </code></pre> <p>It works, but the output is:</p> <pre><code>&lt;meta name="keywords" content="&lt;a href="http://127.0.0.1/1/tag/aquaman/" rel="tag"&gt;aquaman&lt;/a&gt;,&lt;a href="http://127.0.0.1/1/tag/batman/" rel="tag"&gt;batman&lt;/a&gt;,&lt;a href="http://127.0.0.1/1/tag/wonder-woman/" rel="tag"&gt;wonder woman&lt;/a&gt;"/&gt; </code></pre> <p>Is it possible to remove the tags link/URL? And just the text/tag itself will appear?</p>
[ { "answer_id": 263814, "author": "Aniruddha Gawade", "author_id": 101818, "author_profile": "https://wordpress.stackexchange.com/users/101818", "pm_score": 3, "selected": false, "text": "<p>Use <code>get_the_tag_list()</code> instead of <code>the_tags()</code>, since <code>the_tags()</code> prints the results while <code>get_the_tag_list()</code> returns it.</p>\n\n<p>See documentation: <a href=\"https://developer.wordpress.org/reference/functions/get_the_tag_list/\" rel=\"noreferrer\">https://developer.wordpress.org/reference/functions/get_the_tag_list/</a></p>\n" }, { "answer_id": 263816, "author": "Faysal Mahamud", "author_id": 83752, "author_profile": "https://wordpress.stackexchange.com/users/83752", "pm_score": 4, "selected": true, "text": "<p>The code is tested and working fine. </p>\n\n<p>Place this code</p>\n\n<pre><code>&lt;?php\n $posttags = get_the_tags();\n\n if( ! empty( $posttags ) ) :\n $tags = array();\n\n foreach($posttags as $key =&gt; $value){\n $tags[] = $value-&gt;name;\n }\n\n?&gt;\n\n &lt;meta name=\"keywords\" content=\"&lt;?php echo implode( ',', $tags ); ?&gt;,test\"/&gt;\n\n&lt;?php endif;?&gt;\n</code></pre>\n\n<p>instead of </p>\n\n<pre><code>&lt;meta name=\"keywords\" content=\"&lt;?php the_tags( '', ',', '' );?&gt;test&lt;?php }?&gt;\"/&gt;\n</code></pre>\n" } ]
2017/04/17
[ "https://wordpress.stackexchange.com/questions/263813", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/110405/" ]
I'm trying to use tags of the single post, as meta keywords. I tried using this: ``` <meta name="keywords" content="<?php the_tags('',',','');?>test<?php }?>"/> ``` It works, but the output is: ``` <meta name="keywords" content="<a href="http://127.0.0.1/1/tag/aquaman/" rel="tag">aquaman</a>,<a href="http://127.0.0.1/1/tag/batman/" rel="tag">batman</a>,<a href="http://127.0.0.1/1/tag/wonder-woman/" rel="tag">wonder woman</a>"/> ``` Is it possible to remove the tags link/URL? And just the text/tag itself will appear?
The code is tested and working fine. Place this code ``` <?php $posttags = get_the_tags(); if( ! empty( $posttags ) ) : $tags = array(); foreach($posttags as $key => $value){ $tags[] = $value->name; } ?> <meta name="keywords" content="<?php echo implode( ',', $tags ); ?>,test"/> <?php endif;?> ``` instead of ``` <meta name="keywords" content="<?php the_tags( '', ',', '' );?>test<?php }?>"/> ```
263,823
<p>In <code>functions.php</code>, I have added the following code</p> <pre><code>function my_custom_js() { echo '&lt;script type="text/javascript" src="//platform-api.sharethis.com/js/sharethis.js#property=58ef5701485778001223c86c&amp;product=inline-share-buttons"&gt;&lt;/script&gt;'; } add_action('wp_head', 'my_custom_js'); </code></pre> <p>This gives an error:</p> <blockquote> <p>undefined function add_action()</p> </blockquote> <p>But this is already defined by WordPress. Am I missing something?</p>
[ { "answer_id": 263824, "author": "Mukii kumar", "author_id": 88892, "author_profile": "https://wordpress.stackexchange.com/users/88892", "pm_score": -1, "selected": false, "text": "<p>@rajith try this. This might be helps you-</p>\n\n<pre><code>add_action('wp_head', array($this, 'my_custom_js'));\n</code></pre>\n" }, { "answer_id": 263825, "author": "cjbj", "author_id": 75495, "author_profile": "https://wordpress.stackexchange.com/users/75495", "pm_score": 1, "selected": false, "text": "<p>If <a href=\"https://developer.wordpress.org/reference/functions/add_action/\" rel=\"nofollow noreferrer\"><code>add_action</code></a> is undefined, it means WP is not loaded in the regular way. Assuming we are talking about <code>functions.php</code> in the theme folder (and not the <code>functions.php</code> in the <code>wp-includes</code> folder, which you must not mess with) there should be no problem, unless the php-file itself is run outside WP.</p>\n\n<p>This could happen, for instance, if you are including the php-file with a full url, in which case WP would see it as an external source, to be evaluated outside the WP-context. In that case <code>add_action</code> would be undefined. Normally, this would not happen, because WP itself looks for the <code>functions.php</code> file in the active (child) theme, but messing up the normal way of things is certainly possible.</p>\n\n<p>There is not enough context in your question to pinpoint where this could happen, but I suggest you check all <code>include</code> and <code>require</code>statements in your theme. Also, <a href=\"https://wordpress.stackexchange.com/questions/71406/is-there-a-flowchart-for-wordpress-loading-sequence\">this may be a useful resource</a> to track where things go wrong.</p>\n" } ]
2017/04/17
[ "https://wordpress.stackexchange.com/questions/263823", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/117803/" ]
In `functions.php`, I have added the following code ``` function my_custom_js() { echo '<script type="text/javascript" src="//platform-api.sharethis.com/js/sharethis.js#property=58ef5701485778001223c86c&product=inline-share-buttons"></script>'; } add_action('wp_head', 'my_custom_js'); ``` This gives an error: > > undefined function add\_action() > > > But this is already defined by WordPress. Am I missing something?
If [`add_action`](https://developer.wordpress.org/reference/functions/add_action/) is undefined, it means WP is not loaded in the regular way. Assuming we are talking about `functions.php` in the theme folder (and not the `functions.php` in the `wp-includes` folder, which you must not mess with) there should be no problem, unless the php-file itself is run outside WP. This could happen, for instance, if you are including the php-file with a full url, in which case WP would see it as an external source, to be evaluated outside the WP-context. In that case `add_action` would be undefined. Normally, this would not happen, because WP itself looks for the `functions.php` file in the active (child) theme, but messing up the normal way of things is certainly possible. There is not enough context in your question to pinpoint where this could happen, but I suggest you check all `include` and `require`statements in your theme. Also, [this may be a useful resource](https://wordpress.stackexchange.com/questions/71406/is-there-a-flowchart-for-wordpress-loading-sequence) to track where things go wrong.
263,827
<p>I been modifying a WordPress theme, and for some specific pages that need a specific design I placed a php file named <code>page-specific-url.php</code> where specific-url is the page I want to show.</p> <p>The problem I am facing is the location of the specific page I need to design is inside of of a category so the url is <code>domain.com/category1/specific-page</code>. How can I add the extra category1 so when I placed the <code>specific-page.php</code> in the root of the theme I can access it through <code>domain.com/category1/specific-page</code>?</p>
[ { "answer_id": 263828, "author": "mayersdesign", "author_id": 106965, "author_profile": "https://wordpress.stackexchange.com/users/106965", "pm_score": 0, "selected": false, "text": "<p>This is where body tags are your best friend. I would add the category as a custom body tag using this function: </p>\n\n<pre><code>/*Add custom body tag for categories*/\nadd_filter( 'body_class', 'cat_body_class' );\nfunction cat_body_class( $classes ) {\nif (is_single()) {\n $category = get_the_category();\n $classes[] = ‘category-‘.$category[0]-&gt;slug;\n}\n return $classes;\n}\n</code></pre>\n\n<p>Then simply use that body tag to style the page :) You won't even have to add any new page template (unless those categories have WAY different design/layout, or completely different logic.</p>\n" }, { "answer_id": 263830, "author": "cjbj", "author_id": 75495, "author_profile": "https://wordpress.stackexchange.com/users/75495", "pm_score": 2, "selected": false, "text": "<p>There is a filter called <a href=\"https://developer.wordpress.org/reference/hooks/theme_page_templates/\" rel=\"nofollow noreferrer\"><code>theme_page_templates</code></a> which you can use to force the use of a certain template under certain circumstances. Like this:</p>\n\n<pre><code>add_filter ('theme_page_templates', 'wpse263827_filter_theme_page_templates', 20, 3 );\nwpse263827_filter_theme_page_templates ($page_templates, $this, $post) {\n if (condition based on $post) $page_templates = 'path-to-template.php';\n return $page_templates;\n }\n</code></pre>\n\n<p>So, you can place the template file wherever you want and assign it when the page is in that certain category. No need to touch the url structure.</p>\n" } ]
2017/04/17
[ "https://wordpress.stackexchange.com/questions/263827", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/117809/" ]
I been modifying a WordPress theme, and for some specific pages that need a specific design I placed a php file named `page-specific-url.php` where specific-url is the page I want to show. The problem I am facing is the location of the specific page I need to design is inside of of a category so the url is `domain.com/category1/specific-page`. How can I add the extra category1 so when I placed the `specific-page.php` in the root of the theme I can access it through `domain.com/category1/specific-page`?
There is a filter called [`theme_page_templates`](https://developer.wordpress.org/reference/hooks/theme_page_templates/) which you can use to force the use of a certain template under certain circumstances. Like this: ``` add_filter ('theme_page_templates', 'wpse263827_filter_theme_page_templates', 20, 3 ); wpse263827_filter_theme_page_templates ($page_templates, $this, $post) { if (condition based on $post) $page_templates = 'path-to-template.php'; return $page_templates; } ``` So, you can place the template file wherever you want and assign it when the page is in that certain category. No need to touch the url structure.
263,832
<p>i', try added to my site upcoming events, but when i try add via get_post_meta - not working, for example: <a href="http://prntscr.com/exe8oi" rel="nofollow noreferrer">http://prntscr.com/exe8oi</a> i added date, then i use this my code:</p> <pre><code>&lt;?php $today = date('U')*1000;?&gt; &lt;?php $event = new WP_Query(array( 'post_type'=&gt;'event_init', 'meta_query' =&gt; array( array( 'key' =&gt; 'date_events', 'value' =&gt;$today, 'compare' =&gt; '&gt;' , 'order'=&gt;'ASC' ) ), 'showposts' =&gt; -1 ));?&gt; &lt;h2&gt;&lt;?php the_title();?&gt;&lt;/h2&gt; &lt;?php if($event-&gt;have_posts()): while($event-&gt;have_posts()): $event-&gt;the_post();?&gt; &lt;?php $events_date = get_post_meta(get_the_ID(), 'date_events', true);?&gt; &lt;h3 class="uppper" style="font-weight:500;"&gt; &lt;?php echo date('l d F, Y', $events_date/1000 + 86400 )?&gt; &lt;/h3&gt; &lt;h4&gt;&lt;?php the_title();?&gt;&lt;/h4&gt; &lt;?php echo mb_substr( strip_tags( get_the_content() ), 0, 120 ); ?&gt;... &lt;?php endwhile; endif; wp_reset_postdata(); ?&gt; </code></pre> <p>but posts not display in frontend, what wrong? and little additional question: how i can output date in german language (need name of week and need months output in german language). Thanks</p>
[ { "answer_id": 263828, "author": "mayersdesign", "author_id": 106965, "author_profile": "https://wordpress.stackexchange.com/users/106965", "pm_score": 0, "selected": false, "text": "<p>This is where body tags are your best friend. I would add the category as a custom body tag using this function: </p>\n\n<pre><code>/*Add custom body tag for categories*/\nadd_filter( 'body_class', 'cat_body_class' );\nfunction cat_body_class( $classes ) {\nif (is_single()) {\n $category = get_the_category();\n $classes[] = ‘category-‘.$category[0]-&gt;slug;\n}\n return $classes;\n}\n</code></pre>\n\n<p>Then simply use that body tag to style the page :) You won't even have to add any new page template (unless those categories have WAY different design/layout, or completely different logic.</p>\n" }, { "answer_id": 263830, "author": "cjbj", "author_id": 75495, "author_profile": "https://wordpress.stackexchange.com/users/75495", "pm_score": 2, "selected": false, "text": "<p>There is a filter called <a href=\"https://developer.wordpress.org/reference/hooks/theme_page_templates/\" rel=\"nofollow noreferrer\"><code>theme_page_templates</code></a> which you can use to force the use of a certain template under certain circumstances. Like this:</p>\n\n<pre><code>add_filter ('theme_page_templates', 'wpse263827_filter_theme_page_templates', 20, 3 );\nwpse263827_filter_theme_page_templates ($page_templates, $this, $post) {\n if (condition based on $post) $page_templates = 'path-to-template.php';\n return $page_templates;\n }\n</code></pre>\n\n<p>So, you can place the template file wherever you want and assign it when the page is in that certain category. No need to touch the url structure.</p>\n" } ]
2017/04/17
[ "https://wordpress.stackexchange.com/questions/263832", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/-1/" ]
i', try added to my site upcoming events, but when i try add via get\_post\_meta - not working, for example: <http://prntscr.com/exe8oi> i added date, then i use this my code: ``` <?php $today = date('U')*1000;?> <?php $event = new WP_Query(array( 'post_type'=>'event_init', 'meta_query' => array( array( 'key' => 'date_events', 'value' =>$today, 'compare' => '>' , 'order'=>'ASC' ) ), 'showposts' => -1 ));?> <h2><?php the_title();?></h2> <?php if($event->have_posts()): while($event->have_posts()): $event->the_post();?> <?php $events_date = get_post_meta(get_the_ID(), 'date_events', true);?> <h3 class="uppper" style="font-weight:500;"> <?php echo date('l d F, Y', $events_date/1000 + 86400 )?> </h3> <h4><?php the_title();?></h4> <?php echo mb_substr( strip_tags( get_the_content() ), 0, 120 ); ?>... <?php endwhile; endif; wp_reset_postdata(); ?> ``` but posts not display in frontend, what wrong? and little additional question: how i can output date in german language (need name of week and need months output in german language). Thanks
There is a filter called [`theme_page_templates`](https://developer.wordpress.org/reference/hooks/theme_page_templates/) which you can use to force the use of a certain template under certain circumstances. Like this: ``` add_filter ('theme_page_templates', 'wpse263827_filter_theme_page_templates', 20, 3 ); wpse263827_filter_theme_page_templates ($page_templates, $this, $post) { if (condition based on $post) $page_templates = 'path-to-template.php'; return $page_templates; } ``` So, you can place the template file wherever you want and assign it when the page is in that certain category. No need to touch the url structure.
263,845
<p>I have an existing site that has 5 or 6 php pages, with HTML mixed in for some tables and forms. The biggest purpose of the site is to upload CSV files into a database table and then on other pages select certain records from the database and display them in HTML tables. </p> <p>The site works perfectly on my local server with a MySQL workbench interface for the database. However, I was just told it will have to be a wordpress site. Basically, it will link from an existing WP site, but same pages and themes so I'm basically building it within this existing site and pages.</p> <p>I've been told it might be best to turn each of my PHP pages into page templates for the WP install. I'm curious the best way to go about turning these pages into wordpress page templates. I've looked all over but can't find great tutorials. Does anyone have some helpful info?</p>
[ { "answer_id": 263849, "author": "Swen", "author_id": 22588, "author_profile": "https://wordpress.stackexchange.com/users/22588", "pm_score": 2, "selected": true, "text": "<p>It really is rather simple. Check out the <a href=\"https://developer.wordpress.org/themes/template-files-section/page-template-files/\" rel=\"nofollow noreferrer\">Codex on Page Templates</a> for more info.</p>\n\n<ol>\n<li>Make a copy the existing page.php file located inside your WordPress theme's folder.</li>\n<li>Rename your <em>page.php</em> file to <em>page-mypage.php</em></li>\n<li>At the very top of your new <em>page-mypage.php</em> file, right after the opening <code>&lt;?php</code> tag add the following code to define your custom page template.</li>\n</ol>\n\n<p><code>/* Template Name: My Page Template */</code></p>\n\n<ol start=\"4\">\n<li><p>Now inside your <em>page-mypage.php</em> file locate the WordPress loop. It usually looks like this:</p>\n\n<pre><code>&lt;?php\n// Start the loop.\nwhile ( have_posts() ) : the_post();\n\n // Include the page content template.\n get_template_part( 'template-parts/content', 'page' );\n\n // If comments are open or we have at least one comment, load up the comment template.\n if ( comments_open() || get_comments_number() ) {\n comments_template();\n }\n\n // End of the loop.\nendwhile;\n?&gt;\n</code></pre></li>\n<li><p>Replace the entire loop with the relevant PHP code of your project</p></li>\n<li>Now in WordPress you will have to add a new page named <em>mypage</em> and select your custom template (My Page Template) in the \"Page Attributs\" sidebar block. There will be a dropdown menu called \"Template\".</li>\n<li>Done!</li>\n</ol>\n" }, { "answer_id": 263851, "author": "Sleuteltje", "author_id": 64516, "author_profile": "https://wordpress.stackexchange.com/users/64516", "pm_score": 0, "selected": false, "text": "<p>You need there current theme to either develop a child-theme for it, or integrate your code into their existing theme. </p>\n\n<p>This tutorial pretty much covers the basics for creating wordpress templates from scratch: <a href=\"https://www.taniarascia.com/developing-a-wordpress-theme-from-scratch/\" rel=\"nofollow noreferrer\">https://www.taniarascia.com/developing-a-wordpress-theme-from-scratch/</a>\nSo you should be able to find all the bits needed to convert your code into wordpress templates.</p>\n\n<p>If you want a dirty quick fix, as long as you follow the formats from wordpress (using comment blocks above the page template so wordpress can identify it), you can just convert your .php files to a page template easily. To also enable the user to insert his own content into the page template, you do need to use some wordpress hooks tho. But they are really easy, see this part in the codex:\n<a href=\"https://developer.wordpress.org/themes/template-files-section/page-template-files/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/themes/template-files-section/page-template-files/</a> for creating page templates &amp; see <a href=\"https://codex.wordpress.org/The_Loop\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/The_Loop</a> for using the loop:</p>\n\n<pre><code> &lt;?php \nif ( have_posts() ) {\n while ( have_posts() ) {\n the_post(); \n //\n // Post Content here\n //\n } // end while\n} // end if\n?&gt;\n</code></pre>\n\n<p>And then you can use stuff like the_content(); for displaying the content from the WYISWYG editor.</p>\n" } ]
2017/04/17
[ "https://wordpress.stackexchange.com/questions/263845", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/115321/" ]
I have an existing site that has 5 or 6 php pages, with HTML mixed in for some tables and forms. The biggest purpose of the site is to upload CSV files into a database table and then on other pages select certain records from the database and display them in HTML tables. The site works perfectly on my local server with a MySQL workbench interface for the database. However, I was just told it will have to be a wordpress site. Basically, it will link from an existing WP site, but same pages and themes so I'm basically building it within this existing site and pages. I've been told it might be best to turn each of my PHP pages into page templates for the WP install. I'm curious the best way to go about turning these pages into wordpress page templates. I've looked all over but can't find great tutorials. Does anyone have some helpful info?
It really is rather simple. Check out the [Codex on Page Templates](https://developer.wordpress.org/themes/template-files-section/page-template-files/) for more info. 1. Make a copy the existing page.php file located inside your WordPress theme's folder. 2. Rename your *page.php* file to *page-mypage.php* 3. At the very top of your new *page-mypage.php* file, right after the opening `<?php` tag add the following code to define your custom page template. `/* Template Name: My Page Template */` 4. Now inside your *page-mypage.php* file locate the WordPress loop. It usually looks like this: ``` <?php // Start the loop. while ( have_posts() ) : the_post(); // Include the page content template. get_template_part( 'template-parts/content', 'page' ); // If comments are open or we have at least one comment, load up the comment template. if ( comments_open() || get_comments_number() ) { comments_template(); } // End of the loop. endwhile; ?> ``` 5. Replace the entire loop with the relevant PHP code of your project 6. Now in WordPress you will have to add a new page named *mypage* and select your custom template (My Page Template) in the "Page Attributs" sidebar block. There will be a dropdown menu called "Template". 7. Done!
263,848
<p>I have a custom post tipe ("artigo"), and this CPT has a registered taxonomy ("artigo_eixo"), with 3 registered terms in it.</p> <p><strong>I want to show, in that page, a sidebar listing all terms,</strong> <strong><em>except the current term,</em></strong> in the page that lists all posts with that term (<a href="http://localhost/mytaxonomy/current_term/" rel="nofollow noreferrer">http://localhost/mytaxonomy/current_term/</a>)</p> <p>However, I can't exclude the current term from the query.</p> <p>I'm trying to get a list of taxonomy terms, but exclude a certain term from this list. I'm trying to follow the codex examples, but I'm having no success, using either <code>get_terms()</code> or <code>WP_Term_query()</code>.</p> <p>There are 3 terms and the IDs are 13,14,15. There are no posts or CPT items with those IDs. </p> <p>I just tested <code>get_queried_object_id()</code> and it seems to be returning the proper term IDs of the term being shown -- that is, if I am viewing the URL of the term with ID 13, the function returns 13, and so on.</p> <p>It also doesn't work using hardcoded values, be it a string, an integer, or an array of any of those types. Neither won't work:</p> <pre><code>'exclude' =&gt; 14 'exclude' =&gt; '14' 'exclude' =&gt; array(14) 'exclude' =&gt; array('14') </code></pre> <p>There are no errors displayed by PHP or the WP debug log.</p> <h1>get_terms</h1> <pre><code>if (is_tax( 'artigo_eixo' )) { $current_eixo = get_queried_object_id(); $args = array( 'taxonomy' =&gt; 'artigo_eixo', 'exclude' =&gt; $current_eixo ); $eixos = get_terms( $args ); </code></pre> <h1>WP_Term_query</h1> <pre><code>if (is_tax( 'artigo_eixo' )) { $current_eixo = get_queried_object_id(); $args = array( 'taxonomy' =&gt; array('artigo_eixo'), 'exclude' =&gt; $current_eixo ); $eixos = new WP_Term_Query( $args ); $eixos = $eixos-&gt;terms; </code></pre>
[ { "answer_id": 263850, "author": "Aniruddha Gawade", "author_id": 101818, "author_profile": "https://wordpress.stackexchange.com/users/101818", "pm_score": -1, "selected": false, "text": "<p>Possible reason: <code>get_queried_object_id()</code> returns <code>int</code>, whereas <code>exclude</code> parameter uses array or string of comma separated ids.</p>\n\n<p>First make sure you are getting right value in <code>$current_eixo</code>, and then try putting it in array and using that array as parameter.</p>\n\n<pre><code>'exclude' =&gt; array($current_eixo)\n</code></pre>\n\n<p>Although not sure if this is the problem in your case, give it a try.</p>\n" }, { "answer_id": 263878, "author": "That Brazilian Guy", "author_id": 22510, "author_profile": "https://wordpress.stackexchange.com/users/22510", "pm_score": 1, "selected": true, "text": "<p>Turns out there was a function hooking the filter <code>list_terms_exclusions</code>, and the return was inside a logically faulty conditional. I fixed it and now the term query exclusion works as intended.</p>\n" } ]
2017/04/17
[ "https://wordpress.stackexchange.com/questions/263848", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/22510/" ]
I have a custom post tipe ("artigo"), and this CPT has a registered taxonomy ("artigo\_eixo"), with 3 registered terms in it. **I want to show, in that page, a sidebar listing all terms,** ***except the current term,*** in the page that lists all posts with that term (<http://localhost/mytaxonomy/current_term/>) However, I can't exclude the current term from the query. I'm trying to get a list of taxonomy terms, but exclude a certain term from this list. I'm trying to follow the codex examples, but I'm having no success, using either `get_terms()` or `WP_Term_query()`. There are 3 terms and the IDs are 13,14,15. There are no posts or CPT items with those IDs. I just tested `get_queried_object_id()` and it seems to be returning the proper term IDs of the term being shown -- that is, if I am viewing the URL of the term with ID 13, the function returns 13, and so on. It also doesn't work using hardcoded values, be it a string, an integer, or an array of any of those types. Neither won't work: ``` 'exclude' => 14 'exclude' => '14' 'exclude' => array(14) 'exclude' => array('14') ``` There are no errors displayed by PHP or the WP debug log. get\_terms ========== ``` if (is_tax( 'artigo_eixo' )) { $current_eixo = get_queried_object_id(); $args = array( 'taxonomy' => 'artigo_eixo', 'exclude' => $current_eixo ); $eixos = get_terms( $args ); ``` WP\_Term\_query =============== ``` if (is_tax( 'artigo_eixo' )) { $current_eixo = get_queried_object_id(); $args = array( 'taxonomy' => array('artigo_eixo'), 'exclude' => $current_eixo ); $eixos = new WP_Term_Query( $args ); $eixos = $eixos->terms; ```
Turns out there was a function hooking the filter `list_terms_exclusions`, and the return was inside a logically faulty conditional. I fixed it and now the term query exclusion works as intended.
263,911
<p>have a question about best practice for adding fields to author form. The site will post blogs on behalf of another author, but wants an author box at the bottom that would include the "real" authors picture, name, business name, and links to social media. A typical author box won't work since it ties to the author publishing the post.</p> <p>What would be best practice with this? I really only dabble with HTML and CSS so styling it won't be a problem, but not sure if custom fields will work here, or if there is a better practice for this. Love the site and all the help everyone offers. Thanks.</p>
[ { "answer_id": 263914, "author": "Ben HartLenn", "author_id": 6645, "author_profile": "https://wordpress.stackexchange.com/users/6645", "pm_score": 0, "selected": false, "text": "<p>You could use the built in custom fields for most of this, but Advanced Custom Fields will be especially useful for making the author image part easy and is worth using for sure. You can go to Dashboard >> Custom Fields after activating the plugin, and easily create a new Field Group Called \"Custom Author\" or whatever suits you, and it should automatically be attached to the posts post type. After that you can add a text field for a custom author name, and an image field for a custom author image, and fields for whatever else you may need to display. </p>\n\n<p>Once you have your advanced custom fields created(not going to delve into that too much here), a user can fill in your advanced custom author fields on any post, and you can output those fields in your themes template files(likely single.php for when a single post is being viewed). The output/display part is entirely up to you, but I'll show one way you could display a custom text field called \"custom_author_name\" and a custom image field called \"custom_author_image\":</p>\n\n<pre><code>&lt;section class=\"post-meta\"&gt;\n\n &lt;span class='post-author-name'&gt;\n &lt;?php\n $customAuthor = sanitize_text_field( get_field('custom_author_name') ); // Store safe/sanitized value of custom field in variable\n if($customAuthor) { // If custom_author_name field is set, display it\n echo $customAuthor;\n } else { // Otherwise fallback to display the normal post author name\n echo get_the_author();\n }\n ?&gt;\n &lt;/span&gt;\n\n &lt;?php\n $customAuthorImage = get_field('custom_author_image');\n if($customAuthorImage) { // If custom_author_image field is set...\n\n // ... Then put effort into storing sanitized data we need\n $url = esc_url( $customAuthorImage['url'] );\n $alt = esc_attr( $customAuthorImage['alt'] );\n $title = esc_attr( $customAuthorImage['title'] );\n\n // ... And finally display our custom image field in an img tag\n echo '&lt;img class=\"custom-author-image\" src=\"' . $url . '\" alt=\"' . $alt . '\" title=\"' . $title . '\"&gt;';\n } \n ?&gt;\n\n&lt;/section&gt;\n</code></pre>\n\n<p>As far as best practices, use strong logic in your php(you might add stronger conditional logic to how I check if the custom fields are set, and maybe only display the image if the authors name is set for example), and also be sure you sanitize or escape all data when outputting it on the front end.</p>\n\n<p>Also, I'm happy to offer more help if you get stuck on this, just add a comment here. </p>\n" }, { "answer_id": 263958, "author": "Brijesh Dhami", "author_id": 117868, "author_profile": "https://wordpress.stackexchange.com/users/117868", "pm_score": 1, "selected": false, "text": "<p>Add the new custom field to the author profile</p>\n\n<pre><code>function my_epl_custom_user_contact( $contactmethods ) {\n $contactmethods['custom'] = __( 'Custom', 'easy-property-listings' ); \n return $contactmethods;\n}\nadd_filter ('user_contactmethods','my_epl_custom_user_contact',10,1);\n</code></pre>\n\n<p>Create the HTML output of the Custom Fields</p>\n\n<pre><code>function my_epl_get_custom_author_html($html = '') {\n global $epl_author; \n if ( $epl_author-&gt;custom != '' ) {\n $html = '\n &lt;a class=\"epl-author-icon author-icon custom-icon-24\" href=\"http://custom.com/' . $epl_author-&gt;custom . '\"\n title=\"'.__('Follow', 'easy-property-listings' ).' ' . $epl_author-&gt;name . ' '.__('on Custom', 'easy-property-listings' ).'\"&gt;'.\n __('C', 'easy-property-listings' ).\n '&lt;/a&gt;';\n }\n return $html;\n}\n</code></pre>\n\n<p>Add the custom field filter</p>\n\n<pre><code>function my_epl_custom_social_icons_filter( $html ) { \n $html .= my_epl_get_custom_author_html();\n return $html;\n}\nadd_filter( 'epl_author_email_html' , 'my_epl_custom_social_icons_filter' );\n</code></pre>\n" } ]
2017/04/18
[ "https://wordpress.stackexchange.com/questions/263911", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/117851/" ]
have a question about best practice for adding fields to author form. The site will post blogs on behalf of another author, but wants an author box at the bottom that would include the "real" authors picture, name, business name, and links to social media. A typical author box won't work since it ties to the author publishing the post. What would be best practice with this? I really only dabble with HTML and CSS so styling it won't be a problem, but not sure if custom fields will work here, or if there is a better practice for this. Love the site and all the help everyone offers. Thanks.
Add the new custom field to the author profile ``` function my_epl_custom_user_contact( $contactmethods ) { $contactmethods['custom'] = __( 'Custom', 'easy-property-listings' ); return $contactmethods; } add_filter ('user_contactmethods','my_epl_custom_user_contact',10,1); ``` Create the HTML output of the Custom Fields ``` function my_epl_get_custom_author_html($html = '') { global $epl_author; if ( $epl_author->custom != '' ) { $html = ' <a class="epl-author-icon author-icon custom-icon-24" href="http://custom.com/' . $epl_author->custom . '" title="'.__('Follow', 'easy-property-listings' ).' ' . $epl_author->name . ' '.__('on Custom', 'easy-property-listings' ).'">'. __('C', 'easy-property-listings' ). '</a>'; } return $html; } ``` Add the custom field filter ``` function my_epl_custom_social_icons_filter( $html ) { $html .= my_epl_get_custom_author_html(); return $html; } add_filter( 'epl_author_email_html' , 'my_epl_custom_social_icons_filter' ); ```
263,936
<p>I'm looking to restrict all users (other than admins) to only be able to upload images e.g JPG's and PNGs allowed for all users but still allow admins to upload pdfs etc. (Or even better would be to only prevent unregistered users from uploading anything other than JPGs and PNGs!)</p> <p>I've been trying the following functions.php code but it still seems to restrict admins from uploading PDFs:</p> <pre><code>add_filter('upload_mimes','restict_mime'); function restict_mime($mimes) { if(!current_user_can(‘administrator’)){ $mimes = array( 'jpg|jpeg|jpe' =&gt; 'image/jpeg', 'png' =&gt; 'image/png', ); } return $mimes; } </code></pre> <p>Any ideas?</p>
[ { "answer_id": 263926, "author": "mageDev0688", "author_id": 106772, "author_profile": "https://wordpress.stackexchange.com/users/106772", "pm_score": 4, "selected": false, "text": "<p>According to the wordpress <a href=\"https://codex.wordpress.org/Changing_The_Site_URL\" rel=\"noreferrer\">reference here</a></p>\n\n<p>Add these two lines to your wp-config.php, where \"example.com\" is the correct location of your site.</p>\n\n<pre><code>define('WP_HOME','http://example.com'); \ndefine('WP_SITEURL','http://example.com');\n</code></pre>\n\n<p>OR</p>\n\n<p>Edit functions.php</p>\n\n<p>Add these two lines to the file, immediately after the initial \"\n\n<pre><code>update_option( 'siteurl', 'http://example.com' );\nupdate_option( 'home', 'http://example.com' );\n</code></pre>\n\n<p>Or check the <code>.htaccess</code> file as well if added any rewrite rule for redirect the website.</p>\n\n<p>Hope this help!!</p>\n" }, { "answer_id": 263927, "author": "Jignesh Patel", "author_id": 111556, "author_profile": "https://wordpress.stackexchange.com/users/111556", "pm_score": 0, "selected": false, "text": "<p>you can change live url to local url directly in database table <strong>wp_options</strong> two <strong>option_name</strong> field</p>\n\n<pre><code>1) siteurl\n2) home\n</code></pre>\n\n<p>After this save permalink.</p>\n\n<p>Hope is useful</p>\n" }, { "answer_id": 263928, "author": "Israr Mansuri", "author_id": 117862, "author_profile": "https://wordpress.stackexchange.com/users/117862", "pm_score": -1, "selected": false, "text": "<p>I just change my permalink structure to plain and again to old one then Its working.\nthanks all of you for your help. :)</p>\n" }, { "answer_id": 263930, "author": "JItendra Rana", "author_id": 87433, "author_profile": "https://wordpress.stackexchange.com/users/87433", "pm_score": 5, "selected": true, "text": "<p>Try following </p>\n\n<ul>\n<li><p>If there are caching plugins installed like W3 total cache. Then purge cache first. Or may be disable them for time being</p></li>\n<li><p>Perform Search and Replace in the database for Old Site URL. You can <a href=\"https://wordpress.org/plugins/search-and-replace/\" rel=\"nofollow noreferrer\">Use this Plugin</a></p></li>\n<li><p>Reset Permalinks ( Dashboard >> Settings >> Permalinks )</p></li>\n<li><p>Last but not the least. Clear your browser Cache and History</p>\n\n<ul>\n<li>In Chrome, you can try to <a href=\"https://superuser.com/a/203702/389865\">clear your DNS cache</a> before clearing <em>all</em> your cache</li>\n</ul></li>\n</ul>\n" }, { "answer_id": 316507, "author": "masteroleary", "author_id": 152212, "author_profile": "https://wordpress.stackexchange.com/users/152212", "pm_score": 1, "selected": false, "text": "<p>Had to change these lines in my wp-config.php from</p>\n\n<pre><code>define('WP_CACHE', true);\ndefine( 'WPCACHEHOME', 'C:\\wamp64\\www\\wp-content\\plugins\\wp-super-cache/' );\n</code></pre>\n\n<p>to</p>\n\n<pre><code>define('WP_CACHE', false);\n//define( 'WPCACHEHOME', 'C:\\wamp64\\www\\wp-content\\plugins\\wp-super-cache/' );\n</code></pre>\n" }, { "answer_id": 321843, "author": "Vincent Loy", "author_id": 155886, "author_profile": "https://wordpress.stackexchange.com/users/155886", "pm_score": 1, "selected": false, "text": "<p>You can also solve this problem by <a href=\"https://wp-cli.org/fr/#installation\" rel=\"nofollow noreferrer\">installing WP cli</a> and running : </p>\n\n<p><code>wp search-replace 'example.com' 'example.local'</code></p>\n\n<p><a href=\"https://codex.wordpress.org/Changing_The_Site_URL#wp-cli\" rel=\"nofollow noreferrer\">Check the codex</a> for more info. But as JItendra said, it's important to clear the browser cache too after doing this. </p>\n" }, { "answer_id": 351268, "author": "Hannah G.", "author_id": 177372, "author_profile": "https://wordpress.stackexchange.com/users/177372", "pm_score": 0, "selected": false, "text": "<p>Try remove any redirecting plugins if you have in your live site codebase. I solved the same issue by removing the \"safe-redirect-manager\" plugin in local.</p>\n" } ]
2017/04/18
[ "https://wordpress.stackexchange.com/questions/263936", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/117472/" ]
I'm looking to restrict all users (other than admins) to only be able to upload images e.g JPG's and PNGs allowed for all users but still allow admins to upload pdfs etc. (Or even better would be to only prevent unregistered users from uploading anything other than JPGs and PNGs!) I've been trying the following functions.php code but it still seems to restrict admins from uploading PDFs: ``` add_filter('upload_mimes','restict_mime'); function restict_mime($mimes) { if(!current_user_can(‘administrator’)){ $mimes = array( 'jpg|jpeg|jpe' => 'image/jpeg', 'png' => 'image/png', ); } return $mimes; } ``` Any ideas?
Try following * If there are caching plugins installed like W3 total cache. Then purge cache first. Or may be disable them for time being * Perform Search and Replace in the database for Old Site URL. You can [Use this Plugin](https://wordpress.org/plugins/search-and-replace/) * Reset Permalinks ( Dashboard >> Settings >> Permalinks ) * Last but not the least. Clear your browser Cache and History + In Chrome, you can try to [clear your DNS cache](https://superuser.com/a/203702/389865) before clearing *all* your cache
263,950
<p>I am using beneath code im buddypress to show notification of the latest posts posted by users.</p> <p><a href="https://gist.github.com/kishoresahoo/9209b9f6ac69ce21cd6962e7fe21e1b4/6b9d901383da4783f9108ffdc6aa2bb4e671cd44" rel="nofollow noreferrer">https://gist.github.com/kishoresahoo/9209b9f6ac69ce21cd6962e7fe21e1b4/6b9d901383da4783f9108ffdc6aa2bb4e671cd44</a></p> <p>The problem is that when a post is posted then only the person who posts the post receive the notification and the other users don't receive.</p> <p>I want to fix this error.</p> <p>Thanks and regards, Ahmad</p>
[ { "answer_id": 263965, "author": "JItendra Rana", "author_id": 87433, "author_profile": "https://wordpress.stackexchange.com/users/87433", "pm_score": 2, "selected": false, "text": "<p>If you check the function for 'publish_post' action. </p>\n\n<pre><code>function bp_post_published_notification( $post_id, $post ) {\n $author_id = $post-&gt;post_author; /* Post author ID. */\n if ( bp_is_active( 'notifications' ) ) {\n bp_notifications_add_notification( array(\n 'user_id' =&gt; $author_id,\n 'item_id' =&gt; $post_id,\n 'component_name' =&gt; 'custom',\n 'component_action' =&gt; 'custom_action',\n 'date_notified' =&gt; bp_core_current_time(),\n 'is_new' =&gt; 1,\n ) );\n }\n}\nadd_action( 'publish_post', 'bp_post_published_notification', 99, 2 );\n</code></pre>\n\n<p>Notice that you are sending Notification to Post Author only. \nYou will need to change 'user_id' parameter in 'bp_notifications_add_notification' function to the user id you want. </p>\n\n<p>Here is the <a href=\"https://codex.buddypress.org/developer/function-examples/bp_notifications_add_notification/\" rel=\"nofollow noreferrer\">Codex Documentation</a> for <strong>bp_notifications_add_notification</strong> Function.</p>\n\n<hr>\n\n<p><strong>EDIT :</strong> </p>\n\n<p>Update the function as below :</p>\n\n<pre><code>function bp_post_published_notification( $post_id, $post ) {\n // $author_id = $post-&gt;post_author; \n\n $active_users = bp_core_get_users( array(\"per_page\"=&gt;-1));\n\n foreach ( $active_users['users'] as $user ) {\n if ( bp_is_active( 'notifications' ) ) {\n bp_notifications_add_notification( array(\n 'user_id' =&gt; $user-&gt;ID,\n 'item_id' =&gt; $post_id,\n 'component_name' =&gt; 'custom',\n 'component_action' =&gt; 'custom_action',\n 'date_notified' =&gt; bp_core_current_time(),\n 'is_new' =&gt; 1,\n ) );\n }\n }\n}\nadd_action( 'publish_post', 'bp_post_published_notification', 99, 2 );\n</code></pre>\n\n<p><a href=\"http://hookr.io/functions/bp_core_get_users/\" rel=\"nofollow noreferrer\">Click here</a> for more details about <strong>'bp_core_get_users'</strong> function.</p>\n" }, { "answer_id": 263971, "author": "ahendwh2", "author_id": 112098, "author_profile": "https://wordpress.stackexchange.com/users/112098", "pm_score": 2, "selected": true, "text": "<p>Like JItendra Rana already mentioned, you just send a notification to the author. If all users should get a notification, you must loop through all your users and add a notification to everyone. You get the users with <a href=\"https://codex.wordpress.org/Function_Reference/get_users\" rel=\"nofollow noreferrer\">get_users</a>. Here is the modified code to realize it:</p>\n\n<pre><code>function bp_post_published_notification( $post_id, $post ) {\n $author_id = $post-&gt;post_author; /* Post author ID. */\n $users = get_users();\n\n /* Loop all users */\n foreach( $users as $user ) {\n if ( bp_is_active( 'notifications' ) ) {\n bp_notifications_add_notification( array(\n 'user_id' =&gt; $user-&gt;ID,\n 'item_id' =&gt; $post_id,\n 'component_name' =&gt; 'custom',\n 'component_action' =&gt; 'custom_action',\n 'date_notified' =&gt; bp_core_current_time(),\n 'is_new' =&gt; 1,\n ) );\n }\n }\n}\nadd_action( 'publish_post', 'bp_post_published_notification', 99, 2 );\n</code></pre>\n" } ]
2017/04/18
[ "https://wordpress.stackexchange.com/questions/263950", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/117870/" ]
I am using beneath code im buddypress to show notification of the latest posts posted by users. <https://gist.github.com/kishoresahoo/9209b9f6ac69ce21cd6962e7fe21e1b4/6b9d901383da4783f9108ffdc6aa2bb4e671cd44> The problem is that when a post is posted then only the person who posts the post receive the notification and the other users don't receive. I want to fix this error. Thanks and regards, Ahmad
Like JItendra Rana already mentioned, you just send a notification to the author. If all users should get a notification, you must loop through all your users and add a notification to everyone. You get the users with [get\_users](https://codex.wordpress.org/Function_Reference/get_users). Here is the modified code to realize it: ``` function bp_post_published_notification( $post_id, $post ) { $author_id = $post->post_author; /* Post author ID. */ $users = get_users(); /* Loop all users */ foreach( $users as $user ) { if ( bp_is_active( 'notifications' ) ) { bp_notifications_add_notification( array( 'user_id' => $user->ID, 'item_id' => $post_id, 'component_name' => 'custom', 'component_action' => 'custom_action', 'date_notified' => bp_core_current_time(), 'is_new' => 1, ) ); } } } add_action( 'publish_post', 'bp_post_published_notification', 99, 2 ); ```
263,953
<p>I wish to run a cron job that would permanently erase all the posts belonging to some category from the past X days (say, week). This is probably very basic, but I would appreciate some pointers. Thanks.</p>
[ { "answer_id": 263960, "author": "JItendra Rana", "author_id": 87433, "author_profile": "https://wordpress.stackexchange.com/users/87433", "pm_score": 2, "selected": false, "text": "<p>Following Query will give you list of Post ID older than 30 days for given Category ID. </p>\n\n<pre><code>SELECT \n p.ID as post_id, \n term.term_id as category_id\nFROM wp_posts as p \nLEFT JOIN wp_term_relationships as tr ON tr.object_id = p.ID\nLEFT JOIN wp_terms as term ON tr.term_taxonomy_id = term.term_id\nWHERE term.term_id = \"CATEGORY ID HERE\" \n AND DATEDIFF(NOW(), p.post_date) &gt; 30\n</code></pre>\n\n<p>Once you get the list you can decide weather you want to delete post or not. </p>\n\n<p>To Delete the post use following function, the second parameter ( TRUE ) will delete the post permanently. If you want to keep the post in trash pass ( FALSE )</p>\n\n<pre><code>wp_delete_post( 'YOUR_POST_ID_HERE', TRUE);\n</code></pre>\n\n<p>Dont forget to change The Table prefix if its not 'wp_'</p>\n" }, { "answer_id": 264317, "author": "Nathan Johnson", "author_id": 106269, "author_profile": "https://wordpress.stackexchange.com/users/106269", "pm_score": 4, "selected": true, "text": "<p>The first step is setting up the cron job.</p>\n\n<p>The second part requires querying the database for a specific post type where the entry is older than 1 week. We can do this with get_posts() and specifying the category argument and the date_query argument.</p>\n\n<pre><code>//* If the scheduled event got removed from the cron schedule, re-add it\nif( ! wp_next_scheduled( 'wpse_263953_remove_old_entries' ) ) {\n wp_schedule_event( time(), 'daily', 'wpse_263953_remove_old_entries' );\n}\n\n//* Add action to hook fired by cron event\nadd_action( 'wpse_263953_remove_old_entries', 'wpse_263953_remove_old_entries' );\nfunction wpse_263953_remove_old_entries() {\n //* Get all posts older than 7 days...\n $posts = get_posts( [\n 'numberposts' =&gt; -1,\n //* Use `cat` to query the category ID\n //* 'cat' =&gt; 'wpse_263953_category_id',\n //* Use `category_name` to query the category slug\n 'category_name' =&gt; 'wpse_263953_category',\n 'date_query' =&gt; [\n 'after' =&gt; date( \"Y-m-d H:i:s\", strtotime( '-7 days', current_time( 'timestamp' ) ) ),\n //* For posts older than a month, use '-1 months' in strtotime()\n ],\n ]);\n //* ...and delete them\n foreach( $posts as $post ) {\n wp_delete_post( $post-&gt;ID );\n }\n}\n</code></pre>\n" } ]
2017/04/18
[ "https://wordpress.stackexchange.com/questions/263953", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/161/" ]
I wish to run a cron job that would permanently erase all the posts belonging to some category from the past X days (say, week). This is probably very basic, but I would appreciate some pointers. Thanks.
The first step is setting up the cron job. The second part requires querying the database for a specific post type where the entry is older than 1 week. We can do this with get\_posts() and specifying the category argument and the date\_query argument. ``` //* If the scheduled event got removed from the cron schedule, re-add it if( ! wp_next_scheduled( 'wpse_263953_remove_old_entries' ) ) { wp_schedule_event( time(), 'daily', 'wpse_263953_remove_old_entries' ); } //* Add action to hook fired by cron event add_action( 'wpse_263953_remove_old_entries', 'wpse_263953_remove_old_entries' ); function wpse_263953_remove_old_entries() { //* Get all posts older than 7 days... $posts = get_posts( [ 'numberposts' => -1, //* Use `cat` to query the category ID //* 'cat' => 'wpse_263953_category_id', //* Use `category_name` to query the category slug 'category_name' => 'wpse_263953_category', 'date_query' => [ 'after' => date( "Y-m-d H:i:s", strtotime( '-7 days', current_time( 'timestamp' ) ) ), //* For posts older than a month, use '-1 months' in strtotime() ], ]); //* ...and delete them foreach( $posts as $post ) { wp_delete_post( $post->ID ); } } ```
263,970
<p>I'm having a custom post type "products" of which I need to show a list. The products are sorted by meta value into different kinds of product type. I need to set one specific product type "tools" at the bottom of the list. But it also has to be sorted by create date. So all other product types sorted by create date and then the product type "tools" – also sorted by create date. Is this possible within one wp_query?</p> <p>How are the arguments for the wp_query?</p>
[ { "answer_id": 263960, "author": "JItendra Rana", "author_id": 87433, "author_profile": "https://wordpress.stackexchange.com/users/87433", "pm_score": 2, "selected": false, "text": "<p>Following Query will give you list of Post ID older than 30 days for given Category ID. </p>\n\n<pre><code>SELECT \n p.ID as post_id, \n term.term_id as category_id\nFROM wp_posts as p \nLEFT JOIN wp_term_relationships as tr ON tr.object_id = p.ID\nLEFT JOIN wp_terms as term ON tr.term_taxonomy_id = term.term_id\nWHERE term.term_id = \"CATEGORY ID HERE\" \n AND DATEDIFF(NOW(), p.post_date) &gt; 30\n</code></pre>\n\n<p>Once you get the list you can decide weather you want to delete post or not. </p>\n\n<p>To Delete the post use following function, the second parameter ( TRUE ) will delete the post permanently. If you want to keep the post in trash pass ( FALSE )</p>\n\n<pre><code>wp_delete_post( 'YOUR_POST_ID_HERE', TRUE);\n</code></pre>\n\n<p>Dont forget to change The Table prefix if its not 'wp_'</p>\n" }, { "answer_id": 264317, "author": "Nathan Johnson", "author_id": 106269, "author_profile": "https://wordpress.stackexchange.com/users/106269", "pm_score": 4, "selected": true, "text": "<p>The first step is setting up the cron job.</p>\n\n<p>The second part requires querying the database for a specific post type where the entry is older than 1 week. We can do this with get_posts() and specifying the category argument and the date_query argument.</p>\n\n<pre><code>//* If the scheduled event got removed from the cron schedule, re-add it\nif( ! wp_next_scheduled( 'wpse_263953_remove_old_entries' ) ) {\n wp_schedule_event( time(), 'daily', 'wpse_263953_remove_old_entries' );\n}\n\n//* Add action to hook fired by cron event\nadd_action( 'wpse_263953_remove_old_entries', 'wpse_263953_remove_old_entries' );\nfunction wpse_263953_remove_old_entries() {\n //* Get all posts older than 7 days...\n $posts = get_posts( [\n 'numberposts' =&gt; -1,\n //* Use `cat` to query the category ID\n //* 'cat' =&gt; 'wpse_263953_category_id',\n //* Use `category_name` to query the category slug\n 'category_name' =&gt; 'wpse_263953_category',\n 'date_query' =&gt; [\n 'after' =&gt; date( \"Y-m-d H:i:s\", strtotime( '-7 days', current_time( 'timestamp' ) ) ),\n //* For posts older than a month, use '-1 months' in strtotime()\n ],\n ]);\n //* ...and delete them\n foreach( $posts as $post ) {\n wp_delete_post( $post-&gt;ID );\n }\n}\n</code></pre>\n" } ]
2017/04/18
[ "https://wordpress.stackexchange.com/questions/263970", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/84187/" ]
I'm having a custom post type "products" of which I need to show a list. The products are sorted by meta value into different kinds of product type. I need to set one specific product type "tools" at the bottom of the list. But it also has to be sorted by create date. So all other product types sorted by create date and then the product type "tools" – also sorted by create date. Is this possible within one wp\_query? How are the arguments for the wp\_query?
The first step is setting up the cron job. The second part requires querying the database for a specific post type where the entry is older than 1 week. We can do this with get\_posts() and specifying the category argument and the date\_query argument. ``` //* If the scheduled event got removed from the cron schedule, re-add it if( ! wp_next_scheduled( 'wpse_263953_remove_old_entries' ) ) { wp_schedule_event( time(), 'daily', 'wpse_263953_remove_old_entries' ); } //* Add action to hook fired by cron event add_action( 'wpse_263953_remove_old_entries', 'wpse_263953_remove_old_entries' ); function wpse_263953_remove_old_entries() { //* Get all posts older than 7 days... $posts = get_posts( [ 'numberposts' => -1, //* Use `cat` to query the category ID //* 'cat' => 'wpse_263953_category_id', //* Use `category_name` to query the category slug 'category_name' => 'wpse_263953_category', 'date_query' => [ 'after' => date( "Y-m-d H:i:s", strtotime( '-7 days', current_time( 'timestamp' ) ) ), //* For posts older than a month, use '-1 months' in strtotime() ], ]); //* ...and delete them foreach( $posts as $post ) { wp_delete_post( $post->ID ); } } ```
263,988
<p>I have a custom post type in WordPress with custom meta boxes.</p> <p>So I need a hierarchal post and also have a custom template set for each of the post (either Type1 or Type2).</p> <p>This is how my slug looks,</p> <p><a href="http://example.com/taxonomy/type1" rel="nofollow noreferrer">http://example.com/taxonomy/type1</a> - for the primary post</p> <p><a href="http://example.com/taxonomy/type1/type2" rel="nofollow noreferrer">http://example.com/taxonomy/type1/type2</a> - for the secondary post</p> <p>The problem is that the type 2 page is essentially the same as the type1 just with a bit of additional information. And my client plans to have many posts in type1 which will lead to more posts in type2 and this will make managing hard.</p> <p>I can save all the content I need for type2 posts within the parent type1 using meta boxes. I just need a way to point the URLs to the right data. </p> <p>So if I access this URL, <code>http://example.com/taxonomy/type1/type2</code>, it will open primary post and load the data for it from a meta box (also has to load another template file). I want this done via php and don't want to load all the content and edit it frontend using javascript.</p> <p>Update:</p> <p>Sorry if I was a bit confusing. I already have a custom post type with a metabox that allows me to select a template (and also show additional metaboxes depending on the template).</p> <p>My slug already has the custom taxonomy I am using (used %name% as the slug in the argument for creating posts. </p> <p>And my posts slug work fine as long as I choose the right parent post. My question is, instead of creating a custom post (type2) as a child to the type1 post, how can I make wordpress redirect <code>http://example.com/taxonomy/type1/type2</code> to the type1 post and also get the text of type2 within a php function where I can print out the template for the pages.</p> <p><strong>Edit</strong></p> <pre><code>add_filter('query_vars', 'add_type2_var', 0, 1); </code></pre> <p>function add_type2_var($vars){ $vars[] = 'type2'; return $vars; }</p> <p>add_rewrite_rule('/?apk/(.[^/]<em>)/(.[^/]</em>)/(.*)$',"/wp/apk/$1/$2?type2=$3",'top');</p> <p>I have added this code to my theme and did <strong>not</strong> modify .htaccess. The type2 var shows up correctly when I use a child post url or if I add numbers at the end. I set hierarchical to false for the custom post type and the link still shows 404. Is there a way for me to bypass the 404? My guess is that I am trying to get the url using the single_template filter. But I should validate it somewhere before wordpress gives a 404.</p>
[ { "answer_id": 263960, "author": "JItendra Rana", "author_id": 87433, "author_profile": "https://wordpress.stackexchange.com/users/87433", "pm_score": 2, "selected": false, "text": "<p>Following Query will give you list of Post ID older than 30 days for given Category ID. </p>\n\n<pre><code>SELECT \n p.ID as post_id, \n term.term_id as category_id\nFROM wp_posts as p \nLEFT JOIN wp_term_relationships as tr ON tr.object_id = p.ID\nLEFT JOIN wp_terms as term ON tr.term_taxonomy_id = term.term_id\nWHERE term.term_id = \"CATEGORY ID HERE\" \n AND DATEDIFF(NOW(), p.post_date) &gt; 30\n</code></pre>\n\n<p>Once you get the list you can decide weather you want to delete post or not. </p>\n\n<p>To Delete the post use following function, the second parameter ( TRUE ) will delete the post permanently. If you want to keep the post in trash pass ( FALSE )</p>\n\n<pre><code>wp_delete_post( 'YOUR_POST_ID_HERE', TRUE);\n</code></pre>\n\n<p>Dont forget to change The Table prefix if its not 'wp_'</p>\n" }, { "answer_id": 264317, "author": "Nathan Johnson", "author_id": 106269, "author_profile": "https://wordpress.stackexchange.com/users/106269", "pm_score": 4, "selected": true, "text": "<p>The first step is setting up the cron job.</p>\n\n<p>The second part requires querying the database for a specific post type where the entry is older than 1 week. We can do this with get_posts() and specifying the category argument and the date_query argument.</p>\n\n<pre><code>//* If the scheduled event got removed from the cron schedule, re-add it\nif( ! wp_next_scheduled( 'wpse_263953_remove_old_entries' ) ) {\n wp_schedule_event( time(), 'daily', 'wpse_263953_remove_old_entries' );\n}\n\n//* Add action to hook fired by cron event\nadd_action( 'wpse_263953_remove_old_entries', 'wpse_263953_remove_old_entries' );\nfunction wpse_263953_remove_old_entries() {\n //* Get all posts older than 7 days...\n $posts = get_posts( [\n 'numberposts' =&gt; -1,\n //* Use `cat` to query the category ID\n //* 'cat' =&gt; 'wpse_263953_category_id',\n //* Use `category_name` to query the category slug\n 'category_name' =&gt; 'wpse_263953_category',\n 'date_query' =&gt; [\n 'after' =&gt; date( \"Y-m-d H:i:s\", strtotime( '-7 days', current_time( 'timestamp' ) ) ),\n //* For posts older than a month, use '-1 months' in strtotime()\n ],\n ]);\n //* ...and delete them\n foreach( $posts as $post ) {\n wp_delete_post( $post-&gt;ID );\n }\n}\n</code></pre>\n" } ]
2017/04/18
[ "https://wordpress.stackexchange.com/questions/263988", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/68381/" ]
I have a custom post type in WordPress with custom meta boxes. So I need a hierarchal post and also have a custom template set for each of the post (either Type1 or Type2). This is how my slug looks, <http://example.com/taxonomy/type1> - for the primary post <http://example.com/taxonomy/type1/type2> - for the secondary post The problem is that the type 2 page is essentially the same as the type1 just with a bit of additional information. And my client plans to have many posts in type1 which will lead to more posts in type2 and this will make managing hard. I can save all the content I need for type2 posts within the parent type1 using meta boxes. I just need a way to point the URLs to the right data. So if I access this URL, `http://example.com/taxonomy/type1/type2`, it will open primary post and load the data for it from a meta box (also has to load another template file). I want this done via php and don't want to load all the content and edit it frontend using javascript. Update: Sorry if I was a bit confusing. I already have a custom post type with a metabox that allows me to select a template (and also show additional metaboxes depending on the template). My slug already has the custom taxonomy I am using (used %name% as the slug in the argument for creating posts. And my posts slug work fine as long as I choose the right parent post. My question is, instead of creating a custom post (type2) as a child to the type1 post, how can I make wordpress redirect `http://example.com/taxonomy/type1/type2` to the type1 post and also get the text of type2 within a php function where I can print out the template for the pages. **Edit** ``` add_filter('query_vars', 'add_type2_var', 0, 1); ``` function add\_type2\_var($vars){ $vars[] = 'type2'; return $vars; } add\_rewrite\_rule('/?apk/(.[^/]*)/(.[^/]*)/(.\*)$',"/wp/apk/$1/$2?type2=$3",'top'); I have added this code to my theme and did **not** modify .htaccess. The type2 var shows up correctly when I use a child post url or if I add numbers at the end. I set hierarchical to false for the custom post type and the link still shows 404. Is there a way for me to bypass the 404? My guess is that I am trying to get the url using the single\_template filter. But I should validate it somewhere before wordpress gives a 404.
The first step is setting up the cron job. The second part requires querying the database for a specific post type where the entry is older than 1 week. We can do this with get\_posts() and specifying the category argument and the date\_query argument. ``` //* If the scheduled event got removed from the cron schedule, re-add it if( ! wp_next_scheduled( 'wpse_263953_remove_old_entries' ) ) { wp_schedule_event( time(), 'daily', 'wpse_263953_remove_old_entries' ); } //* Add action to hook fired by cron event add_action( 'wpse_263953_remove_old_entries', 'wpse_263953_remove_old_entries' ); function wpse_263953_remove_old_entries() { //* Get all posts older than 7 days... $posts = get_posts( [ 'numberposts' => -1, //* Use `cat` to query the category ID //* 'cat' => 'wpse_263953_category_id', //* Use `category_name` to query the category slug 'category_name' => 'wpse_263953_category', 'date_query' => [ 'after' => date( "Y-m-d H:i:s", strtotime( '-7 days', current_time( 'timestamp' ) ) ), //* For posts older than a month, use '-1 months' in strtotime() ], ]); //* ...and delete them foreach( $posts as $post ) { wp_delete_post( $post->ID ); } } ```
263,989
<p>I've restored my Wordpress database from an sql backup. However, in doing so, all of the tables have lost auto increment.</p> <p>When I try to add it back in with this sql </p> <pre><code>ALTER TABLE `mercury_posts` CHANGE `ID` `ID` BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT; </code></pre> <p>I get the error <code>#1067 - Invalid default value for 'post_date'</code>. How do I fix this?</p>
[ { "answer_id": 264142, "author": "SinisterBeard", "author_id": 63673, "author_profile": "https://wordpress.stackexchange.com/users/63673", "pm_score": 2, "selected": false, "text": "<p>I eventually solved this by deleting the faulty database, backing up again from the working database but exporting structure and data separately. </p>\n" }, { "answer_id": 313069, "author": "Carlos Faria", "author_id": 39047, "author_profile": "https://wordpress.stackexchange.com/users/39047", "pm_score": 3, "selected": false, "text": "<p>The post_date default value is 0000-00-00 00:00:00. If you check the sql_mode variable like this:</p>\n<pre><code>show variables like 'sql_mode'; \n</code></pre>\n<p>... it will show you the sql_mode variable, that will be sth like this: <strong>ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION</strong></p>\n<p>You have to set up again sql_mode variable without\n<strong>NO_ZERO_IN_DATE,NO_ZERO_DATE</strong></p>\n<p>So in the previous example you should set the sql_mode like this:</p>\n<pre><code>SET sql_mode = 'ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION';\n</code></pre>\n<p>Then check the sql_mode variable again to be sure it has changed correctly:</p>\n<pre><code>show variables like 'sql_mode';\n</code></pre>\n<p>Then the restriction is gone ;D</p>\n<p>Found the solution here: <a href=\"https://stackoverflow.com/a/37696251/504910\">https://stackoverflow.com/a/37696251/504910</a></p>\n" }, { "answer_id": 358403, "author": "Cristian Cartes", "author_id": 182558, "author_profile": "https://wordpress.stackexchange.com/users/182558", "pm_score": 3, "selected": false, "text": "<p>You must to add this code at the top of your SQL</p>\n\n<pre>SET SQL_MODE = \"NO_AUTO_VALUE_ON_ZERO\";\nSET AUTOCOMMIT = 0;\nSTART TRANSACTION;\nSET time_zone = \"+00:00\";</pre>\n" }, { "answer_id": 388556, "author": "Julius Barra", "author_id": 137900, "author_profile": "https://wordpress.stackexchange.com/users/137900", "pm_score": 0, "selected": false, "text": "<p>Changing sql_mode to</p>\n<p>ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION</p>\n<p>works, but it only lasts until you restart the sql server.</p>\n<p>So in case you need it again, you have to change sql_mode again.</p>\n" }, { "answer_id": 393416, "author": "Sumit Jangir", "author_id": 198937, "author_profile": "https://wordpress.stackexchange.com/users/198937", "pm_score": 2, "selected": false, "text": "<p><strong>You can use following command to change your default post_date:-</strong></p>\n<pre><code> ALTER TABLE `wp_posts` \n CHANGE `post_date` `post_date` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP\n</code></pre>\n" } ]
2017/04/18
[ "https://wordpress.stackexchange.com/questions/263989", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/63673/" ]
I've restored my Wordpress database from an sql backup. However, in doing so, all of the tables have lost auto increment. When I try to add it back in with this sql ``` ALTER TABLE `mercury_posts` CHANGE `ID` `ID` BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT; ``` I get the error `#1067 - Invalid default value for 'post_date'`. How do I fix this?
The post\_date default value is 0000-00-00 00:00:00. If you check the sql\_mode variable like this: ``` show variables like 'sql_mode'; ``` ... it will show you the sql\_mode variable, that will be sth like this: **ONLY\_FULL\_GROUP\_BY,STRICT\_TRANS\_TABLES,NO\_ZERO\_IN\_DATE,NO\_ZERO\_DATE,ERROR\_FOR\_DIVISION\_BY\_ZERO,NO\_AUTO\_CREATE\_USER,NO\_ENGINE\_SUBSTITUTION** You have to set up again sql\_mode variable without **NO\_ZERO\_IN\_DATE,NO\_ZERO\_DATE** So in the previous example you should set the sql\_mode like this: ``` SET sql_mode = 'ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION'; ``` Then check the sql\_mode variable again to be sure it has changed correctly: ``` show variables like 'sql_mode'; ``` Then the restriction is gone ;D Found the solution here: <https://stackoverflow.com/a/37696251/504910>
264,017
<p>Pretty much what the title says.</p> <p>I have a custom plugin written, that relies on the use of admin-ajax to handle various forms and actions. That's all working fine, however as the various functions echo out responses I have to throw in a die() after the echo function. ie:</p> <pre><code>echo $return_string; die(); </code></pre> <p>All fine, however this unfortunately breaks my PHPUnit tests as throwing in a die() will kill the script and prevent the unit test from working. Without the die I receive the traditional 0 at the end of my response, which isn't what I want. Have also tried the WP recommended:</p> <pre><code>wp_die(); </code></pre> <p>Does anyone have any ideas on how to get around this?</p>
[ { "answer_id": 264027, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 2, "selected": false, "text": "<p>Unfortunately, the ajax hook handler has to <code>die</code> otherwise wordpress will continue running and some more output might be generated (or might not, but you don't want to rely on it). </p>\n\n<p>The solution is probably to isolate your response generation code in a function and test the output it generate, and then on the hook handler itself just do</p>\n\n<pre><code>echo echo_fn(....);\nwp_die()\n</code></pre>\n\n<p>Then in your unit tests you test only <code>echo_fn()</code>.</p>\n" }, { "answer_id": 264042, "author": "J.D.", "author_id": 27757, "author_profile": "https://wordpress.stackexchange.com/users/27757", "pm_score": 3, "selected": false, "text": "<p>If you use <code>wp_die()</code> you can utilize the tools included with WordPress's PHPUnit test suite. The <code>WP_Ajax_UnitTestCase</code> provides the <code>_handleAjax()</code> method that will hook into the actions called by <code>wp_die()</code> and throw an exception, which will prevent <code>die()</code> from being called. I've written a <a href=\"https://codesymphony.co/wp-ajax-plugin-unit-testing/\" rel=\"noreferrer\">tutorial on how to use <code>WP_Ajax_UnitTestCase</code></a>, which explains all of the features it provides, but here is a basic example:</p>\n\n<pre><code>class My_Ajax_Test extends WP_Ajax_UnitTestCase {\n\n public function test_some_option_is_saved() {\n\n // Fulfill requirements of the callback here...\n $_POST['_wpnonce'] = wp_create_nonce( 'my_nonce' );\n $_POST['option_value'] = 'yes';\n\n try {\n $this-&gt;_handleAjax( 'my_ajax_action' );\n } catch ( WPAjaxDieStopException $e ) {\n // We expected this, do nothing.\n }\n\n // Check that the exception was thrown.\n $this-&gt;assertTrue( isset( $e ) );\n\n // Check that the callback did whatever it is expected to do...\n $this-&gt;assertEquals( 'yes', get_option( 'some_option' ) );\n }\n}\n</code></pre>\n\n<p>Note that technically speaking, this is integration testing rather than unit testing, as it tests a complete cross-section of the callback's functionality, not just a single unit. This is how WordPress does it, but depending on the complexity of your callback's code, you may also want to create true unit tests for it as well, probably abstracting portions of it out into other functions that you can mock.</p>\n" } ]
2017/04/18
[ "https://wordpress.stackexchange.com/questions/264017", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/71134/" ]
Pretty much what the title says. I have a custom plugin written, that relies on the use of admin-ajax to handle various forms and actions. That's all working fine, however as the various functions echo out responses I have to throw in a die() after the echo function. ie: ``` echo $return_string; die(); ``` All fine, however this unfortunately breaks my PHPUnit tests as throwing in a die() will kill the script and prevent the unit test from working. Without the die I receive the traditional 0 at the end of my response, which isn't what I want. Have also tried the WP recommended: ``` wp_die(); ``` Does anyone have any ideas on how to get around this?
If you use `wp_die()` you can utilize the tools included with WordPress's PHPUnit test suite. The `WP_Ajax_UnitTestCase` provides the `_handleAjax()` method that will hook into the actions called by `wp_die()` and throw an exception, which will prevent `die()` from being called. I've written a [tutorial on how to use `WP_Ajax_UnitTestCase`](https://codesymphony.co/wp-ajax-plugin-unit-testing/), which explains all of the features it provides, but here is a basic example: ``` class My_Ajax_Test extends WP_Ajax_UnitTestCase { public function test_some_option_is_saved() { // Fulfill requirements of the callback here... $_POST['_wpnonce'] = wp_create_nonce( 'my_nonce' ); $_POST['option_value'] = 'yes'; try { $this->_handleAjax( 'my_ajax_action' ); } catch ( WPAjaxDieStopException $e ) { // We expected this, do nothing. } // Check that the exception was thrown. $this->assertTrue( isset( $e ) ); // Check that the callback did whatever it is expected to do... $this->assertEquals( 'yes', get_option( 'some_option' ) ); } } ``` Note that technically speaking, this is integration testing rather than unit testing, as it tests a complete cross-section of the callback's functionality, not just a single unit. This is how WordPress does it, but depending on the complexity of your callback's code, you may also want to create true unit tests for it as well, probably abstracting portions of it out into other functions that you can mock.
264,022
<p>I found this action hook in wp-login.php file. It says it can be used to create custom actions to the wp-login. However, as I'm new to WP coding and PHP, I do not understand how {action} can work even though it is under double quotations? Here is the action hook:</p> <pre><code>do_action( "login_form_{$action}" ); </code></pre> <p>In the plugin that I'm following, this action hook is added by this:</p> <pre><code>add_action( 'login_form_login', array( $this, 'redirect_to_custom_login' )); </code></pre> <p>How does login_form_login matches and replaces login_form_{action} ?</p>
[ { "answer_id": 264029, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 2, "selected": false, "text": "<p>This is a <em>dynamic</em> hook:</p>\n\n<pre><code>do_action( \"login_form_{$action}\" );\n</code></pre>\n\n<p>Meaning that it depends on the <code>$action</code> variable.</p>\n\n<p>There are other such hooks used in the WordPress core.</p>\n\n<p>You can check out the naming convention for dynamic hooks in the <em>Core Contributor Handbook</em> <a href=\"https://make.wordpress.org/core/handbook/best-practices/coding-standards/php/#interpolation-for-naming-dynamic-hooks\" rel=\"nofollow noreferrer\">here</a>. It's says e.g.:</p>\n\n<blockquote>\n <p>Dynamic hooks should be named using interpolation rather than\n concatenation for readability and discoverability purposes.</p>\n</blockquote>\n\n<p><em>Double quoted</em> strings in PHP can parse variables, that's why it's not written with <em>single quotes</em>:</p>\n\n<pre><code>do_action( 'login_form_{$action}' );\n</code></pre>\n\n<p>Check out the <em>curly syntax</em> in the PHP docs in the <a href=\"http://php.net/manual/en/language.types.string.php#language.types.string.parsing\" rel=\"nofollow noreferrer\">variable parsing</a> section.</p>\n\n<p><strong>Example:</strong></p>\n\n<p>If we have:</p>\n\n<pre><code>$action = 'login';\n</code></pre>\n\n<p>then it will generate the following action: </p>\n\n<pre><code>do_action( \"login_form_login\" );\n</code></pre>\n\n<p>that plugins can hook into via: </p>\n\n<pre><code>add_action( 'login_form_login', ... );\n</code></pre>\n" }, { "answer_id": 264032, "author": "Nathan Johnson", "author_id": 106269, "author_profile": "https://wordpress.stackexchange.com/users/106269", "pm_score": 1, "selected": false, "text": "<p><code>$action</code> is a variable that is set on line 384 of wp-login.php (as of WordPress 4.7.3).</p>\n\n<pre><code>$action = isset($_REQUEST['action']) ? $_REQUEST['action'] : 'login';\n</code></pre>\n\n<p>When WordPress gets to line 428, it evaluates the string inside the double quotations first as <code>login_form_login</code> if the <code>$_REQUEST['action']</code> variable is not set. If that variable is set, for instance as <code>register</code>, then the string inside the double quotations would be evaluated as <code>login_form_register</code>.</p>\n\n<p>When the the WordPress function <code>do_action()</code> is interpreted, see <a href=\"https://core.trac.wordpress.org/browser/trunk/src/wp-includes/plugin.php#L421\" rel=\"nofollow noreferrer\">line 421 of wp-includes/plugin.php</a>, does some stuff, and on line 453 applies the <code>do_action()</code> method of the <code>$wp_filter</code> global.</p>\n\n<p>To see what this method does, we need to go to <a href=\"https://core.trac.wordpress.org/browser/trunk/src/wp-includes/class-wp-hook.php#L321\" rel=\"nofollow noreferrer\">line 321 of wp-includes/class-wp-hook.php</a>, which because hooks are just simplified filters, calls the <code>apply_filters()</code> method, which is on line 276 of the same file.</p>\n\n<p>The relevant parts of this method are lines 296, 298, and 300 and they look like:</p>\n\n<pre><code>$value = call_user_func_array( $the_['function'], array() );\n</code></pre>\n\n<p><a href=\"http://php.net/manual/en/function.call-user-func-array.php\" rel=\"nofollow noreferrer\"><code>call_user_func_array()</code></a> is a PHP function that calls a callback with an array of parameters.</p>\n\n<p>WordPress stores the callbacks for each hook in the <code>$wp_filter</code> global. We add them using the <code>add_action()</code> and <code>add_filter()</code> functions.</p>\n\n<pre><code>add_action( 'login_form_login', array( $this, 'redirect_to_custom_login' ));\n</code></pre>\n\n<p>This is telling WordPress to add an action to the <code>login_form_login</code> hook and the callable callback is the <code>redirect_to_custom_login</code> method from <code>$this</code> object.</p>\n" } ]
2017/04/18
[ "https://wordpress.stackexchange.com/questions/264022", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/112658/" ]
I found this action hook in wp-login.php file. It says it can be used to create custom actions to the wp-login. However, as I'm new to WP coding and PHP, I do not understand how {action} can work even though it is under double quotations? Here is the action hook: ``` do_action( "login_form_{$action}" ); ``` In the plugin that I'm following, this action hook is added by this: ``` add_action( 'login_form_login', array( $this, 'redirect_to_custom_login' )); ``` How does login\_form\_login matches and replaces login\_form\_{action} ?
This is a *dynamic* hook: ``` do_action( "login_form_{$action}" ); ``` Meaning that it depends on the `$action` variable. There are other such hooks used in the WordPress core. You can check out the naming convention for dynamic hooks in the *Core Contributor Handbook* [here](https://make.wordpress.org/core/handbook/best-practices/coding-standards/php/#interpolation-for-naming-dynamic-hooks). It's says e.g.: > > Dynamic hooks should be named using interpolation rather than > concatenation for readability and discoverability purposes. > > > *Double quoted* strings in PHP can parse variables, that's why it's not written with *single quotes*: ``` do_action( 'login_form_{$action}' ); ``` Check out the *curly syntax* in the PHP docs in the [variable parsing](http://php.net/manual/en/language.types.string.php#language.types.string.parsing) section. **Example:** If we have: ``` $action = 'login'; ``` then it will generate the following action: ``` do_action( "login_form_login" ); ``` that plugins can hook into via: ``` add_action( 'login_form_login', ... ); ```
264,046
<h1>I need foo-bar to become foo/bar instead:</h1> <p>//domain.com<b>/foo-bar</b> &nbsp; &raquo; &nbsp; //domain.com<b>/foo/bar</b></p> <hr> <p>I'm rebuilding a website that is currently in a home-brew CMS. They have a few pages with children, but the parent page URL does not match the children. The parent URLs were changed but the children were never updated.</p> <p><strong>Expected Structure:</strong><br/> //domain.com/parent/<br/> //domain.com/parent/child</p> <p><strong>Current Structure:</strong><br/> //domain.com/parentpage/ &nbsp; &nbsp; (<em>changed from /parent/</em>)<br/> //domain.com/parent/child</p> <p>I could just create a page for each but I'm trying to avoid having empty/unused pages.</p> <p><strong>What I'm hoping to do is just create //domain.com/parent-child/ and rewrite the URL to match, but I can't get my rules to take priority over an existing rule</strong>.</p> <p>Maybe I'm misunderstanding what rewrites can accomplish?</p> <hr> <h1>add_rewrite_rule</h1> <p><strong>Matched Query:</strong></p> <pre><code>pagename=foo-bar&amp;page= </code></pre> <p><strong>My Attempts:</strong> I expected somethig like one of these to be my solution, but I've tried a dozen different minor variations without success:</p> <pre><code>add_rewrite_rule( '^foo/bar', 'index.php?pagename=foo-bar', 'top'); add_rewrite_rule( '(foo)/(bar)', 'index.php?pagename=$matches[1]-$matches[2]&amp;page=', 'top'); </code></pre> <p><strong>Default rule my page is matching:</strong></p> <pre><code>add_rewrite_rule( '(.?.+?)(?:/([0-9]+))?/?$', 'index.php?pagename=$matches[1]&amp;page=$matches[2]') </code></pre>
[ { "answer_id": 264165, "author": "Oleg Butuzov", "author_id": 14536, "author_profile": "https://wordpress.stackexchange.com/users/14536", "pm_score": 0, "selected": false, "text": "<p>First of all, you can change rules not only with <code>add_rewrite_rule</code> but also with a filter(s) (one - general I am using in all common cases is <code>rewrite_rules_array</code>). You will receive an array of rewrite rules (and you expect to return it back), but you can change it slightly.</p>\n\n<p>And (minute of advertisement) - you can also use <a href=\"https://wordpress.org/plugins/debug-bar/\" rel=\"nofollow noreferrer\">debug bar</a> and <a href=\"https://wordpress.org/plugins/debug-bar-rewrite-rules/\" rel=\"nofollow noreferrer\">debug bar rewrite rules</a> panel to check your rules against your test URLs to see priority/matches etc. I am the author of this plugin (debug bar rewrite rules panel) and will be glad for a feedback. </p>\n" }, { "answer_id": 264170, "author": "H21", "author_id": 103994, "author_profile": "https://wordpress.stackexchange.com/users/103994", "pm_score": 2, "selected": true, "text": "<p>This rule is what I ended up with after finding this post:\n<a href=\"https://wordpress.stackexchange.com/questions/250837/understanding-add-rewrite-rule\">Understanding add_rewrite_rule</a></p>\n\n<pre><code>add_rewrite_rule( '^foo/([^/]*)/?$', 'index.php?pagename=foo-$matches[1]', 'top' );\n</code></pre>\n" } ]
2017/04/18
[ "https://wordpress.stackexchange.com/questions/264046", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/103994/" ]
I need foo-bar to become foo/bar instead: ========================================= //domain.com**/foo-bar**   »   //domain.com**/foo/bar** --- I'm rebuilding a website that is currently in a home-brew CMS. They have a few pages with children, but the parent page URL does not match the children. The parent URLs were changed but the children were never updated. **Expected Structure:** //domain.com/parent/ //domain.com/parent/child **Current Structure:** //domain.com/parentpage/     (*changed from /parent/*) //domain.com/parent/child I could just create a page for each but I'm trying to avoid having empty/unused pages. **What I'm hoping to do is just create //domain.com/parent-child/ and rewrite the URL to match, but I can't get my rules to take priority over an existing rule**. Maybe I'm misunderstanding what rewrites can accomplish? --- add\_rewrite\_rule ================== **Matched Query:** ``` pagename=foo-bar&page= ``` **My Attempts:** I expected somethig like one of these to be my solution, but I've tried a dozen different minor variations without success: ``` add_rewrite_rule( '^foo/bar', 'index.php?pagename=foo-bar', 'top'); add_rewrite_rule( '(foo)/(bar)', 'index.php?pagename=$matches[1]-$matches[2]&page=', 'top'); ``` **Default rule my page is matching:** ``` add_rewrite_rule( '(.?.+?)(?:/([0-9]+))?/?$', 'index.php?pagename=$matches[1]&page=$matches[2]') ```
This rule is what I ended up with after finding this post: [Understanding add\_rewrite\_rule](https://wordpress.stackexchange.com/questions/250837/understanding-add-rewrite-rule) ``` add_rewrite_rule( '^foo/([^/]*)/?$', 'index.php?pagename=foo-$matches[1]', 'top' ); ```
264,054
<p>I want to add divs and classes to child [ li ] elements that come after [ ul class ="sub-menu" ] of the parent [ li ]. The problem is, when I try to modify the [ li ] in the start_el function, all [ li ] get modified, even the ones that are outside of the [ ul class ="sub-menu" ], the parent ones also get modified. Please help me to seperate the [ li ], so that I can only modify the ones that are inside [ ul class ="sub-menu" ] without Javascript.</p> <pre><code>public function start_el( &amp;$output, $item, $depth = 0, $args = array(), $id = 0 ) { if ( isset( $args-&gt;item_spacing ) &amp;&amp; 'discard' === $args-&gt;item_spacing ) { $t = ''; $n = ''; } else { $t = "\t"; $n = "\n"; } $indent = ( $depth ) ? str_repeat( $t, $depth ) : ''; $classes = empty( $item-&gt;classes ) ? array() : (array) $item-&gt;classes; $classes[] = 'menu-item-' . $item-&gt;ID; $class_names = join( ' ', apply_filters( 'nav_menu_css_class', array_filter( $classes ), $item, $args, $depth ) ); $class_names = $class_names ? ' class="' . esc_attr( $class_names ) . '"' : ''; $id = apply_filters( 'nav_menu_item_id', 'menu-item-'. $item-&gt;ID, $item, $args, $depth ); $id = $id ? ' id="' . esc_attr( $id ) . '"' : ''; $output .= $indent . '&lt;li' . $id . $class_names .'&gt;'; $atts = array(); $atts['title'] = ! empty( $item-&gt;attr_title ) ? $item-&gt;attr_title : ''; $atts['target'] = ! empty( $item-&gt;target ) ? $item-&gt;target : ''; $atts['rel'] = ! empty( $item-&gt;xfn ) ? $item-&gt;xfn : ''; $atts['href'] = ! empty( $item-&gt;url ) ? $item-&gt;url : ''; $atts = apply_filters( 'nav_menu_link_attributes', $atts, $item, $args, $depth ); $attributes = ''; foreach ( $atts as $attr =&gt; $value ) { if ( ! empty( $value ) ) { $value = ( 'href' === $attr ) ? esc_url( $value ) : esc_attr( $value ); $attributes .= ' ' . $attr . '="' . $value . '"'; } } $title = apply_filters( 'the_title', $item-&gt;title, $item-&gt;ID ); $title = apply_filters( 'nav_menu_item_title', $title, $item, $args, $depth ); $item_output = $args-&gt;before; $item_output .= '&lt;a'. $attributes .'&gt;'; $item_output .= $args-&gt;link_before . $title . $args-&gt;link_after; $item_output .= '&lt;/a&gt;'; $item_output .= $args-&gt;after; $output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args ); } </code></pre>
[ { "answer_id": 264059, "author": "Diogo", "author_id": 115596, "author_profile": "https://wordpress.stackexchange.com/users/115596", "pm_score": 0, "selected": false, "text": "<p>If you want to dinamically insert those <code>&lt;div&gt;</code>s based on some condition or trigger you will need javascript (or jQuery or php). There´s no escaping from scripting languages.</p>\n\n<p>The <code>&lt;li&gt;</code>´s coming out of this function are defined in this variable: </p>\n\n<p><code>$output .= $indent . '&lt;li' . $id . $class_names .'&gt;';</code> </p>\n\n<p>So, if you to add a <code>&lt;div&gt;</code> inside it, you can try this: </p>\n\n<p><code>$output .= $indent . '&lt;li' . $id . $class_names .'&gt;' . '&lt;div class=\"class-1 class-2\"&gt;';</code></p>\n\n<p>However, if these <code>&lt;div&gt;</code>´s should be present at all times, you can just hardcode it in the php file it is coming from.</p>\n\n<p>When it comes to applying style changes to only those specific <code>&lt;li&gt;</code>´s, if you´re doing it via CSS it´s quite simple and all you have to do is be specific about the <code>&lt;li&gt;</code> you want to target. </p>\n\n<p>Like so:</p>\n\n<pre><code>ul.sub-menu li.the-li-class {\n property: value;\n}\n</code></pre>\n\n<p>If you´re doing it using jQuery, for example, it´ll be something like this:</p>\n\n<pre><code>$('.sub-menu').find('.li-class');\n $(this).css({'property-1' : 'value', 'property-2' : 'value' });\n</code></pre>\n\n<p>There are other approaches when it comes to jQuery. It´s all about knowing how to traverse the DOM tree and you may want to dig deeper into this if you´re not familiar.</p>\n" }, { "answer_id": 264061, "author": "ngearing", "author_id": 50184, "author_profile": "https://wordpress.stackexchange.com/users/50184", "pm_score": 2, "selected": false, "text": "<p>You don't need to make a whole new walker, you can do this with just a filter and some conditionals based on the function parameters.</p>\n\n<p>The filter we need is <code>walker_nav_menu_start_el</code> which you can see at the bottom of your code sample.</p>\n\n<p>And to make sure we only target the child pages we can use the <code>$depth</code> parameter from that function, see example below.</p>\n\n<pre><code>function ngstyle_child_menu_items($item_output, $item, $depth, $args)\n{\n // Check we are on the right menu &amp; right depth\n if ($args-&gt;theme_location != 'primary' || $depth !== 1) {\n return $item_output;\n }\n\n $new_output = $item_output;\n $new_output .= '&lt;div class=\"super-mega-awesome\"&gt;&lt;/div&gt;'; // Add custom elems\n\n return $new_output;\n}\nadd_filter('walker_nav_menu_start_el', 'ngstyle_child_menu_items', 10, 4);\n</code></pre>\n" } ]
2017/04/18
[ "https://wordpress.stackexchange.com/questions/264054", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/116197/" ]
I want to add divs and classes to child [ li ] elements that come after [ ul class ="sub-menu" ] of the parent [ li ]. The problem is, when I try to modify the [ li ] in the start\_el function, all [ li ] get modified, even the ones that are outside of the [ ul class ="sub-menu" ], the parent ones also get modified. Please help me to seperate the [ li ], so that I can only modify the ones that are inside [ ul class ="sub-menu" ] without Javascript. ``` public function start_el( &$output, $item, $depth = 0, $args = array(), $id = 0 ) { if ( isset( $args->item_spacing ) && 'discard' === $args->item_spacing ) { $t = ''; $n = ''; } else { $t = "\t"; $n = "\n"; } $indent = ( $depth ) ? str_repeat( $t, $depth ) : ''; $classes = empty( $item->classes ) ? array() : (array) $item->classes; $classes[] = 'menu-item-' . $item->ID; $class_names = join( ' ', apply_filters( 'nav_menu_css_class', array_filter( $classes ), $item, $args, $depth ) ); $class_names = $class_names ? ' class="' . esc_attr( $class_names ) . '"' : ''; $id = apply_filters( 'nav_menu_item_id', 'menu-item-'. $item->ID, $item, $args, $depth ); $id = $id ? ' id="' . esc_attr( $id ) . '"' : ''; $output .= $indent . '<li' . $id . $class_names .'>'; $atts = array(); $atts['title'] = ! empty( $item->attr_title ) ? $item->attr_title : ''; $atts['target'] = ! empty( $item->target ) ? $item->target : ''; $atts['rel'] = ! empty( $item->xfn ) ? $item->xfn : ''; $atts['href'] = ! empty( $item->url ) ? $item->url : ''; $atts = apply_filters( 'nav_menu_link_attributes', $atts, $item, $args, $depth ); $attributes = ''; foreach ( $atts as $attr => $value ) { if ( ! empty( $value ) ) { $value = ( 'href' === $attr ) ? esc_url( $value ) : esc_attr( $value ); $attributes .= ' ' . $attr . '="' . $value . '"'; } } $title = apply_filters( 'the_title', $item->title, $item->ID ); $title = apply_filters( 'nav_menu_item_title', $title, $item, $args, $depth ); $item_output = $args->before; $item_output .= '<a'. $attributes .'>'; $item_output .= $args->link_before . $title . $args->link_after; $item_output .= '</a>'; $item_output .= $args->after; $output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args ); } ```
You don't need to make a whole new walker, you can do this with just a filter and some conditionals based on the function parameters. The filter we need is `walker_nav_menu_start_el` which you can see at the bottom of your code sample. And to make sure we only target the child pages we can use the `$depth` parameter from that function, see example below. ``` function ngstyle_child_menu_items($item_output, $item, $depth, $args) { // Check we are on the right menu & right depth if ($args->theme_location != 'primary' || $depth !== 1) { return $item_output; } $new_output = $item_output; $new_output .= '<div class="super-mega-awesome"></div>'; // Add custom elems return $new_output; } add_filter('walker_nav_menu_start_el', 'ngstyle_child_menu_items', 10, 4); ```
264,055
<p>I´ve been struggling with this for nearly a month now and still couldn´t find anything at all on how to do this! Not here, not in Quora, not through many different advanced Google search queries...</p> <p>Here it is:</p> <p>The <strong>parent theme</strong> has only <strong>one script file</strong> <code>main.min.js</code>. It contains all the scripts and libraries being used by it, including <code>jQuery</code>, <code>Select2</code>, <code>Parsley</code> and <code>Slick</code>, to name a few.</p> <p>How do I go about <strong>making my own scripts use one or more of these libraries as their dependencies in the child theme</strong>?</p> <p>The immediatelly obvious approach is to declare the parent theme <code>main.min.js</code> as the dependency when enqueueing my own scripts in the child´s <code>functions.php</code> and make sure my scripts fire after the dependency has been loaded on the page.</p> <p>I´ve done that, yet, it doesn´t work. My scripts cannot access their dependencies.</p> <p>The only alternative I can think of is enqueueing all these libraries separately in the child theme, as if the parent didn´t have them. Which is clearly a horrible thing to do, as the parent theme will load these libraries in its main js file too!</p> <p>So there must be a way to do this by using the <strong>already provided libraries</strong> in the parent.</p> <p>Had the parent theme enqueued the libraries separately this would be easy. I guess the main issue here is that all scripts and libraries are included in one single js file.</p> <p>Any help would be immensely appreciated!</p>
[ { "answer_id": 264059, "author": "Diogo", "author_id": 115596, "author_profile": "https://wordpress.stackexchange.com/users/115596", "pm_score": 0, "selected": false, "text": "<p>If you want to dinamically insert those <code>&lt;div&gt;</code>s based on some condition or trigger you will need javascript (or jQuery or php). There´s no escaping from scripting languages.</p>\n\n<p>The <code>&lt;li&gt;</code>´s coming out of this function are defined in this variable: </p>\n\n<p><code>$output .= $indent . '&lt;li' . $id . $class_names .'&gt;';</code> </p>\n\n<p>So, if you to add a <code>&lt;div&gt;</code> inside it, you can try this: </p>\n\n<p><code>$output .= $indent . '&lt;li' . $id . $class_names .'&gt;' . '&lt;div class=\"class-1 class-2\"&gt;';</code></p>\n\n<p>However, if these <code>&lt;div&gt;</code>´s should be present at all times, you can just hardcode it in the php file it is coming from.</p>\n\n<p>When it comes to applying style changes to only those specific <code>&lt;li&gt;</code>´s, if you´re doing it via CSS it´s quite simple and all you have to do is be specific about the <code>&lt;li&gt;</code> you want to target. </p>\n\n<p>Like so:</p>\n\n<pre><code>ul.sub-menu li.the-li-class {\n property: value;\n}\n</code></pre>\n\n<p>If you´re doing it using jQuery, for example, it´ll be something like this:</p>\n\n<pre><code>$('.sub-menu').find('.li-class');\n $(this).css({'property-1' : 'value', 'property-2' : 'value' });\n</code></pre>\n\n<p>There are other approaches when it comes to jQuery. It´s all about knowing how to traverse the DOM tree and you may want to dig deeper into this if you´re not familiar.</p>\n" }, { "answer_id": 264061, "author": "ngearing", "author_id": 50184, "author_profile": "https://wordpress.stackexchange.com/users/50184", "pm_score": 2, "selected": false, "text": "<p>You don't need to make a whole new walker, you can do this with just a filter and some conditionals based on the function parameters.</p>\n\n<p>The filter we need is <code>walker_nav_menu_start_el</code> which you can see at the bottom of your code sample.</p>\n\n<p>And to make sure we only target the child pages we can use the <code>$depth</code> parameter from that function, see example below.</p>\n\n<pre><code>function ngstyle_child_menu_items($item_output, $item, $depth, $args)\n{\n // Check we are on the right menu &amp; right depth\n if ($args-&gt;theme_location != 'primary' || $depth !== 1) {\n return $item_output;\n }\n\n $new_output = $item_output;\n $new_output .= '&lt;div class=\"super-mega-awesome\"&gt;&lt;/div&gt;'; // Add custom elems\n\n return $new_output;\n}\nadd_filter('walker_nav_menu_start_el', 'ngstyle_child_menu_items', 10, 4);\n</code></pre>\n" } ]
2017/04/18
[ "https://wordpress.stackexchange.com/questions/264055", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/115596/" ]
I´ve been struggling with this for nearly a month now and still couldn´t find anything at all on how to do this! Not here, not in Quora, not through many different advanced Google search queries... Here it is: The **parent theme** has only **one script file** `main.min.js`. It contains all the scripts and libraries being used by it, including `jQuery`, `Select2`, `Parsley` and `Slick`, to name a few. How do I go about **making my own scripts use one or more of these libraries as their dependencies in the child theme**? The immediatelly obvious approach is to declare the parent theme `main.min.js` as the dependency when enqueueing my own scripts in the child´s `functions.php` and make sure my scripts fire after the dependency has been loaded on the page. I´ve done that, yet, it doesn´t work. My scripts cannot access their dependencies. The only alternative I can think of is enqueueing all these libraries separately in the child theme, as if the parent didn´t have them. Which is clearly a horrible thing to do, as the parent theme will load these libraries in its main js file too! So there must be a way to do this by using the **already provided libraries** in the parent. Had the parent theme enqueued the libraries separately this would be easy. I guess the main issue here is that all scripts and libraries are included in one single js file. Any help would be immensely appreciated!
You don't need to make a whole new walker, you can do this with just a filter and some conditionals based on the function parameters. The filter we need is `walker_nav_menu_start_el` which you can see at the bottom of your code sample. And to make sure we only target the child pages we can use the `$depth` parameter from that function, see example below. ``` function ngstyle_child_menu_items($item_output, $item, $depth, $args) { // Check we are on the right menu & right depth if ($args->theme_location != 'primary' || $depth !== 1) { return $item_output; } $new_output = $item_output; $new_output .= '<div class="super-mega-awesome"></div>'; // Add custom elems return $new_output; } add_filter('walker_nav_menu_start_el', 'ngstyle_child_menu_items', 10, 4); ```
264,070
<p>Stuck in an infinite loop when trying to log in to my wordpress site. I type in the URL/wp-admin and then it loops me back to the regular website, not the admin login page. </p> <p>I have tried with http and https to no luck... </p>
[ { "answer_id": 264079, "author": "mayersdesign", "author_id": 106965, "author_profile": "https://wordpress.stackexchange.com/users/106965", "pm_score": 3, "selected": false, "text": "<p>Don't worry, you'll be back in quick if you follow these steps one at a time, until one succeeds!</p>\n\n<ol>\n<li><strong>Clear you cookies</strong> - Clear your local browser cookies (follow instructions for whatever browser you are using.</li>\n<li><strong>Deactivate All Plugins</strong> - Rename /wp-content/plugins/ directory to plugins_OLD</li>\n<li><strong>Revert Back to the Default Theme</strong> - Go to /wp-content/themes/ directory and rename your current theme directory to anything (like theme_OLD).</li>\n<li><strong>\"Delete\" .htaccess File</strong> - Again using FTP software, rename this to .htaccess_OLD</li>\n<li><strong>Update Site URL</strong> - In wp-config.php add these lines (using your url of course):</li>\n</ol>\n\n<p><code>define('WP_HOME','http://example.com');\ndefine('WP_SITEURL','http://example.com');</code></p>\n" }, { "answer_id": 295238, "author": "Vadim", "author_id": 137588, "author_profile": "https://wordpress.stackexchange.com/users/137588", "pm_score": 5, "selected": false, "text": "<p>I found a solution. In <code>wp-config.php</code> add:</p>\n\n<pre><code>define('FORCE_SSL_ADMIN', false);\n</code></pre>\n\n<p>In my situation, I migrated to <em>https</em> from <em>http</em>, and use plugin <em>Rename wp-login.php</em></p>\n\n<p>My <code>wp-config.php</code> contained the lines:</p>\n\n<pre><code>define('WP_SITEURL','https://example.com');\ndefine('WP_HOME','https://example.com');\n</code></pre>\n\n<p>Without the line <code>define('FORCE_SSL_ADMIN', false);</code>, a redirect loop occurs.</p>\n" }, { "answer_id": 306767, "author": "ClickMonster", "author_id": 145745, "author_profile": "https://wordpress.stackexchange.com/users/145745", "pm_score": 1, "selected": false, "text": "<p>I spend hours trying to resolve this, did everything. Eventually notice a log about group write permissions on the wp-login.php file. Looked and the server file permissions were 664 .. changed them to 644 and problem solved.</p>\n" }, { "answer_id": 311802, "author": "MTAdmin", "author_id": 116134, "author_profile": "https://wordpress.stackexchange.com/users/116134", "pm_score": 1, "selected": false, "text": "<p>I had the same issue after moving my site from a production host to localhost for dev testing. Steps that work for me in production didn't work locally. For instance, when using Chrome as my browser, entering </p>\n\n<p><strong><a href=\"http://localhost/wp/wp-admin\" rel=\"nofollow noreferrer\">http://localhost/wp/wp-admin</a></strong> would redirect to </p>\n\n<p><strong><a href=\"http://localhost/wp/wp-login.php?redirect_to=http%3A%2F%2Flocalhost%2Fwp%2Fwpcurrent%2Fwp-admin%2F&amp;reauth=1\" rel=\"nofollow noreferrer\">http://localhost/wp/wp-login.php?redirect_to=http%3A%2F%2Flocalhost%2Fwp%2Fwpcurrent%2Fwp-admin%2F&amp;reauth=1</a></strong>. </p>\n\n<p>Entering my username/password would redirect back to the second link with a new username/password prompt. </p>\n\n<p><strong>Firefox resolution:</strong> add to wp-config.php:</p>\n\n<pre><code>define('WP_HOME','http://your_url.com'); \ndefine('WP_SITEURL','http://your_url.com');\n</code></pre>\n\n<p><strong>Chrome resolution:</strong> Remove the redirect querystring from the login page: e.g. <strong><a href=\"http://localhost/wp/wp-login.php\" rel=\"nofollow noreferrer\">http://localhost/wp/wp-login.php</a></strong> . </p>\n\n<p>Yes, I'm fairly new to Wordpress and I'm not 100% certain of the internal route for logins and redirects after authentication, so much trial and error was involved to find these two solutions. Hopefully they can help someone else. </p>\n" }, { "answer_id": 325933, "author": "nfbne", "author_id": 159267, "author_profile": "https://wordpress.stackexchange.com/users/159267", "pm_score": 3, "selected": false, "text": "<p>I've just solved an issue with this symptom. The 8 key and salt values must be present in the <code>wp-config.php</code> file or admin doesn't work.</p>\n\n<p>I had these in the file, but because of how I dynamically generated <code>wp-config.php</code> the values were appended at the bottom of the file. Any constant definitions (<code>define()</code>) must be placed above the <code>/* That's all, stop editing! Happy blogging. */</code> line.</p>\n\n<p>Wordpress gave no error or logs to indicate it was missing config items. This also stopped <code>'WP_DEBUG', true</code> working. Once I moved all of these higher in the <code>wp-config.php</code> file everything started working.</p>\n" } ]
2017/04/19
[ "https://wordpress.stackexchange.com/questions/264070", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/117937/" ]
Stuck in an infinite loop when trying to log in to my wordpress site. I type in the URL/wp-admin and then it loops me back to the regular website, not the admin login page. I have tried with http and https to no luck...
I found a solution. In `wp-config.php` add: ``` define('FORCE_SSL_ADMIN', false); ``` In my situation, I migrated to *https* from *http*, and use plugin *Rename wp-login.php* My `wp-config.php` contained the lines: ``` define('WP_SITEURL','https://example.com'); define('WP_HOME','https://example.com'); ``` Without the line `define('FORCE_SSL_ADMIN', false);`, a redirect loop occurs.
264,089
<p>I am learning AngularJS and wanted to created a project in AngularJS 4. In this I want to use WordPress back-end and get data through rest API. I have done little bit research but not found any useful tutorial or example. I don't want to create theme in WordPress based on AngularJS, but want independent application in AngularJS which only use WordPress rest API for displaying content. I want to know how can i implement Wordpress Rest API in to AngluarJS application. So tutorial or example in this topic will be great helpful</p>
[ { "answer_id": 264079, "author": "mayersdesign", "author_id": 106965, "author_profile": "https://wordpress.stackexchange.com/users/106965", "pm_score": 3, "selected": false, "text": "<p>Don't worry, you'll be back in quick if you follow these steps one at a time, until one succeeds!</p>\n\n<ol>\n<li><strong>Clear you cookies</strong> - Clear your local browser cookies (follow instructions for whatever browser you are using.</li>\n<li><strong>Deactivate All Plugins</strong> - Rename /wp-content/plugins/ directory to plugins_OLD</li>\n<li><strong>Revert Back to the Default Theme</strong> - Go to /wp-content/themes/ directory and rename your current theme directory to anything (like theme_OLD).</li>\n<li><strong>\"Delete\" .htaccess File</strong> - Again using FTP software, rename this to .htaccess_OLD</li>\n<li><strong>Update Site URL</strong> - In wp-config.php add these lines (using your url of course):</li>\n</ol>\n\n<p><code>define('WP_HOME','http://example.com');\ndefine('WP_SITEURL','http://example.com');</code></p>\n" }, { "answer_id": 295238, "author": "Vadim", "author_id": 137588, "author_profile": "https://wordpress.stackexchange.com/users/137588", "pm_score": 5, "selected": false, "text": "<p>I found a solution. In <code>wp-config.php</code> add:</p>\n\n<pre><code>define('FORCE_SSL_ADMIN', false);\n</code></pre>\n\n<p>In my situation, I migrated to <em>https</em> from <em>http</em>, and use plugin <em>Rename wp-login.php</em></p>\n\n<p>My <code>wp-config.php</code> contained the lines:</p>\n\n<pre><code>define('WP_SITEURL','https://example.com');\ndefine('WP_HOME','https://example.com');\n</code></pre>\n\n<p>Without the line <code>define('FORCE_SSL_ADMIN', false);</code>, a redirect loop occurs.</p>\n" }, { "answer_id": 306767, "author": "ClickMonster", "author_id": 145745, "author_profile": "https://wordpress.stackexchange.com/users/145745", "pm_score": 1, "selected": false, "text": "<p>I spend hours trying to resolve this, did everything. Eventually notice a log about group write permissions on the wp-login.php file. Looked and the server file permissions were 664 .. changed them to 644 and problem solved.</p>\n" }, { "answer_id": 311802, "author": "MTAdmin", "author_id": 116134, "author_profile": "https://wordpress.stackexchange.com/users/116134", "pm_score": 1, "selected": false, "text": "<p>I had the same issue after moving my site from a production host to localhost for dev testing. Steps that work for me in production didn't work locally. For instance, when using Chrome as my browser, entering </p>\n\n<p><strong><a href=\"http://localhost/wp/wp-admin\" rel=\"nofollow noreferrer\">http://localhost/wp/wp-admin</a></strong> would redirect to </p>\n\n<p><strong><a href=\"http://localhost/wp/wp-login.php?redirect_to=http%3A%2F%2Flocalhost%2Fwp%2Fwpcurrent%2Fwp-admin%2F&amp;reauth=1\" rel=\"nofollow noreferrer\">http://localhost/wp/wp-login.php?redirect_to=http%3A%2F%2Flocalhost%2Fwp%2Fwpcurrent%2Fwp-admin%2F&amp;reauth=1</a></strong>. </p>\n\n<p>Entering my username/password would redirect back to the second link with a new username/password prompt. </p>\n\n<p><strong>Firefox resolution:</strong> add to wp-config.php:</p>\n\n<pre><code>define('WP_HOME','http://your_url.com'); \ndefine('WP_SITEURL','http://your_url.com');\n</code></pre>\n\n<p><strong>Chrome resolution:</strong> Remove the redirect querystring from the login page: e.g. <strong><a href=\"http://localhost/wp/wp-login.php\" rel=\"nofollow noreferrer\">http://localhost/wp/wp-login.php</a></strong> . </p>\n\n<p>Yes, I'm fairly new to Wordpress and I'm not 100% certain of the internal route for logins and redirects after authentication, so much trial and error was involved to find these two solutions. Hopefully they can help someone else. </p>\n" }, { "answer_id": 325933, "author": "nfbne", "author_id": 159267, "author_profile": "https://wordpress.stackexchange.com/users/159267", "pm_score": 3, "selected": false, "text": "<p>I've just solved an issue with this symptom. The 8 key and salt values must be present in the <code>wp-config.php</code> file or admin doesn't work.</p>\n\n<p>I had these in the file, but because of how I dynamically generated <code>wp-config.php</code> the values were appended at the bottom of the file. Any constant definitions (<code>define()</code>) must be placed above the <code>/* That's all, stop editing! Happy blogging. */</code> line.</p>\n\n<p>Wordpress gave no error or logs to indicate it was missing config items. This also stopped <code>'WP_DEBUG', true</code> working. Once I moved all of these higher in the <code>wp-config.php</code> file everything started working.</p>\n" } ]
2017/04/19
[ "https://wordpress.stackexchange.com/questions/264089", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/94923/" ]
I am learning AngularJS and wanted to created a project in AngularJS 4. In this I want to use WordPress back-end and get data through rest API. I have done little bit research but not found any useful tutorial or example. I don't want to create theme in WordPress based on AngularJS, but want independent application in AngularJS which only use WordPress rest API for displaying content. I want to know how can i implement Wordpress Rest API in to AngluarJS application. So tutorial or example in this topic will be great helpful
I found a solution. In `wp-config.php` add: ``` define('FORCE_SSL_ADMIN', false); ``` In my situation, I migrated to *https* from *http*, and use plugin *Rename wp-login.php* My `wp-config.php` contained the lines: ``` define('WP_SITEURL','https://example.com'); define('WP_HOME','https://example.com'); ``` Without the line `define('FORCE_SSL_ADMIN', false);`, a redirect loop occurs.
264,096
<p>I've implemented some meta fields for users like mobile number, address. It can be updated by user as well as admin, I wan't to trigger an email to user and admin stating about the updated field value if any value is updated, irrespective of who updates it.</p>
[ { "answer_id": 264079, "author": "mayersdesign", "author_id": 106965, "author_profile": "https://wordpress.stackexchange.com/users/106965", "pm_score": 3, "selected": false, "text": "<p>Don't worry, you'll be back in quick if you follow these steps one at a time, until one succeeds!</p>\n\n<ol>\n<li><strong>Clear you cookies</strong> - Clear your local browser cookies (follow instructions for whatever browser you are using.</li>\n<li><strong>Deactivate All Plugins</strong> - Rename /wp-content/plugins/ directory to plugins_OLD</li>\n<li><strong>Revert Back to the Default Theme</strong> - Go to /wp-content/themes/ directory and rename your current theme directory to anything (like theme_OLD).</li>\n<li><strong>\"Delete\" .htaccess File</strong> - Again using FTP software, rename this to .htaccess_OLD</li>\n<li><strong>Update Site URL</strong> - In wp-config.php add these lines (using your url of course):</li>\n</ol>\n\n<p><code>define('WP_HOME','http://example.com');\ndefine('WP_SITEURL','http://example.com');</code></p>\n" }, { "answer_id": 295238, "author": "Vadim", "author_id": 137588, "author_profile": "https://wordpress.stackexchange.com/users/137588", "pm_score": 5, "selected": false, "text": "<p>I found a solution. In <code>wp-config.php</code> add:</p>\n\n<pre><code>define('FORCE_SSL_ADMIN', false);\n</code></pre>\n\n<p>In my situation, I migrated to <em>https</em> from <em>http</em>, and use plugin <em>Rename wp-login.php</em></p>\n\n<p>My <code>wp-config.php</code> contained the lines:</p>\n\n<pre><code>define('WP_SITEURL','https://example.com');\ndefine('WP_HOME','https://example.com');\n</code></pre>\n\n<p>Without the line <code>define('FORCE_SSL_ADMIN', false);</code>, a redirect loop occurs.</p>\n" }, { "answer_id": 306767, "author": "ClickMonster", "author_id": 145745, "author_profile": "https://wordpress.stackexchange.com/users/145745", "pm_score": 1, "selected": false, "text": "<p>I spend hours trying to resolve this, did everything. Eventually notice a log about group write permissions on the wp-login.php file. Looked and the server file permissions were 664 .. changed them to 644 and problem solved.</p>\n" }, { "answer_id": 311802, "author": "MTAdmin", "author_id": 116134, "author_profile": "https://wordpress.stackexchange.com/users/116134", "pm_score": 1, "selected": false, "text": "<p>I had the same issue after moving my site from a production host to localhost for dev testing. Steps that work for me in production didn't work locally. For instance, when using Chrome as my browser, entering </p>\n\n<p><strong><a href=\"http://localhost/wp/wp-admin\" rel=\"nofollow noreferrer\">http://localhost/wp/wp-admin</a></strong> would redirect to </p>\n\n<p><strong><a href=\"http://localhost/wp/wp-login.php?redirect_to=http%3A%2F%2Flocalhost%2Fwp%2Fwpcurrent%2Fwp-admin%2F&amp;reauth=1\" rel=\"nofollow noreferrer\">http://localhost/wp/wp-login.php?redirect_to=http%3A%2F%2Flocalhost%2Fwp%2Fwpcurrent%2Fwp-admin%2F&amp;reauth=1</a></strong>. </p>\n\n<p>Entering my username/password would redirect back to the second link with a new username/password prompt. </p>\n\n<p><strong>Firefox resolution:</strong> add to wp-config.php:</p>\n\n<pre><code>define('WP_HOME','http://your_url.com'); \ndefine('WP_SITEURL','http://your_url.com');\n</code></pre>\n\n<p><strong>Chrome resolution:</strong> Remove the redirect querystring from the login page: e.g. <strong><a href=\"http://localhost/wp/wp-login.php\" rel=\"nofollow noreferrer\">http://localhost/wp/wp-login.php</a></strong> . </p>\n\n<p>Yes, I'm fairly new to Wordpress and I'm not 100% certain of the internal route for logins and redirects after authentication, so much trial and error was involved to find these two solutions. Hopefully they can help someone else. </p>\n" }, { "answer_id": 325933, "author": "nfbne", "author_id": 159267, "author_profile": "https://wordpress.stackexchange.com/users/159267", "pm_score": 3, "selected": false, "text": "<p>I've just solved an issue with this symptom. The 8 key and salt values must be present in the <code>wp-config.php</code> file or admin doesn't work.</p>\n\n<p>I had these in the file, but because of how I dynamically generated <code>wp-config.php</code> the values were appended at the bottom of the file. Any constant definitions (<code>define()</code>) must be placed above the <code>/* That's all, stop editing! Happy blogging. */</code> line.</p>\n\n<p>Wordpress gave no error or logs to indicate it was missing config items. This also stopped <code>'WP_DEBUG', true</code> working. Once I moved all of these higher in the <code>wp-config.php</code> file everything started working.</p>\n" } ]
2017/04/19
[ "https://wordpress.stackexchange.com/questions/264096", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/114978/" ]
I've implemented some meta fields for users like mobile number, address. It can be updated by user as well as admin, I wan't to trigger an email to user and admin stating about the updated field value if any value is updated, irrespective of who updates it.
I found a solution. In `wp-config.php` add: ``` define('FORCE_SSL_ADMIN', false); ``` In my situation, I migrated to *https* from *http*, and use plugin *Rename wp-login.php* My `wp-config.php` contained the lines: ``` define('WP_SITEURL','https://example.com'); define('WP_HOME','https://example.com'); ``` Without the line `define('FORCE_SSL_ADMIN', false);`, a redirect loop occurs.
264,101
<p>I need to get the URL for Custom post type Thumbnail, My custom post type name is slider. I have defined on functions.php:</p> <pre><code>/* Custom post type */ add_action('init', 'slider_register'); function slider_register() { $labels = array( 'name' =&gt; __('Slider', 'post type general name'), 'singular_name' =&gt; __('Slider Item', 'post type singular name'), 'add_new' =&gt; __('Add New', 'portfolio item'), 'add_new_item' =&gt; __('Add New Slider Item'), 'edit_item' =&gt; __('Edit Slider Item'), 'new_item' =&gt; __('New Slider Item'), 'view_item' =&gt; __('View Slider Item'), 'search_items' =&gt; __('Search Slider'), 'not_found' =&gt; __('Nothing found'), 'not_found_in_trash' =&gt; __('Nothing found in Trash'), 'parent_item_colon' =&gt; '' ); $args = array( 'labels' =&gt; $labels, 'public' =&gt; true, 'publicly_queryable' =&gt; true, 'show_ui' =&gt; true, 'query_var' =&gt; true, 'menu_icon' =&gt; get_stylesheet_directory_uri() . '/image/slider.png', 'rewrite' =&gt; true, 'capability_type' =&gt; 'post', 'hierarchical' =&gt; false, 'menu_position' =&gt; null, 'supports' =&gt; array('title','editor','thumbnail') ); register_post_type( 'slider' , $args ); flush_rewrite_rules(); } add_filter("manage_edit-slider_columns", "slider_edit_columns"); function slider_edit_columns($columns){ $columns = array( "cb" =&gt; "&lt;input type='checkbox' /&gt;;", "title" =&gt; "Portfolio Title", ); return $columns; } </code></pre> <p>My code is:</p> <pre><code>&lt;!-- Slider --&gt; &lt;?php $args = array( 'post_type'=&gt; 'post', 'post_status' =&gt; 'publish', 'order' =&gt; 'DESC', 'tax_query' =&gt; array( array( 'post-type' =&gt; array('post', 'slider') ) ) ); $query = new WP_Query($args); if( $query -&gt; have_posts() ) { ?&gt; &lt;div id="slider_area"&gt; &lt;div class="slider"&gt; &lt;a href='#' class="prev"&gt;&lt;i class="fa fa-angle-double-left"&gt;&lt;/i&gt;&lt;/a&gt; &lt;a href='#' class="next"&gt;&lt;i class="fa fa-angle-double-right"&gt;&lt;/i&gt;&lt;/a&gt; &lt;ul class="slider_list"&gt; &lt;?php while($query-&gt;have_posts()) : $query-&gt;the_post(); if(has_post_thumbnail()) { ?&gt; &lt;li&gt; &lt;?php the_post_thumbnail(); ?&gt; &lt;/li&gt; &lt;?php } elseif($thumbnail = get_post_meta($post-&gt;ID, 'image', true)) { ?&gt; &lt;li&gt; &lt;img src="&lt;?php echo $thumbnail; ?&gt;" alt="&lt;?php the_title(); ?&gt;" title="&lt;?php the_title(); ?&gt;" /&gt; &lt;/li&gt; &lt;?php } endwhile; ?&gt; &lt;/ul&gt; &lt;/div&gt; &lt;/div&gt; &lt;?php } ?&gt; </code></pre> <p>What is the problem? Could anyone help me? Thank you for your helps.</p>
[ { "answer_id": 264108, "author": "BlueSuiter", "author_id": 92665, "author_profile": "https://wordpress.stackexchange.com/users/92665", "pm_score": 2, "selected": true, "text": "<p>Please update the while loop with this:\nIt will print the thumbnail url for you</p>\n\n<p>** POST FETCHING ARGUMENTS **</p>\n\n<pre><code>&lt;?php \n/**** Slider Call Function ****/\nfunction callTheSlider()\n{\n $args = array('post_type'=&gt; 'expro_slider', 'post_status' =&gt; 'publish', 'order' =&gt; 'DESC');\n ?&gt;\n &lt;ul&gt;\n &lt;?php\n wp_reset_query();\n $query = new WP_Query($args);\n while($query-&gt;have_posts()) : $query-&gt;the_post();\n if(has_post_thumbnail()) { ?&gt;\n &lt;li&gt;\n &lt;?php the_post_thumbnail(); ?&gt;\n &lt;/li&gt;\n &lt;?php }\n elseif($thumbnail = get_post_meta($post-&gt;ID, 'image', true)) { echo 12323; ?&gt;\n &lt;li&gt;\n &lt;img src=\"&lt;?php echo $thumbnail; ?&gt;\" alt=\"&lt;?php the_title(); ?&gt;\" title=\"&lt;?php the_title(); ?&gt;\" /&gt;\n &lt;/li&gt;\n &lt;?php } endwhile;\n ?&gt;\n &lt;/ul&gt;\n &lt;?php\n}\n?&gt;\n</code></pre>\n" }, { "answer_id": 264110, "author": "Dev", "author_id": 104464, "author_profile": "https://wordpress.stackexchange.com/users/104464", "pm_score": 1, "selected": false, "text": "<p>You should use </p>\n\n<pre><code>'post_type' =&gt; array( 'slider' ),\n</code></pre>\n\n<p>This is what you should use to display content from a post type named slider not:</p>\n\n<pre><code>'post_type' =&gt; 'post',\n</code></pre>\n" }, { "answer_id": 362937, "author": "habib", "author_id": 184431, "author_profile": "https://wordpress.stackexchange.com/users/184431", "pm_score": 0, "selected": false, "text": "<p>The following solution worked for me:</p>\n\n<pre><code>$q=new WP_Query(array('post_type'=&gt;'slider', 'post_status' =&gt; 'publish', 'order' =&gt; 'DESC'));\nif($q-&gt;have_posts()):\nwhile($q-&gt;have_posts()):\n$q-&gt;the_post(); \n echo get_the_post_thumbnail_url(get_the_ID(),'full');\nendwhile;\nendif;\n</code></pre>\n\n<p><a href=\"https://developer.wordpress.org/reference/functions/get_the_post_thumbnail_url/\" rel=\"nofollow noreferrer\">Reference</a></p>\n" } ]
2017/04/19
[ "https://wordpress.stackexchange.com/questions/264101", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/117954/" ]
I need to get the URL for Custom post type Thumbnail, My custom post type name is slider. I have defined on functions.php: ``` /* Custom post type */ add_action('init', 'slider_register'); function slider_register() { $labels = array( 'name' => __('Slider', 'post type general name'), 'singular_name' => __('Slider Item', 'post type singular name'), 'add_new' => __('Add New', 'portfolio item'), 'add_new_item' => __('Add New Slider Item'), 'edit_item' => __('Edit Slider Item'), 'new_item' => __('New Slider Item'), 'view_item' => __('View Slider Item'), 'search_items' => __('Search Slider'), 'not_found' => __('Nothing found'), 'not_found_in_trash' => __('Nothing found in Trash'), 'parent_item_colon' => '' ); $args = array( 'labels' => $labels, 'public' => true, 'publicly_queryable' => true, 'show_ui' => true, 'query_var' => true, 'menu_icon' => get_stylesheet_directory_uri() . '/image/slider.png', 'rewrite' => true, 'capability_type' => 'post', 'hierarchical' => false, 'menu_position' => null, 'supports' => array('title','editor','thumbnail') ); register_post_type( 'slider' , $args ); flush_rewrite_rules(); } add_filter("manage_edit-slider_columns", "slider_edit_columns"); function slider_edit_columns($columns){ $columns = array( "cb" => "<input type='checkbox' />;", "title" => "Portfolio Title", ); return $columns; } ``` My code is: ``` <!-- Slider --> <?php $args = array( 'post_type'=> 'post', 'post_status' => 'publish', 'order' => 'DESC', 'tax_query' => array( array( 'post-type' => array('post', 'slider') ) ) ); $query = new WP_Query($args); if( $query -> have_posts() ) { ?> <div id="slider_area"> <div class="slider"> <a href='#' class="prev"><i class="fa fa-angle-double-left"></i></a> <a href='#' class="next"><i class="fa fa-angle-double-right"></i></a> <ul class="slider_list"> <?php while($query->have_posts()) : $query->the_post(); if(has_post_thumbnail()) { ?> <li> <?php the_post_thumbnail(); ?> </li> <?php } elseif($thumbnail = get_post_meta($post->ID, 'image', true)) { ?> <li> <img src="<?php echo $thumbnail; ?>" alt="<?php the_title(); ?>" title="<?php the_title(); ?>" /> </li> <?php } endwhile; ?> </ul> </div> </div> <?php } ?> ``` What is the problem? Could anyone help me? Thank you for your helps.
Please update the while loop with this: It will print the thumbnail url for you \*\* POST FETCHING ARGUMENTS \*\* ``` <?php /**** Slider Call Function ****/ function callTheSlider() { $args = array('post_type'=> 'expro_slider', 'post_status' => 'publish', 'order' => 'DESC'); ?> <ul> <?php wp_reset_query(); $query = new WP_Query($args); while($query->have_posts()) : $query->the_post(); if(has_post_thumbnail()) { ?> <li> <?php the_post_thumbnail(); ?> </li> <?php } elseif($thumbnail = get_post_meta($post->ID, 'image', true)) { echo 12323; ?> <li> <img src="<?php echo $thumbnail; ?>" alt="<?php the_title(); ?>" title="<?php the_title(); ?>" /> </li> <?php } endwhile; ?> </ul> <?php } ?> ```
264,107
<p>Generally,</p> <p>We put <code>&lt;?php get_search_form(); ?&gt;</code> in the header where we desire the search form, and then later we put the custom code for HTML in searchform.php.</p> <p>This is the whole <a href="http://html.ankishpost.com/" rel="nofollow noreferrer">HTML</a> from where I am trying to create an HTML template.</p> <p>This is the Portion of an HTML</p> <pre><code>&lt;li&gt;&lt;input class="search" type="search" placeholder="Search"&gt;&lt;/li&gt; </code></pre> <p>that was supposed to be converted into an working wordpress search.</p> <p>However, I put this whole form modified a little bit with my CSS's classes →</p> <pre><code> &lt;form action="/" method="get"&gt; &lt;li&gt; &lt;input class="search" type="search" placeholder="Search" type="text" name="s" id="search" value="&lt;?php the_search_query(); ?&gt;"&gt; &lt;/li&gt; &lt;/form&gt; </code></pre> <p><strong>THE PROBLEM →</strong> Misleading search URL. Suppose my search string is "<strong>ok</strong>"</p> <p>The search URL anticipated to be generated is →</p> <p><a href="http://codepen.trafficopedia.com/site01/?s=ok" rel="nofollow noreferrer">right</a> but it generates →</p> <p><a href="http://codepen.trafficopedia.com/?s=ok" rel="nofollow noreferrer">wrong</a>.</p> <p><a href="http://codepen.trafficopedia.com/site01/" rel="nofollow noreferrer">Live WP Site here.</a></p>
[ { "answer_id": 264155, "author": "ciaika", "author_id": 48497, "author_profile": "https://wordpress.stackexchange.com/users/48497", "pm_score": 0, "selected": false, "text": "<p>Try this form based on your code:</p>\n\n<pre>&lt;form action=\"&lt;?php echo esc_url(home_url()); ?>\" method=\"get\">\n &lt;li>\n &lt;input class=\"search\" type=\"text\" name=\"s\" id=\"s\" \n placeholder=\"Search\" value=\"&lt;?php the_search_query(); ?>\">\n &lt;/li>\n&lt;/form></pre> \n" }, { "answer_id": 264301, "author": "ciaika", "author_id": 48497, "author_profile": "https://wordpress.stackexchange.com/users/48497", "pm_score": 1, "selected": false, "text": "<p>Below you can find a template for displaying Search Results pages. Add the code to your <strong>search.php</strong> file. If you have installed the <strong>WP-PageNavi</strong> plugin then you'll see the pagination if the search result has more than 10 items.</p>\n\n<p><pre>&lt;?php\n/**\n * The template for displaying Search Results pages.\n*/\nget_header();\n?></p>\n\n<code>&lt;h2&gt;&lt;?php printf( __( 'Search Results for: %s', 'themedomain' ), '&lt;strong&gt;\"' . get_search_query() . '\"&lt;/strong&gt;' ); ?&gt;&lt;/h2&gt;\n\n&lt;div class=\"posts\"&gt;\n &lt;?php\n global $paged;\n $s = $_GET['s'];\n $post_types = array('post', 'page');\n $args=array(\n 'post_type' =&gt; $post_types,\n 'post_status' =&gt; 'publish',\n 's' =&gt; $s,\n 'orderby' =&gt; 'date',\n 'order' =&gt; 'desc',\n 'posts_per_page' =&gt; 10,\n 'paged' =&gt; $paged\n );\n\n $wp_query = new WP_Query($args);\n if ($wp_query-&gt;have_posts()) : while($wp_query-&gt;have_posts()) : $wp_query-&gt;the_post();\n ?&gt;\n &lt;!-- post-box --&gt;\n &lt;article class=\"post-box\"&gt;\n &lt;div class=\"meta\"&gt;\n &lt;h3&gt;&lt;a href=\"&lt;?php the_permalink(); ?&gt;\"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;&lt;/h3&gt;\n &lt;p&gt;&lt;?php _e('Posted by','themedomain');?&gt; &lt;?php if (!get_the_author_meta('first_name') &amp;&amp; !get_the_author_meta('last_name')) { the_author_posts_link(); } else { echo '&lt;a href=\"'.get_author_posts_url(get_the_author_meta('ID')).'\"&gt;'.get_the_author_meta('first_name').' '.get_the_author_meta('last_name').'&lt;/a&gt;'; } ?&gt; &lt;?php _e('&amp;middot; on','themedomain');?&gt; &lt;?php echo get_the_time('F d, Y'); ?&gt; &lt;?php _e('&amp;middot; in','themedomain');?&gt; &lt;?php the_category(', ') ?&gt; &lt;?php _e('&amp;middot; with','themedomain');?&gt; &lt;?php comments_popup_link(__('0 Comments', 'themedomain'),__('1 Comment', 'themedomain'), __('% Comments', 'themedomain')); ?&gt;&lt;/p&gt;\n &lt;/div&gt;\n &lt;?php the_excerpt(); ?&gt;\n &lt;p&gt;&lt;a href=\"&lt;?php the_permalink(); ?&gt;\"&gt;&lt;?php _e('Continue Reading &amp;rarr;','themedomain'); ?&gt;&lt;/a&gt;&lt;/p&gt;\n &lt;/article&gt;\n &lt;?php \n endwhile;\n endif;\n ?&gt;\n&lt;/div&gt;\n&lt;!-- paging --&gt;\n&lt;div class=\"paging\"&gt;\n &lt;ul&gt;\n &lt;?php\n if(function_exists('wp_pagenavi')) { wp_pagenavi(); } \n ?&gt;\n &lt;/ul&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p>&lt;?php get_footer(); ?></p>\n" } ]
2017/04/19
[ "https://wordpress.stackexchange.com/questions/264107", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/105791/" ]
Generally, We put `<?php get_search_form(); ?>` in the header where we desire the search form, and then later we put the custom code for HTML in searchform.php. This is the whole [HTML](http://html.ankishpost.com/) from where I am trying to create an HTML template. This is the Portion of an HTML ``` <li><input class="search" type="search" placeholder="Search"></li> ``` that was supposed to be converted into an working wordpress search. However, I put this whole form modified a little bit with my CSS's classes → ``` <form action="/" method="get"> <li> <input class="search" type="search" placeholder="Search" type="text" name="s" id="search" value="<?php the_search_query(); ?>"> </li> </form> ``` **THE PROBLEM →** Misleading search URL. Suppose my search string is "**ok**" The search URL anticipated to be generated is → [right](http://codepen.trafficopedia.com/site01/?s=ok) but it generates → [wrong](http://codepen.trafficopedia.com/?s=ok). [Live WP Site here.](http://codepen.trafficopedia.com/site01/)
Below you can find a template for displaying Search Results pages. Add the code to your **search.php** file. If you have installed the **WP-PageNavi** plugin then you'll see the pagination if the search result has more than 10 items. ``` <?php /** * The template for displaying Search Results pages. */ get_header(); ?> ``` `<h2><?php printf( __( 'Search Results for: %s', 'themedomain' ), '<strong>"' . get_search_query() . '"</strong>' ); ?></h2> <div class="posts"> <?php global $paged; $s = $_GET['s']; $post_types = array('post', 'page'); $args=array( 'post_type' => $post_types, 'post_status' => 'publish', 's' => $s, 'orderby' => 'date', 'order' => 'desc', 'posts_per_page' => 10, 'paged' => $paged ); $wp_query = new WP_Query($args); if ($wp_query->have_posts()) : while($wp_query->have_posts()) : $wp_query->the_post(); ?> <!-- post-box --> <article class="post-box"> <div class="meta"> <h3><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3> <p><?php _e('Posted by','themedomain');?> <?php if (!get_the_author_meta('first_name') && !get_the_author_meta('last_name')) { the_author_posts_link(); } else { echo '<a href="'.get_author_posts_url(get_the_author_meta('ID')).'">'.get_the_author_meta('first_name').' '.get_the_author_meta('last_name').'</a>'; } ?> <?php _e('&middot; on','themedomain');?> <?php echo get_the_time('F d, Y'); ?> <?php _e('&middot; in','themedomain');?> <?php the_category(', ') ?> <?php _e('&middot; with','themedomain');?> <?php comments_popup_link(__('0 Comments', 'themedomain'),__('1 Comment', 'themedomain'), __('% Comments', 'themedomain')); ?></p> </div> <?php the_excerpt(); ?> <p><a href="<?php the_permalink(); ?>"><?php _e('Continue Reading &rarr;','themedomain'); ?></a></p> </article> <?php endwhile; endif; ?> </div> <!-- paging --> <div class="paging"> <ul> <?php if(function_exists('wp_pagenavi')) { wp_pagenavi(); } ?> </ul> </div>` <?php get\_footer(); ?>
264,115
<p>I'm using the following JS code to open a wp.media window to allow users to select images and videos for a gallery. Everything is working as expected, but I'm unable to restrict the window to show images and videos only, it's showing everything.</p> <p>Any ideas on what might be wrong? </p> <p>Thanks in advance</p> <p><strong>JS:</strong></p> <pre><code>$( '#add_item' ).on( 'click', function( e ) { var $el = $( this ); e.preventDefault(); // If the media frame already exists, reopen it. if ( items_frame ) { items_frame.open(); return; } // Create the media frame. items_frame = wp.media.frames.items = wp.media({ title: 'Add to Gallery', button: { text: 'Select' }, states: [ new wp.media.controller.Library({ title: 'Add to Gallery', filterable: 'all', type: ['image', 'video'], multiple: true }) ] }); // Finally, open the modal. items_frame.open(); }); </code></pre>
[ { "answer_id": 268597, "author": "user433351", "author_id": 83792, "author_profile": "https://wordpress.stackexchange.com/users/83792", "pm_score": 5, "selected": true, "text": "<p>It's been a while since this question was asked, but on the off chance that you are still looking for a solution:</p>\n\n<pre><code>items_frame = wp.media.frames.items = wp.media({\n title: 'Add to Gallery',\n button: {\n text: 'Select'\n },\n library: {\n type: [ 'video', 'image' ]\n },\n});\n</code></pre>\n" }, { "answer_id": 303357, "author": "Sark Peha", "author_id": 143469, "author_profile": "https://wordpress.stackexchange.com/users/143469", "pm_score": 1, "selected": false, "text": "<p>With a bit more searching I found that you can specify the exact file type within the <strong>library</strong> property. This may come in handy when creating a plugin where only certain files are permitted.</p>\n\n<pre><code>var frame = wp.media({\n title: 'Insert movie',\n library: {type: 'video/MP4'},\n multiple: false,\n button: {text: 'Insert'}\n });\n</code></pre>\n\n<p>Unfortunately, there does not seem to be a list anywhere that specifies which values work for a particular extension.</p>\n" }, { "answer_id": 406077, "author": "Deepak Anand", "author_id": 222518, "author_profile": "https://wordpress.stackexchange.com/users/222518", "pm_score": 1, "selected": false, "text": "<pre><code>$( '#add_item' ).on( 'click', function( e ) {\n var $el = $( this );\n\n e.preventDefault();\n\n // If the media frame already exists, reopen it.\n if ( items_frame ) {\n items_frame.open();\n return;\n }\n\n // Create the media frame.\n items_frame = wp.media.frames.items = wp.media({\n title: 'Add to Gallery',\n button: {\n text: 'Select'\n },\n library: {\n type: [ 'video', 'image' ]\n },\n });\n\n // Finally, open the modal.\n items_frame.open();\n\n});\n</code></pre>\n<p><strong>Use the above code and check the line number 18,19 and 20</strong></p>\n<p>I checked some other comments too for the different file type. Try the below list of mime types:</p>\n<p><strong>Extension MIME Type</strong></p>\n<pre><code>.doc application/msword\n.dot application/msword\n\n.docx application/vnd.openxmlformats-officedocument.wordprocessingml.document\n.dotx application/vnd.openxmlformats-officedocument.wordprocessingml.template\n.docm application/vnd.ms-word.document.macroEnabled.12\n.dotm application/vnd.ms-word.template.macroEnabled.12\n\n.xls application/vnd.ms-excel\n.xlt application/vnd.ms-excel\n.xla application/vnd.ms-excel\n\n.xlsx application/vnd.openxmlformats-officedocument.spreadsheetml.sheet\n.xltx application/vnd.openxmlformats-officedocument.spreadsheetml.template\n.xlsm application/vnd.ms-excel.sheet.macroEnabled.12\n.xltm application/vnd.ms-excel.template.macroEnabled.12\n.xlam application/vnd.ms-excel.addin.macroEnabled.12\n.xlsb application/vnd.ms-excel.sheet.binary.macroEnabled.12\n\n.ppt application/vnd.ms-powerpoint\n.pot application/vnd.ms-powerpoint\n.pps application/vnd.ms-powerpoint\n.ppa application/vnd.ms-powerpoint\n\n.pptx application/vnd.openxmlformats-officedocument.presentationml.presentation\n.potx application/vnd.openxmlformats-officedocument.presentationml.template\n.ppsx application/vnd.openxmlformats-officedocument.presentationml.slideshow\n.ppam application/vnd.ms-powerpoint.addin.macroEnabled.12\n.pptm application/vnd.ms-powerpoint.presentation.macroEnabled.12\n.potm application/vnd.ms-powerpoint.template.macroEnabled.12\n.ppsm application/vnd.ms-powerpoint.slideshow.macroEnabled.12\n\n.mdb application/vnd.ms-access\n</code></pre>\n" }, { "answer_id": 406211, "author": "Unaib Amir", "author_id": 124531, "author_profile": "https://wordpress.stackexchange.com/users/124531", "pm_score": 0, "selected": false, "text": "<p>I am pretty much late to this answer and i was stuck but this how I was able to get it right after spending hours. Hopefully this will help anyone who is reading. Basically just modify the media picker's input attribute on the go.</p>\n<pre><code>items_frame.on('uploader:ready', function () {\n jQuery('.moxie-shim-html5 input[type=&quot;file&quot;]')\n .attr({\n tabIndex: '-1',\n 'multiple': false,\n 'accept': 'application/pdf, application/epub+zip', // this where to add your mime type\n 'aria-hidden': 'true'\n });\n});\n</code></pre>\n" } ]
2017/04/19
[ "https://wordpress.stackexchange.com/questions/264115", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/33049/" ]
I'm using the following JS code to open a wp.media window to allow users to select images and videos for a gallery. Everything is working as expected, but I'm unable to restrict the window to show images and videos only, it's showing everything. Any ideas on what might be wrong? Thanks in advance **JS:** ``` $( '#add_item' ).on( 'click', function( e ) { var $el = $( this ); e.preventDefault(); // If the media frame already exists, reopen it. if ( items_frame ) { items_frame.open(); return; } // Create the media frame. items_frame = wp.media.frames.items = wp.media({ title: 'Add to Gallery', button: { text: 'Select' }, states: [ new wp.media.controller.Library({ title: 'Add to Gallery', filterable: 'all', type: ['image', 'video'], multiple: true }) ] }); // Finally, open the modal. items_frame.open(); }); ```
It's been a while since this question was asked, but on the off chance that you are still looking for a solution: ``` items_frame = wp.media.frames.items = wp.media({ title: 'Add to Gallery', button: { text: 'Select' }, library: { type: [ 'video', 'image' ] }, }); ```
264,156
<p>I am using the following code to show the expiration date of my coupon;</p> <pre><code> &lt;?php _e('Expiration Date:','wpestate'); echo esc_html($expiration_date); ?&gt; </code></pre> <p>But, it is showing in following unreadable format; </p> <blockquote> <p>Expiration Date:1491955200</p> </blockquote> <p>Therefore how to convert it to readable format like;</p> <blockquote> <p>Expiration date : 2017-04-30</p> </blockquote>
[ { "answer_id": 268597, "author": "user433351", "author_id": 83792, "author_profile": "https://wordpress.stackexchange.com/users/83792", "pm_score": 5, "selected": true, "text": "<p>It's been a while since this question was asked, but on the off chance that you are still looking for a solution:</p>\n\n<pre><code>items_frame = wp.media.frames.items = wp.media({\n title: 'Add to Gallery',\n button: {\n text: 'Select'\n },\n library: {\n type: [ 'video', 'image' ]\n },\n});\n</code></pre>\n" }, { "answer_id": 303357, "author": "Sark Peha", "author_id": 143469, "author_profile": "https://wordpress.stackexchange.com/users/143469", "pm_score": 1, "selected": false, "text": "<p>With a bit more searching I found that you can specify the exact file type within the <strong>library</strong> property. This may come in handy when creating a plugin where only certain files are permitted.</p>\n\n<pre><code>var frame = wp.media({\n title: 'Insert movie',\n library: {type: 'video/MP4'},\n multiple: false,\n button: {text: 'Insert'}\n });\n</code></pre>\n\n<p>Unfortunately, there does not seem to be a list anywhere that specifies which values work for a particular extension.</p>\n" }, { "answer_id": 406077, "author": "Deepak Anand", "author_id": 222518, "author_profile": "https://wordpress.stackexchange.com/users/222518", "pm_score": 1, "selected": false, "text": "<pre><code>$( '#add_item' ).on( 'click', function( e ) {\n var $el = $( this );\n\n e.preventDefault();\n\n // If the media frame already exists, reopen it.\n if ( items_frame ) {\n items_frame.open();\n return;\n }\n\n // Create the media frame.\n items_frame = wp.media.frames.items = wp.media({\n title: 'Add to Gallery',\n button: {\n text: 'Select'\n },\n library: {\n type: [ 'video', 'image' ]\n },\n });\n\n // Finally, open the modal.\n items_frame.open();\n\n});\n</code></pre>\n<p><strong>Use the above code and check the line number 18,19 and 20</strong></p>\n<p>I checked some other comments too for the different file type. Try the below list of mime types:</p>\n<p><strong>Extension MIME Type</strong></p>\n<pre><code>.doc application/msword\n.dot application/msword\n\n.docx application/vnd.openxmlformats-officedocument.wordprocessingml.document\n.dotx application/vnd.openxmlformats-officedocument.wordprocessingml.template\n.docm application/vnd.ms-word.document.macroEnabled.12\n.dotm application/vnd.ms-word.template.macroEnabled.12\n\n.xls application/vnd.ms-excel\n.xlt application/vnd.ms-excel\n.xla application/vnd.ms-excel\n\n.xlsx application/vnd.openxmlformats-officedocument.spreadsheetml.sheet\n.xltx application/vnd.openxmlformats-officedocument.spreadsheetml.template\n.xlsm application/vnd.ms-excel.sheet.macroEnabled.12\n.xltm application/vnd.ms-excel.template.macroEnabled.12\n.xlam application/vnd.ms-excel.addin.macroEnabled.12\n.xlsb application/vnd.ms-excel.sheet.binary.macroEnabled.12\n\n.ppt application/vnd.ms-powerpoint\n.pot application/vnd.ms-powerpoint\n.pps application/vnd.ms-powerpoint\n.ppa application/vnd.ms-powerpoint\n\n.pptx application/vnd.openxmlformats-officedocument.presentationml.presentation\n.potx application/vnd.openxmlformats-officedocument.presentationml.template\n.ppsx application/vnd.openxmlformats-officedocument.presentationml.slideshow\n.ppam application/vnd.ms-powerpoint.addin.macroEnabled.12\n.pptm application/vnd.ms-powerpoint.presentation.macroEnabled.12\n.potm application/vnd.ms-powerpoint.template.macroEnabled.12\n.ppsm application/vnd.ms-powerpoint.slideshow.macroEnabled.12\n\n.mdb application/vnd.ms-access\n</code></pre>\n" }, { "answer_id": 406211, "author": "Unaib Amir", "author_id": 124531, "author_profile": "https://wordpress.stackexchange.com/users/124531", "pm_score": 0, "selected": false, "text": "<p>I am pretty much late to this answer and i was stuck but this how I was able to get it right after spending hours. Hopefully this will help anyone who is reading. Basically just modify the media picker's input attribute on the go.</p>\n<pre><code>items_frame.on('uploader:ready', function () {\n jQuery('.moxie-shim-html5 input[type=&quot;file&quot;]')\n .attr({\n tabIndex: '-1',\n 'multiple': false,\n 'accept': 'application/pdf, application/epub+zip', // this where to add your mime type\n 'aria-hidden': 'true'\n });\n});\n</code></pre>\n" } ]
2017/04/19
[ "https://wordpress.stackexchange.com/questions/264156", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/93692/" ]
I am using the following code to show the expiration date of my coupon; ``` <?php _e('Expiration Date:','wpestate'); echo esc_html($expiration_date); ?> ``` But, it is showing in following unreadable format; > > Expiration Date:1491955200 > > > Therefore how to convert it to readable format like; > > Expiration date : 2017-04-30 > > >
It's been a while since this question was asked, but on the off chance that you are still looking for a solution: ``` items_frame = wp.media.frames.items = wp.media({ title: 'Add to Gallery', button: { text: 'Select' }, library: { type: [ 'video', 'image' ] }, }); ```
264,179
<p>I used the XML Sitemaps in the All in One SEO Pack plugin to generate my sitemap.</p> <p>When I type in the site address/sitemap.xml (<a href="http://flysuas.ie/sitemap.xml" rel="nofollow noreferrer">http://flysuas.ie/sitemap.xml</a>) the sitemap appears.</p> <p>I want to get rid of some links that don't make sense but when I look for sitemap.xml on the machine it is not present.</p> <pre><code>sudo find -name sitemap\* </code></pre> <p>Does anyone know where the sitemap is and how it is being assembled to appear as if it is in the htdocs folder?</p>
[ { "answer_id": 264180, "author": "Oleg Butuzov", "author_id": 14536, "author_profile": "https://wordpress.stackexchange.com/users/14536", "pm_score": 1, "selected": false, "text": "<p>hm.. isn't you suppose to run find command in other way?</p>\n\n<pre><code>sudo find / -iname sitemap*\n</code></pre>\n\n<p>note for / &lt;- that stands for root directory.</p>\n\n<p>P.S.\nIsn't there easier just to check web root of your website for this file?</p>\n" }, { "answer_id": 264183, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 3, "selected": true, "text": "<p>The sitemap added by most of the plugins (such as Google sitemaps or YOAST SEO pack) is a virtual file added to your websites by the plugin. This file doesn't physically exist, therefore modifying it is not an option for you.</p>\n\n<p>There might be 2 things that you can do about it,</p>\n\n<p>Either find the <code>php</code> file that is generating the XML and modify it, or maybe add a filter if it's supported. In your case, the file is located in <code>/plugins/all-in-one-seo-pack/inc/sitemap-xsl.php</code>.</p>\n\n<p>OR</p>\n\n<p>Find the option to demote your URL from the XML list. This option may not exist on every plugin.</p>\n" } ]
2017/04/19
[ "https://wordpress.stackexchange.com/questions/264179", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/71456/" ]
I used the XML Sitemaps in the All in One SEO Pack plugin to generate my sitemap. When I type in the site address/sitemap.xml (<http://flysuas.ie/sitemap.xml>) the sitemap appears. I want to get rid of some links that don't make sense but when I look for sitemap.xml on the machine it is not present. ``` sudo find -name sitemap\* ``` Does anyone know where the sitemap is and how it is being assembled to appear as if it is in the htdocs folder?
The sitemap added by most of the plugins (such as Google sitemaps or YOAST SEO pack) is a virtual file added to your websites by the plugin. This file doesn't physically exist, therefore modifying it is not an option for you. There might be 2 things that you can do about it, Either find the `php` file that is generating the XML and modify it, or maybe add a filter if it's supported. In your case, the file is located in `/plugins/all-in-one-seo-pack/inc/sitemap-xsl.php`. OR Find the option to demote your URL from the XML list. This option may not exist on every plugin.
264,186
<p>I have loop and I want to get the amount of posts on a current page. So I try:</p> <pre><code>&lt;?php $post_number = $wp_query-&gt;post_count; ?&gt; &lt;?php echo($post_number) ; ?&gt; &lt;?php while ( have_posts() ) : the_post();?&gt; &lt;?php get_template_part( 'post', get_post_format() );?&gt; &lt;?php endwhile; ?&gt; </code></pre> <p>but it doesn't work. I can't see result. So how can I get amount of posts?</p>
[ { "answer_id": 264180, "author": "Oleg Butuzov", "author_id": 14536, "author_profile": "https://wordpress.stackexchange.com/users/14536", "pm_score": 1, "selected": false, "text": "<p>hm.. isn't you suppose to run find command in other way?</p>\n\n<pre><code>sudo find / -iname sitemap*\n</code></pre>\n\n<p>note for / &lt;- that stands for root directory.</p>\n\n<p>P.S.\nIsn't there easier just to check web root of your website for this file?</p>\n" }, { "answer_id": 264183, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 3, "selected": true, "text": "<p>The sitemap added by most of the plugins (such as Google sitemaps or YOAST SEO pack) is a virtual file added to your websites by the plugin. This file doesn't physically exist, therefore modifying it is not an option for you.</p>\n\n<p>There might be 2 things that you can do about it,</p>\n\n<p>Either find the <code>php</code> file that is generating the XML and modify it, or maybe add a filter if it's supported. In your case, the file is located in <code>/plugins/all-in-one-seo-pack/inc/sitemap-xsl.php</code>.</p>\n\n<p>OR</p>\n\n<p>Find the option to demote your URL from the XML list. This option may not exist on every plugin.</p>\n" } ]
2017/04/19
[ "https://wordpress.stackexchange.com/questions/264186", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/116307/" ]
I have loop and I want to get the amount of posts on a current page. So I try: ``` <?php $post_number = $wp_query->post_count; ?> <?php echo($post_number) ; ?> <?php while ( have_posts() ) : the_post();?> <?php get_template_part( 'post', get_post_format() );?> <?php endwhile; ?> ``` but it doesn't work. I can't see result. So how can I get amount of posts?
The sitemap added by most of the plugins (such as Google sitemaps or YOAST SEO pack) is a virtual file added to your websites by the plugin. This file doesn't physically exist, therefore modifying it is not an option for you. There might be 2 things that you can do about it, Either find the `php` file that is generating the XML and modify it, or maybe add a filter if it's supported. In your case, the file is located in `/plugins/all-in-one-seo-pack/inc/sitemap-xsl.php`. OR Find the option to demote your URL from the XML list. This option may not exist on every plugin.
264,233
<p>I'm developing a website with 3 different post types, and 4 different taxonomies to save the posts under.</p> <p>The default post type and categories are unused in this template, and since many of authors are not very familiar with WordPress and we can't always control them, i wish to delete, change or at least hide the categories and default post from them, so they have to post it under a custom type.</p> <p>For example, someone creates a new post under 'Breaking news' type, and assigns it to <code>News</code> Taxonomy, this post won't be categorized under any category (Uncategorized). </p> <p>If he publishes this as a normal post type,it won't be shown anywhere in the website.</p> <p>Is it possible to work around this?</p>
[ { "answer_id": 264234, "author": "Thijs", "author_id": 107050, "author_profile": "https://wordpress.stackexchange.com/users/107050", "pm_score": 4, "selected": true, "text": "<p>Yes this is possible with a very simple solution. Add this code snippet to your theme's funtion.php</p>\n\n<pre><code>add_action('admin_menu','remove_default_post_type');\n\nfunction remove_default_post_type() {\n remove_menu_page('edit.php');\n}\n</code></pre>\n\n<p>More info: <a href=\"https://www.techjunkie.com/remove-default-post-type-from-admin-menu-wordpress/\" rel=\"noreferrer\">https://www.techjunkie.com/remove-default-post-type-from-admin-menu-wordpress/</a> or <a href=\"https://codex.wordpress.org/Function_Reference/remove_menu_page\" rel=\"noreferrer\">https://codex.wordpress.org/Function_Reference/remove_menu_page</a></p>\n" }, { "answer_id": 264371, "author": "Vinod Dalvi", "author_id": 14347, "author_profile": "https://wordpress.stackexchange.com/users/14347", "pm_score": 2, "selected": false, "text": "<p>You can delete the default post type and category menu using below code.</p>\n\n<pre><code>add_action('admin_menu','remove_post_cat_menu');\n\nfunction remove_post_cat_menu() {\n remove_submenu_page( 'edit.php', 'post-new.php' );\n remove_submenu_page( 'edit.php', 'edit-tags.php?taxonomy=category' ); // Removes default category menu\n}\n</code></pre>\n" }, { "answer_id": 264377, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 1, "selected": false, "text": "<p>Based on @Thijs answer, i managed to do this in 3 parts:</p>\n\n<p>First, by removing the edit posts menu from the admin menu.</p>\n\n<pre><code>add_action('admin_menu','remove_default_post_type');\nfunction remove_default_post_type() {\n remove_menu_page('edit.php');\n}\n</code></pre>\n\n<p>Then, by removing the <code>new-post</code> button from admin bar, and changing the default link.</p>\n\n<pre><code>add_action('admin_menu','remove_default_post_type');\nfunction remove_default_post_type() {\n remove_menu_page('edit.php');\n $default_link = $wp_admin_bar-&gt;get_node('new-content');\n $default_link-&gt;href = '#';\n $wp_admin_bar-&gt;add_node($default_link);\n}\n</code></pre>\n\n<p>Now, it's time to completely wipe categories from custom post types, but only assigning tags to taxonomies, while creating custom taxonomies.</p>\n\n<p><code>'taxonomies' =&gt; array('post_tag' )</code></p>\n\n<p>This will remove any trace of default post type and categories. Since the tag is assigned to taxonomies, we can still access tags from custom post type's menu. However the direct link will still be accessible, which can easily be blocked or redirected using user roles hook.</p>\n" } ]
2017/04/20
[ "https://wordpress.stackexchange.com/questions/264233", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/94498/" ]
I'm developing a website with 3 different post types, and 4 different taxonomies to save the posts under. The default post type and categories are unused in this template, and since many of authors are not very familiar with WordPress and we can't always control them, i wish to delete, change or at least hide the categories and default post from them, so they have to post it under a custom type. For example, someone creates a new post under 'Breaking news' type, and assigns it to `News` Taxonomy, this post won't be categorized under any category (Uncategorized). If he publishes this as a normal post type,it won't be shown anywhere in the website. Is it possible to work around this?
Yes this is possible with a very simple solution. Add this code snippet to your theme's funtion.php ``` add_action('admin_menu','remove_default_post_type'); function remove_default_post_type() { remove_menu_page('edit.php'); } ``` More info: <https://www.techjunkie.com/remove-default-post-type-from-admin-menu-wordpress/> or <https://codex.wordpress.org/Function_Reference/remove_menu_page>
264,235
<p>I am new to wordpress and I am creating a theme for a local company as my final project towards my college degree. They wish to use this theme as a main theme for all their wp sites and that any change in design shall be taken care of by child themes. </p> <p>they requested that some subpages should have a sidebar menu and some others to have another sidebar menu. </p> <p>I have made a metabox with a dropdownlist in the page editor so that I can select a menu for each page. The dropdownlist displays all registered menus that are hardcoded inside the theme but not the ones created inside the admin menu editor. </p> <pre><code>$menus = get_registered_nav_menus(); echo '&lt;select&gt;'; foreach($menus as $menu =&gt; $value){ echo '&lt;option value="'.$menu.'"&gt;' . $value .'&lt;/option&gt;'; } echo '&lt;/select&gt;'; </code></pre> <p>How can I also get the menus that are created with the admin menu editor?</p>
[ { "answer_id": 264260, "author": "CompactCode", "author_id": 118063, "author_profile": "https://wordpress.stackexchange.com/users/118063", "pm_score": 3, "selected": true, "text": "<p>Maybe this helps :</p>\n\n<pre><code>function get_all_wordpress_menus(){\n return get_terms( 'nav_menu', array( 'hide_empty' =&gt; true ) ); \n}\n</code></pre>\n\n<p>get_registered_nav_menus only gets the theme's menu's and not the clients menu's.</p>\n\n<p>Source : <a href=\"https://paulund.co.uk/get-all-wordpress-navigation-menus\" rel=\"nofollow noreferrer\">Paulund</a>\nThis returns all ID's. To get the name you can use :</p>\n\n<pre><code>&lt;?php $nav_menu = wp_get_nav_menu_object(ID comes here); echo $nav_menu-&gt;name; ?&gt;\n</code></pre>\n\n<p>All menu objects have the next settings :</p>\n\n<pre><code>Object (\nterm_id =&gt; 7\nname =&gt; Test menu\nslug =&gt; Test menu\nterm_group =&gt; 0\nterm_taxonomy_id =&gt; 3\ntaxonomy =&gt; nav_menu\ndescription =&gt;\nparent =&gt; 0\ncount =&gt; 6\n)\n</code></pre>\n\n<p>Source : <a href=\"https://stanhub.com/how-to-display-wordpress-custom-menu-title/\" rel=\"nofollow noreferrer\">Stanhub Display wordpress menu title</a></p>\n" }, { "answer_id": 410845, "author": "mihdan", "author_id": 105269, "author_profile": "https://wordpress.stackexchange.com/users/105269", "pm_score": 1, "selected": false, "text": "<p>To get a list of all menus created through the WordPress menu editor, use the <code>wp_get_nav_menus</code> function.</p>\n<pre class=\"lang-php prettyprint-override\"><code>&lt;?php\nvar_dump( wp_get_nav_menus() );\n</code></pre>\n" } ]
2017/04/20
[ "https://wordpress.stackexchange.com/questions/264235", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/118049/" ]
I am new to wordpress and I am creating a theme for a local company as my final project towards my college degree. They wish to use this theme as a main theme for all their wp sites and that any change in design shall be taken care of by child themes. they requested that some subpages should have a sidebar menu and some others to have another sidebar menu. I have made a metabox with a dropdownlist in the page editor so that I can select a menu for each page. The dropdownlist displays all registered menus that are hardcoded inside the theme but not the ones created inside the admin menu editor. ``` $menus = get_registered_nav_menus(); echo '<select>'; foreach($menus as $menu => $value){ echo '<option value="'.$menu.'">' . $value .'</option>'; } echo '</select>'; ``` How can I also get the menus that are created with the admin menu editor?
Maybe this helps : ``` function get_all_wordpress_menus(){ return get_terms( 'nav_menu', array( 'hide_empty' => true ) ); } ``` get\_registered\_nav\_menus only gets the theme's menu's and not the clients menu's. Source : [Paulund](https://paulund.co.uk/get-all-wordpress-navigation-menus) This returns all ID's. To get the name you can use : ``` <?php $nav_menu = wp_get_nav_menu_object(ID comes here); echo $nav_menu->name; ?> ``` All menu objects have the next settings : ``` Object ( term_id => 7 name => Test menu slug => Test menu term_group => 0 term_taxonomy_id => 3 taxonomy => nav_menu description => parent => 0 count => 6 ) ``` Source : [Stanhub Display wordpress menu title](https://stanhub.com/how-to-display-wordpress-custom-menu-title/)
264,238
<p>I have a category called News and a custom Taxonomy called Filters which is a hierarchical Taxonomy.</p> <p>When a user creates a Post, they select a subcategory under news and a sub-filter under the Filter Taxonomy.</p> <p>Now I am trying to list all the 'Sub-Categories' and 'Filters' when a user navigates to /news.</p> <p>Listing the Sub-Categories for the 'News' category was easy. But I can't seem to figure out a way to list all the 'Sub-Filters' for the Taxonomy 'Filters' limited to only the category 'News'.</p> <p>Here is the code I used for getting a list of sub-categories for the category news:</p> <pre><code>function get_child_categories() { if (is_category()) { $thiscat = get_category(get_query_var('cat')); $catid = $thiscat-&gt;cat_ID; $args = array('parent' =&gt; $catid); $categories = get_categories($args); return $categories; } return false; } </code></pre> <p>I was hoping for a similar function which will list all terms for taxonomy 'Filters' but only limited to the category 'News'. Here is a screenshot of what I am trying to achieve:</p> <p>In the screenshot below '/news' is related to the 'News' category in the admin area. So if a user goes to /news, the front end should list all the posts for the 'News' Category.</p> <p>The page should also list all the sub-categories under the Category 'News'. This is done as you can see from the horizontal list of Sub Categories. </p> <p>Now the user can also select a Filter as can be seen in the admin UI. What I am trying to achieve is to list all the Filters for any post that may be categorized under 'News' and display in the horizontal list where under 'Filters'. This will then be used to filter the posts when the user clicks for example 'World News' to list only the posts that have the Filter 'World News' checked. </p> <p><a href="https://i.stack.imgur.com/MVRQp.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/MVRQp.png" alt="enter image description here"></a></p> <p>Current Category/Taxonomy in the Admin Area when editing the post</p> <p><a href="https://i.stack.imgur.com/3PTig.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3PTig.png" alt="enter image description here"></a></p>
[ { "answer_id": 264261, "author": "Nate", "author_id": 87380, "author_profile": "https://wordpress.stackexchange.com/users/87380", "pm_score": 1, "selected": false, "text": "<p>I'm not sure that I've understand what you are asking for but i hope this can help you out-</p>\n\n<p><strong>Getting all sub-categories of current category</strong></p>\n\n<pre><code>$args = array('parent' =&gt; 17); // Or get queried object for ID\n$categories = get_categories( $args );\n</code></pre>\n\n<p><strong>Getting all sub-categories from all levels</strong></p>\n\n<pre><code>$args = array('child_of' =&gt; 17); // Or get queried object for ID\n$categories = get_categories( $args );\n</code></pre>\n\n<p><strong>Getting all categories under custom taxonomy</strong></p>\n\n<pre><code>$terms = get_terms(array(\n 'taxonomy' =&gt; 'post_tag',\n 'hide_empty' =&gt; false,\n));\n</code></pre>\n" }, { "answer_id": 264282, "author": "Vinod Dalvi", "author_id": 14347, "author_profile": "https://wordpress.stackexchange.com/users/14347", "pm_score": 3, "selected": true, "text": "<p>The following code will do it. Please change the 'filter' text in the below code to whatever filters taxonomy name you have set.</p>\n\n<pre><code>if(is_category() ){\n\n $thiscat = get_queried_object_id(); \n $filter_tax = array();\n $args = array( 'category' =&gt; $thiscat );\n $lastposts = get_posts( $args );\n\n foreach ( $lastposts as $post ){\n setup_postdata( $post );\n $terms = get_the_terms( $post-&gt;ID, 'filter' ); // Change the taxonomy name here\n\n if ( $terms &amp;&amp; ! is_wp_error( $terms ) ){\n\n foreach ( $terms as $term ) {\n $filter_tax[] = $term;\n }\n\n }\n }\n wp_reset_postdata();\n\n if( !empty($filter_tax) ){\n print_r($filter_tax);\n } else {\n echo 'No filter set.';\n }\n\n}\n</code></pre>\n" } ]
2017/04/20
[ "https://wordpress.stackexchange.com/questions/264238", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/114495/" ]
I have a category called News and a custom Taxonomy called Filters which is a hierarchical Taxonomy. When a user creates a Post, they select a subcategory under news and a sub-filter under the Filter Taxonomy. Now I am trying to list all the 'Sub-Categories' and 'Filters' when a user navigates to /news. Listing the Sub-Categories for the 'News' category was easy. But I can't seem to figure out a way to list all the 'Sub-Filters' for the Taxonomy 'Filters' limited to only the category 'News'. Here is the code I used for getting a list of sub-categories for the category news: ``` function get_child_categories() { if (is_category()) { $thiscat = get_category(get_query_var('cat')); $catid = $thiscat->cat_ID; $args = array('parent' => $catid); $categories = get_categories($args); return $categories; } return false; } ``` I was hoping for a similar function which will list all terms for taxonomy 'Filters' but only limited to the category 'News'. Here is a screenshot of what I am trying to achieve: In the screenshot below '/news' is related to the 'News' category in the admin area. So if a user goes to /news, the front end should list all the posts for the 'News' Category. The page should also list all the sub-categories under the Category 'News'. This is done as you can see from the horizontal list of Sub Categories. Now the user can also select a Filter as can be seen in the admin UI. What I am trying to achieve is to list all the Filters for any post that may be categorized under 'News' and display in the horizontal list where under 'Filters'. This will then be used to filter the posts when the user clicks for example 'World News' to list only the posts that have the Filter 'World News' checked. [![enter image description here](https://i.stack.imgur.com/MVRQp.png)](https://i.stack.imgur.com/MVRQp.png) Current Category/Taxonomy in the Admin Area when editing the post [![enter image description here](https://i.stack.imgur.com/3PTig.png)](https://i.stack.imgur.com/3PTig.png)
The following code will do it. Please change the 'filter' text in the below code to whatever filters taxonomy name you have set. ``` if(is_category() ){ $thiscat = get_queried_object_id(); $filter_tax = array(); $args = array( 'category' => $thiscat ); $lastposts = get_posts( $args ); foreach ( $lastposts as $post ){ setup_postdata( $post ); $terms = get_the_terms( $post->ID, 'filter' ); // Change the taxonomy name here if ( $terms && ! is_wp_error( $terms ) ){ foreach ( $terms as $term ) { $filter_tax[] = $term; } } } wp_reset_postdata(); if( !empty($filter_tax) ){ print_r($filter_tax); } else { echo 'No filter set.'; } } ```
264,284
<p>I created a custom content template, assigned it to a page and coded the query.</p> <p>Everything appears to be working as they should. The only issue I have is with the pagination. So, when I go the second page I get a "No posts were found."</p> <p>What I've tried so far:</p> <ul> <li>I set another paginated grid (3rd party plugin) as a homepage. Fiddling with the pagination of that plugin gave me the same devastating result.</li> </ul> <p>This is my source</p> <pre><code> &lt;?php if ( get_query_var('paged') ) { $paged = get_query_var('paged'); } elseif ( get_query_var('page') ) { $paged = get_query_var('page'); } else { $paged = 1; } $args=array( 'post_type' =&gt; 'gadget', 'post_status' =&gt; 'publish', 'posts_per_page' =&gt; 36, 'paged' =&gt; $paged, 'nopaging' =&gt; false ); $fp_query = null; $fp_query = new WP_Query($args); if( $fp_query-&gt;have_posts() ) { $i = 0; while ($fp_query-&gt;have_posts()) : $fp_query-&gt;the_post(); global $post; $postidlt = get_the_id($post-&gt;ID); // modified to work with 3 columns // output an open &lt;div&gt; if($i % 3 == 0) { ?&gt; &lt;div class="vc_row prd-box-row"&gt; &lt;?php } ?&gt; &lt;div class="vc_col-md-4 vc_col-sm-6 vc_col-xs-12 prd-box row-height"&gt; &lt;div class="prd-box-inner"&gt; &lt;div class="prd-box-image-container"&gt; &lt;a href="&lt;?php the_permalink(); ?&gt;"&gt; &lt;div class="prd-box-image" style ="background-image: url( &lt;?php $acf_header = get_field('header_image'); if ($acf_header) { the_field('header_image'); } else { echo types_render_field('headerimage', array("raw"=&gt;"true", "url"=&gt;"true","id"=&gt;"$postidlt")); } ?&gt;);"&gt; &lt;div class="vc_col-xs-12 prd-box-date"&gt;&lt;?php $short_date = get_the_date( 'M j' ); echo $short_date;?&gt;&lt;span class="full-date"&gt;, &lt;?php $full_date = get_the_date( 'Y' ); echo $full_date;?&gt;&lt;/span&gt;&lt;/div&gt; &lt;div class="badges-container"&gt; &lt;!-- Discount Condition --&gt; &lt;?php $discountbg = types_render_field("discount", array("style" =&gt; "FIELD_NAME : $ FIELD_VALUE", "id"=&gt;"$postidlt")); if($discountbg) : ?&gt; &lt;div class="vc_col-xs-2 discounted-badge"&gt; &lt;i class="fa fa-percent" aria-hidden="true"&gt;&lt;/i&gt; &lt;/div&gt; &lt;?php endif; ?&gt; &lt;!-- Video Condition --&gt; &lt;div class="vc_col-xs-2 video-badge"&gt; &lt;i class="fa fa-play" aria-hidden="true"&gt;&lt;/i&gt; &lt;/div&gt; &lt;!-- Crowdfunding Condition --&gt; &lt;?php if ( has_term('crowdfunding', 'gadget-categories', $post-&gt;ID) ): ?&gt; &lt;div class="vc_col-xs-2 crowdfunding-badge"&gt; &lt;i class="fa fa-money" aria-hidden="true"&gt;&lt;/i&gt; &lt;/div&gt; &lt;?php endif; ?&gt; &lt;/div&gt; &lt;/div&gt; &lt;/a&gt; &lt;/div&gt; &lt;div class="prd-separator"&gt;&lt;/div&gt; &lt;div class="vc_row prd-box-info"&gt; &lt;div class="vc_col-xs-12 prd-box-title"&gt;&lt;a href="&lt;?php the_permalink(); ?&gt;" title="&lt;?php the_title_attribute(); ?&gt;"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;&lt;/div&gt; &lt;/div&gt; &lt;div class="prd-separator"&gt;&lt;/div&gt; &lt;div class="vc_row prd-box-info"&gt; &lt;div class="vc_col-md-12 vc_col-sm-12 vc_col-xs-12 ct-pr-wrapper"&gt; &lt;div class="prd-box-price"&gt; &lt;?php $initalprice = types_render_field("initial-price", array("style" =&gt; "FIELD_NAME : $ FIELD_VALUE", "id"=&gt;"$postidlt")); $discountedprice = types_render_field("discount", array("style" =&gt; "FIELD_NAME : $ FIELD_VALUE", "id"=&gt;"$postidlt")); $tba = types_render_field("tba-n", array("output" =&gt; "raw", "id"=&gt;"$postidlt")); $currency = types_render_field("currency", array()); if ($initalprice &amp;&amp; empty($discountedprice) &amp;&amp; empty($tba)) { echo($currency),($initalprice); } elseif ($discountedprice &amp;&amp; empty($tba)) { echo($currency),($discountedprice); } elseif ($tba) { echo("TBA"); } ?&gt; &lt;/div&gt; &lt;div class="prd-box-category"&gt; &lt;?php $terms = get_the_terms( $post-&gt;ID , 'gadget_categories' ); foreach ( $terms as $index =&gt; $term ) { if ($index == 0) { // The $term is an object, so we don't need to specify the $taxonomy. $term_link = get_term_link( $term ); // If there was an error, continue to the next term. if ( is_wp_error( $term_link ) ) { continue; } // We successfully got a link. Print it out. echo '&lt;a class="first-ct" href="' . esc_url( $term_link ) . '"&gt;' . $term-&gt;name . '&lt;/a&gt;'; } } ?&gt; &lt;?php $terms_rst = get_the_terms( $post-&gt;ID , 'gadget_categories' ); echo '&lt;div class="rest-categories"&gt;'; foreach ( $terms_rst as $index =&gt; $term ) { if ($index &gt; 0) { // The $term is an object, so we don't need to specify the $taxonomy. $term_link = get_term_link( $term ); // If there was an error, continue to the next term. if ( is_wp_error( $term_link ) ) { continue; } // We successfully got a link. Print it out. echo '&lt;a class="rest" href="' . esc_url( $term_link ) . '"&gt;' . $term-&gt;name . '&lt;/a&gt;'; } } echo '&lt;/div&gt;'; ?&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="vc_row prd-box-share-wh-row"&gt; &lt;div class="prd-separator"&gt;&lt;/div&gt; &lt;div class="prd-box-share-container"&gt; &lt;div class="vc_col-xs-1"&gt;&lt;/div&gt; &lt;div class="vc_col-xs-4"&gt;&lt;?php echo do_shortcode( '[addtoany]' );?&gt;&lt;/div&gt; &lt;div class="vc_col-xs-1"&gt;&lt;/div&gt; &lt;/div&gt; &lt;div class="prd-box-wishlist-container"&gt; &lt;div class="vc_col-xs-1"&gt;&lt;/div&gt; &lt;div class="vc_col-xs-4"&gt; &lt;?php $arg = array ( 'echo' =&gt; true ); do_action('gd_mylist_btn',$arg); ?&gt; &lt;/div&gt; &lt;div class="vc_col-xs-1"&gt;&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="prd-separator"&gt;&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;?php $i++; // Closing the grid row div if($i != 0 &amp;&amp; $i % 3 == 0) { ?&gt; &lt;/div&gt;&lt;!--/.row--&gt; &lt;div class="clearfix"&gt;&lt;/div&gt; &lt;?php } ?&gt; &lt;!-- Random Category Snippet Generation --&gt; &lt;?php if( $i % 12 == 0 ) { $max = 1; //number of categories to display $taxonomy = 'gadget_categories'; $terms = get_terms($taxonomy, 'orderby=name&amp;order= ASC&amp;hide_empty=0'); // Random order shuffle($terms); // Get first $max items $terms = array_slice($terms, 0, $max); // Sort by name usort($terms, function($a, $b){ return strcasecmp($a-&gt;name, $b-&gt;name); }); // Echo random terms sorted alphabetically if ($terms) { foreach($terms as $term) { $termID = $term-&gt;term_id; echo '&lt;div class="random-category-snippet" style="background-image: url('.types_render_termmeta("category-image", array( "term_id" =&gt; $termID, "output" =&gt;"raw") ).')"&gt;&lt;div class="random-snippet-inner"&gt;&lt;a href="' .get_term_link( $term, $taxonomy ) . '" title="' . sprintf( __( "View all gadgets in %s" ), $term-&gt;name ) . '" ' . '&gt;' . $term-&gt;name.'&lt;/a&gt;&lt;p&gt;' . $term-&gt;description . '&lt;/p&gt;&lt;br&gt;&lt;br&gt;&lt;a class="explore-category" href="'. esc_url( get_term_link( $term ) ) .'"&gt;Explore This Category&lt;/a&gt;&lt;/div&gt;&lt;/div&gt; '; } } } ?&gt; &lt;?php endwhile; } wp_reset_postdata(); ?&gt; &lt;div class="pagination"&gt; &lt;div class="previous"&gt;&lt;?php previous_posts_link( 'Older Posts' ); ?&gt;&lt;/div&gt; &lt;div class="next"&gt;&lt;?php next_posts_link( 'Newer Posts', $fp_query-&gt;max_num_pages ); ?&gt;&lt;/div&gt; &lt;/div&gt; &lt;!-- pagination --&gt; &lt;/div&gt;&lt;!--/.container--&gt; &lt;/div&gt; </code></pre> <p>You can see a live representation of the issue by visiting <a href="https://mygadgeto.com/wpmig" rel="nofollow noreferrer">this link</a> and clicking on "Newer Posts" at the bottom of the page.</p> <p>EDIT</p> <p>You can see that at the moment there is a lazyloader at the bottom of the page. Using this template I almost achieved the desired result <a href="https://www.mygadgeto.com/wpmig/index.php/pagination-test" rel="nofollow noreferrer">here</a>. However, I still get nothing on the frontpage (keep in mind that the frontpage and the page I provided before are using the same exact template.</p>
[ { "answer_id": 264700, "author": "BlueSuiter", "author_id": 92665, "author_profile": "https://wordpress.stackexchange.com/users/92665", "pm_score": 3, "selected": true, "text": "<p>Please, update your loop part with following code:</p>\n\n<pre><code>&lt;?php\n\n$page = (get_query_var('page') ? get_query_var('page') : 1);\n$args=array('post_type' =&gt; 'gadget', 'post_status' =&gt; 'publish', 'posts_per_page' =&gt; 36, 'page' =&gt; $page);\n\n$wp_query = new WP_Query($args);\nif( $wp_query-&gt;have_posts() ) {\n\n $i = 0;\n while ($wp_query-&gt;have_posts()) : $wp_query-&gt;the_post();\n $postidlt = $post-&gt;ID;\n</code></pre>\n\n<p><strong>Reason before using page instead of paged.</strong>\n<strong>page (int)</strong> - number of page for a static front page. Show the posts that would normally show up just on page X of a Static Front Page.</p>\n" }, { "answer_id": 264774, "author": "Swen", "author_id": 22588, "author_profile": "https://wordpress.stackexchange.com/users/22588", "pm_score": 0, "selected": false, "text": "<p>I am not entirely sure if this will work, but I remember struggling with a similar issue before. It's worth a try, and I took this from my own (working) code.</p>\n\n<p><strong>Please note that this is my own vague understanding of the issue.</strong></p>\n\n<p>I think the general idea is that your pagination is working off the main WordPress query for displaying the front page or custom page. This is why it does not work with your custom (additional) query inside the Main query.</p>\n\n<p>To circumvent this, we first store the main <code>$wp_query</code> object inside the <code>$temp_query</code> object. Then we reset the main <code>$wp_query</code>, and replace it with our own custom query.</p>\n\n<p>After looping through our posts, we restore the main <code>$wp_query</code> object from our <code>$temp_query</code>.</p>\n\n<pre><code>global $wp_query\n\n$custom_query_args = array(\n 'post_type' =&gt; 'gadget',\n 'post_status' =&gt; 'publish',\n 'posts_per_page' =&gt; 36\n);\n\n// Get the pagination\n$custom_query_args['paged'] = get_query_var( 'paged' ) ? get_query_var( 'paged' ) : 1; \n\n// Create the WP_Query object\n$custom_query = new WP_Query( $custom_query_args );\n\n// Store the existing $wp_query object\n$temp_query = $wp_query;\n\n// Clear the $wp_query object\n$wp_query = NULL;\n\n// Replace with our custom query object\n$wp_query = $custom_query;\n\n// Run our query\nif ( $custom_query-&gt;have_posts() ) {\n\n while ( $custom_query-&gt;have_posts() ) {\n\n $custom_query-&gt;the_post();\n\n }\n\n // Display pagination links before resetting the $wp_query object to the original\n ?&gt;\n &lt;div class=\"pagination\"&gt;\n &lt;div class=\"previous\"&gt;&lt;?php previous_posts_link( 'Older Posts' ); ?&gt;&lt;/div&gt;\n &lt;div class=\"next\"&gt;&lt;?php next_posts_link( 'Newer Posts', $custom_query-&gt;max_num_pages ); ?&gt;&lt;/div&gt;\n &lt;/div&gt;\n &lt;?php\n\n}\n\n// Reset postdata\nwp_reset_postdata();\n\n// Restore main query object\n$wp_query = NULL;\n$wp_query = $temp_query;\n</code></pre>\n" } ]
2017/04/20
[ "https://wordpress.stackexchange.com/questions/264284", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/115305/" ]
I created a custom content template, assigned it to a page and coded the query. Everything appears to be working as they should. The only issue I have is with the pagination. So, when I go the second page I get a "No posts were found." What I've tried so far: * I set another paginated grid (3rd party plugin) as a homepage. Fiddling with the pagination of that plugin gave me the same devastating result. This is my source ``` <?php if ( get_query_var('paged') ) { $paged = get_query_var('paged'); } elseif ( get_query_var('page') ) { $paged = get_query_var('page'); } else { $paged = 1; } $args=array( 'post_type' => 'gadget', 'post_status' => 'publish', 'posts_per_page' => 36, 'paged' => $paged, 'nopaging' => false ); $fp_query = null; $fp_query = new WP_Query($args); if( $fp_query->have_posts() ) { $i = 0; while ($fp_query->have_posts()) : $fp_query->the_post(); global $post; $postidlt = get_the_id($post->ID); // modified to work with 3 columns // output an open <div> if($i % 3 == 0) { ?> <div class="vc_row prd-box-row"> <?php } ?> <div class="vc_col-md-4 vc_col-sm-6 vc_col-xs-12 prd-box row-height"> <div class="prd-box-inner"> <div class="prd-box-image-container"> <a href="<?php the_permalink(); ?>"> <div class="prd-box-image" style ="background-image: url( <?php $acf_header = get_field('header_image'); if ($acf_header) { the_field('header_image'); } else { echo types_render_field('headerimage', array("raw"=>"true", "url"=>"true","id"=>"$postidlt")); } ?>);"> <div class="vc_col-xs-12 prd-box-date"><?php $short_date = get_the_date( 'M j' ); echo $short_date;?><span class="full-date">, <?php $full_date = get_the_date( 'Y' ); echo $full_date;?></span></div> <div class="badges-container"> <!-- Discount Condition --> <?php $discountbg = types_render_field("discount", array("style" => "FIELD_NAME : $ FIELD_VALUE", "id"=>"$postidlt")); if($discountbg) : ?> <div class="vc_col-xs-2 discounted-badge"> <i class="fa fa-percent" aria-hidden="true"></i> </div> <?php endif; ?> <!-- Video Condition --> <div class="vc_col-xs-2 video-badge"> <i class="fa fa-play" aria-hidden="true"></i> </div> <!-- Crowdfunding Condition --> <?php if ( has_term('crowdfunding', 'gadget-categories', $post->ID) ): ?> <div class="vc_col-xs-2 crowdfunding-badge"> <i class="fa fa-money" aria-hidden="true"></i> </div> <?php endif; ?> </div> </div> </a> </div> <div class="prd-separator"></div> <div class="vc_row prd-box-info"> <div class="vc_col-xs-12 prd-box-title"><a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a></div> </div> <div class="prd-separator"></div> <div class="vc_row prd-box-info"> <div class="vc_col-md-12 vc_col-sm-12 vc_col-xs-12 ct-pr-wrapper"> <div class="prd-box-price"> <?php $initalprice = types_render_field("initial-price", array("style" => "FIELD_NAME : $ FIELD_VALUE", "id"=>"$postidlt")); $discountedprice = types_render_field("discount", array("style" => "FIELD_NAME : $ FIELD_VALUE", "id"=>"$postidlt")); $tba = types_render_field("tba-n", array("output" => "raw", "id"=>"$postidlt")); $currency = types_render_field("currency", array()); if ($initalprice && empty($discountedprice) && empty($tba)) { echo($currency),($initalprice); } elseif ($discountedprice && empty($tba)) { echo($currency),($discountedprice); } elseif ($tba) { echo("TBA"); } ?> </div> <div class="prd-box-category"> <?php $terms = get_the_terms( $post->ID , 'gadget_categories' ); foreach ( $terms as $index => $term ) { if ($index == 0) { // The $term is an object, so we don't need to specify the $taxonomy. $term_link = get_term_link( $term ); // If there was an error, continue to the next term. if ( is_wp_error( $term_link ) ) { continue; } // We successfully got a link. Print it out. echo '<a class="first-ct" href="' . esc_url( $term_link ) . '">' . $term->name . '</a>'; } } ?> <?php $terms_rst = get_the_terms( $post->ID , 'gadget_categories' ); echo '<div class="rest-categories">'; foreach ( $terms_rst as $index => $term ) { if ($index > 0) { // The $term is an object, so we don't need to specify the $taxonomy. $term_link = get_term_link( $term ); // If there was an error, continue to the next term. if ( is_wp_error( $term_link ) ) { continue; } // We successfully got a link. Print it out. echo '<a class="rest" href="' . esc_url( $term_link ) . '">' . $term->name . '</a>'; } } echo '</div>'; ?> </div> </div> </div> <div class="vc_row prd-box-share-wh-row"> <div class="prd-separator"></div> <div class="prd-box-share-container"> <div class="vc_col-xs-1"></div> <div class="vc_col-xs-4"><?php echo do_shortcode( '[addtoany]' );?></div> <div class="vc_col-xs-1"></div> </div> <div class="prd-box-wishlist-container"> <div class="vc_col-xs-1"></div> <div class="vc_col-xs-4"> <?php $arg = array ( 'echo' => true ); do_action('gd_mylist_btn',$arg); ?> </div> <div class="vc_col-xs-1"></div> </div> </div> <div class="prd-separator"></div> </div> </div> <?php $i++; // Closing the grid row div if($i != 0 && $i % 3 == 0) { ?> </div><!--/.row--> <div class="clearfix"></div> <?php } ?> <!-- Random Category Snippet Generation --> <?php if( $i % 12 == 0 ) { $max = 1; //number of categories to display $taxonomy = 'gadget_categories'; $terms = get_terms($taxonomy, 'orderby=name&order= ASC&hide_empty=0'); // Random order shuffle($terms); // Get first $max items $terms = array_slice($terms, 0, $max); // Sort by name usort($terms, function($a, $b){ return strcasecmp($a->name, $b->name); }); // Echo random terms sorted alphabetically if ($terms) { foreach($terms as $term) { $termID = $term->term_id; echo '<div class="random-category-snippet" style="background-image: url('.types_render_termmeta("category-image", array( "term_id" => $termID, "output" =>"raw") ).')"><div class="random-snippet-inner"><a href="' .get_term_link( $term, $taxonomy ) . '" title="' . sprintf( __( "View all gadgets in %s" ), $term->name ) . '" ' . '>' . $term->name.'</a><p>' . $term->description . '</p><br><br><a class="explore-category" href="'. esc_url( get_term_link( $term ) ) .'">Explore This Category</a></div></div> '; } } } ?> <?php endwhile; } wp_reset_postdata(); ?> <div class="pagination"> <div class="previous"><?php previous_posts_link( 'Older Posts' ); ?></div> <div class="next"><?php next_posts_link( 'Newer Posts', $fp_query->max_num_pages ); ?></div> </div> <!-- pagination --> </div><!--/.container--> </div> ``` You can see a live representation of the issue by visiting [this link](https://mygadgeto.com/wpmig) and clicking on "Newer Posts" at the bottom of the page. EDIT You can see that at the moment there is a lazyloader at the bottom of the page. Using this template I almost achieved the desired result [here](https://www.mygadgeto.com/wpmig/index.php/pagination-test). However, I still get nothing on the frontpage (keep in mind that the frontpage and the page I provided before are using the same exact template.
Please, update your loop part with following code: ``` <?php $page = (get_query_var('page') ? get_query_var('page') : 1); $args=array('post_type' => 'gadget', 'post_status' => 'publish', 'posts_per_page' => 36, 'page' => $page); $wp_query = new WP_Query($args); if( $wp_query->have_posts() ) { $i = 0; while ($wp_query->have_posts()) : $wp_query->the_post(); $postidlt = $post->ID; ``` **Reason before using page instead of paged.** **page (int)** - number of page for a static front page. Show the posts that would normally show up just on page X of a Static Front Page.
264,289
<p>The Twenty Seventeen header displays two text boxes: the Site Title and the Tagline. I would like to add a new text box at the top right of the screen. How can I do it?</p> <p>I have an active Twenty Seventeen child theme.</p>
[ { "answer_id": 264324, "author": "Greeso", "author_id": 34253, "author_profile": "https://wordpress.stackexchange.com/users/34253", "pm_score": 1, "selected": false, "text": "<p>In the original Twenty Seventeen theme, find which file is used to display the Site Title and the Tagline. Then in your child theme, recreate this file, and edit it to include your text box.</p>\n" }, { "answer_id": 266258, "author": "Martial Foucault", "author_id": 119255, "author_profile": "https://wordpress.stackexchange.com/users/119255", "pm_score": 1, "selected": true, "text": "<p>That works if you put your code in header.php, copied in the childtheme, after the line:</p>\n\n<pre><code>&lt;header id=\"masthead\" class=\"site-header\" role=\"banner\"&gt;\n</code></pre>\n\n<p>My html code is:</p>\n\n<pre><code>&lt;div class=\"logo-right-text\"&gt;\n&lt;span style=\"font-size: 14px; font-weight: bold; color: #555;\"&gt;1800-123-456-22&lt;/span&gt;\n&lt;div class=\"clear\" style=\" height:3px;\"&gt;&lt;/div&gt;\n&lt;span style=\"font-size: 14px; font-weight: bold; color: #555; \"&gt;[email protected]&lt;/span&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p>And CSS:</p>\n\n<pre><code>div.logo-right-text{ margin: 0px 10px; }\ndiv.logo-right-text { float: right; text-align: right; }\n.logo-right-text{ padding-top: 42px; }\n</code></pre>\n\n<p>But finaly I'll try to put these 2 phone and mail in the menu line... if I find how to do ;)</p>\n" } ]
2017/04/20
[ "https://wordpress.stackexchange.com/questions/264289", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/112370/" ]
The Twenty Seventeen header displays two text boxes: the Site Title and the Tagline. I would like to add a new text box at the top right of the screen. How can I do it? I have an active Twenty Seventeen child theme.
That works if you put your code in header.php, copied in the childtheme, after the line: ``` <header id="masthead" class="site-header" role="banner"> ``` My html code is: ``` <div class="logo-right-text"> <span style="font-size: 14px; font-weight: bold; color: #555;">1800-123-456-22</span> <div class="clear" style=" height:3px;"></div> <span style="font-size: 14px; font-weight: bold; color: #555; ">[email protected]</span> </div> ``` And CSS: ``` div.logo-right-text{ margin: 0px 10px; } div.logo-right-text { float: right; text-align: right; } .logo-right-text{ padding-top: 42px; } ``` But finaly I'll try to put these 2 phone and mail in the menu line... if I find how to do ;)
264,313
<p>I've been working on my own theme and for some reason wordpress doesn't seem to be implementing my code. My navigation bar doesn't load right if I'm logged in but loads find if I'm logged out, however any bootstrap coding I put in the body loads right if I'm logged in but doesn't load if I'm logged out.</p> <p>When I'm logged in:</p> <p><a href="https://i.stack.imgur.com/kubKb.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/kubKb.png" alt="enter image description here"></a></p> <p>When I'm logged out:</p> <p><a href="https://i.stack.imgur.com/PWCiO.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/PWCiO.png" alt="enter image description here"></a></p> <p>Header Code:</p> <pre><code> &lt;head&gt; &lt;meta charset="utf-8"&gt; &lt;title&gt;Bootstrap, from Twitter&lt;/title&gt; &lt;meta name="viewport" content="width=device-width, initial-scale=1.0"&gt; &lt;!-- Le styles --&gt; &lt;link href="&lt;?php bloginfo('stylesheet_url');?&gt;" rel="stylesheet"&gt; &lt;!-- Le HTML5 shim, for IE6-8 support of HTML5 elements --&gt; &lt;!--[if lt IE 9]&gt; &lt;script src="http://html5shim.googlecode.com/svn/trunk/html5.js"&gt;&lt;/script&gt; &lt;![endif]--&gt; &lt;?php wp_enqueue_script("jquery"); ?&gt; &lt;?php wp_head(); ?&gt; &lt;/head&gt; &lt;?php echo '&lt;body class="'.join(' ', get_body_class()).'"&gt;'.PHP_EOL; ?&gt; &lt;section class="navigation"&gt; &lt;div class="navbar navbar-inverse navbar-fixed-top"&gt; &lt;div class="navbar-inner"&gt; &lt;div class="container"&gt; &lt;a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse"&gt; &lt;span class="icon-bar"&gt;&lt;/span&gt; &lt;span class="icon-bar"&gt;&lt;/span&gt; &lt;span class="icon-bar"&gt;&lt;/span&gt; &lt;/a&gt; &lt;a class="brand" href="&lt;?php echo site_url(); ?&gt;"&gt;AdventureSpace&lt;/a&gt; &lt;div class="nav-collapse collapse"&gt; &lt;ul class="nav"&gt; &lt;?php wp_list_pages(array('title_li' =&gt; '', 'exclude' =&gt; 4)); ?&gt; &lt;/ul&gt; &lt;/div&gt;&lt;!--/.nav-collapse --&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;section id="body-content"&gt; </code></pre> <p>I don't see any reason for it to be loading like this. You can even see that when logged it in fails to load the navigation bar correctly but it loads the columns right. I'm using xampp to run wordpress on my laptop right now.</p> <p><strong>Update - Further Information</strong> my style.css (the commented part was from a tutorial I did which I'll also link below):</p> <pre><code>/* Theme Name: WP Bootstrap Theme URI: http://teamtreehouse.com/how-to-build-a-simple-responsive-wordpress-site-with-twitter-bootstrap Description: A simple responsive theme built with Bootstrap Author: Zac Gordon Author URI: http://zacgordon.com/ Version: 1.0 Tags: responsive, white, bootstrap License: Attribution-ShareAlike 3.0 Unported (CC BY-SA 3.0) License URI: http://creativecommons.org/licenses/by-sa/3.0/ This is an example theme to go along with the Treehouse blog post on &lt;a href="http://teamtreehouse.com/how-to-build-a-responsive-wordpress-site-with-twitter-bootstrap"&gt;How to Build a Simple Responsive WordPress Site Using Twitter Bootstrap&lt;/a&gt;. */ @import url('bootstrap/css/bootstrap.css'); @import url('bootstrap/css/bootstrap-responsive.css'); body { padding-top: 70px; padding-bottom: 40px; } </code></pre> <p>Header.php:</p> <pre><code> &lt;head&gt; &lt;meta charset="utf-8"&gt; &lt;title&gt;Bootstrap, from Twitter&lt;/title&gt; &lt;meta name="viewport" content="width=device-width, initial-scale=1.0"&gt; &lt;!-- Le styles --&gt; &lt;link href="&lt;?php bloginfo('stylesheet_url');?&gt;" rel="stylesheet"&gt; &lt;!-- Le HTML5 shim, for IE6-8 support of HTML5 elements --&gt; &lt;!--[if lt IE 9]&gt; &lt;script src="http://html5shim.googlecode.com/svn/trunk/html5.js"&gt;&lt;/script&gt; &lt;![endif]--&gt; &lt;?php wp_enqueue_script("jquery"); ?&gt; &lt;?php wp_head(); ?&gt; &lt;/head&gt; &lt;?php echo '&lt;body class="'.join(' ', get_body_class()).'"&gt;'.PHP_EOL; ?&gt; &lt;section class="navigation"&gt; &lt;div class="navbar navbar-inverse navbar-fixed-top"&gt; &lt;div class="navbar-inner"&gt; &lt;div class="container"&gt; &lt;a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse"&gt; &lt;span class="icon-bar"&gt;&lt;/span&gt; &lt;span class="icon-bar"&gt;&lt;/span&gt; &lt;span class="icon-bar"&gt;&lt;/span&gt; &lt;/a&gt; &lt;a class="brand" href="&lt;?php echo site_url(); ?&gt;"&gt;AdventureSpace&lt;/a&gt; &lt;div class="nav-collapse collapse"&gt; &lt;ul class="nav"&gt; &lt;?php wp_list_pages(array('title_li' =&gt; '', 'exclude' =&gt; 4)); ?&gt; &lt;/ul&gt; &lt;/div&gt;&lt;!--/.nav-collapse --&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;section id="body-content"&gt; </code></pre> <p>Footer.php</p> <pre><code> &lt;hr&gt; &lt;footer&gt; &lt;p&gt;© Company 2012&lt;/p&gt; &lt;/footer&gt; &lt;/section&gt; &lt;!-- /container --&gt; &lt;/div&gt; &lt;!-- /container --&gt; &lt;?php wp_footer(); ?&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>functions.php (a lot of whats in here was given as a solution to the navbar being hidden behind the admin bar here <a href="https://wordpress.stackexchange.com/questions/87717/wordpress-admin-bar-overlapping-twitter-bootstrap-navigation">WordPress admin bar overlapping twitter bootstrap navigation</a>):</p> <pre><code>&lt;?php function wpbootstrap_scripts_with_jquery() { // Register the script like this for a theme: wp_register_script( 'custom-script', get_template_directory_uri() . '/bootstrap/js/bootstrap.js', array( 'jquery' ) ); // For either a plugin or a theme, you can then enqueue the script: wp_enqueue_script( 'custom-script' ); } add_action( 'wp_enqueue_scripts', 'wpbootstrap_scripts_with_jquery' ); if ( function_exists('register_sidebar') ) register_sidebar(array( 'before_widget' =&gt; '', 'after_widget' =&gt; '', 'before_title' =&gt; '&lt;h3&gt;', 'after_title' =&gt; '&lt;/h3&gt;', )); add_action('wp_head', 'mbe_wp_head'); function mbe_body_class($classes){ if(is_user_logged_in()){ $classes[] = 'body-logged-in'; } else{ $classes[] = 'body-logged-out'; } return $classes; } function mbe_wp_head(){ echo '&lt;style&gt;' .PHP_EOL .'body{ padding-top: 40px !important; }' .PHP_EOL .'body.body-logged-in .navbar-fixed-top{ top: 46px !important; }' .PHP_EOL .'body.logged-in .navbar-fixed-top{ top: 46px !important; }' .PHP_EOL .'@media only screen and (min-width: 783px) {' .PHP_EOL .'body{ padding-top: 40px !important; }' .PHP_EOL .'body.body-logged-in .navbar-fixed-top{ top: 28px !important; }' .PHP_EOL .'body.logged-in .navbar-fixed-top{ top: 28px !important; }' .PHP_EOL .'}&lt;/style&gt;' .PHP_EOL; } ?&gt; </code></pre> <p>Original tutorial here <code>http://blog.teamtreehouse.com/responsive-wordpress-bootstrap-theme-tutorial</code></p> <p>Its not a problem with the navbar, if I hadn't followed the instructions above for unhiding it you wouldn't see that dark part under the admin bar that says "AdventureSpace." For some reason my navbar isn't loading properly when I'm logged in (see pictures above) but loads fine when I'm logged out.</p> <p>I'm much less concerned about he navbar however. I would like to fix that but I'm <strong><em>much more interested in why my other boostrap code isn't working</em></strong>:</p> <pre><code> &lt;div class="container"&gt; &lt;div class="row"&gt; &lt;div class="col-md-6"&gt;1 of 2&lt;/div&gt; &lt;div class="col-md-6"&gt;1 of 2&lt;/div&gt; &lt;/div&gt; &lt;div class="row"&gt; &lt;div class="col"&gt;1 of 3&lt;/div&gt; &lt;div class="col"&gt;1 of 3&lt;/div&gt; &lt;div class="col"&gt;1 of 3&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="btn-group" role="group" aria-label="..."&gt; &lt;button type="button" class="btn btn-default"&gt;Left&lt;/button&gt; &lt;button type="button" class="btn btn-default"&gt;Middle&lt;/button&gt; &lt;button type="button" class="btn btn-default"&gt;Right&lt;/button&gt; &lt;/div&gt; Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam vestibulum ex laoreet venenatis imperdiet. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Ut ligula velit, efficitur a accumsan sit amet, cursus eget metus. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Cras consequat purus finibus lacus condimentum pulvinar. Aenean at commodo nulla, sollicitudin venenatis tortor. Vestibulum id efficitur sapien. Nulla congue tortor in mauris pulvinar, eu ultricies eros convallis. Sed non ligula id nulla lobortis vestibulum. Ut sed libero vel justo imperdiet suscipit a vel lectus. Aenean eget sapien eu eros facilisis finibus vitae et turpis. Nulla facilisi. Sed bibendum vehicula imperdiet. In quis erat sed massa volutpat posuere quis nec purus. Donec sagittis erat ex, congue sodales massa rutrum a. Morbi sed neque vel elit bibendum pretium sit amet vitae sapien. Mauris vitae ligula non magna fringilla efficitur. Vestibulum convallis lacus eget imperdiet accumsan. Integer eget nulla eget urna gravida ultricies quis id lectus. Nulla dictum, mauris sed sollicitudin laoreet, augue magna feugiat leo, eu euismod ipsum massa eu tellus. Sed nec urna facilisis, posuere augue finibus, facilisis est. Proin pulvinar ex nec consequat egestas. Ut rutrum mollis mi, vitae rutrum tortor gravida vel. Nullam eu libero lobortis ligula molestie ultricies. Suspendisse eleifend, ligula ac feugiat ultrices, mi ipsum tincidunt augue, quis dapibus turpis sem accumsan enim. Ut sit amet eleifend arcu, ac condimentum ipsum. Praesent efficitur felis mauris, non ullamcorper elit tempus eu. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Nulla gravida nisl ipsum, id viverra justo finibus nec. Pellentesque placerat euismod lectus, sit amet vulputate diam. Cras ut nisl vel urna euismod fringilla id et turpis. Donec et orci lacus. Curabitur dapibus nisi sit amet lobortis congue. Morbi turpis ex, sollicitudin nec nulla id, molestie lacinia dolor. Donec nec erat quis elit consectetur venenatis sit amet non nulla. Ut lacinia tempus faucibus. Mauris finibus ex sit amet urna feugiat, vel vehicula nisl vestibulum. Duis pulvinar magna ante, tempor pretium orci mollis at. In aliquet risus vel quam hendrerit sagittis. Proin laoreet vel felis ut tempus. Donec efficitur odio in erat vehicula auctor. Vestibulum posuere tortor vitae ultricies pretium. Nam euismod sollicitudin tortor, id interdum orci tincidunt vel. Vivamus lobortis euismod finibus. Duis iaculis turpis nec orci viverra, auctor sodales urna vestibulum. Etiam facilisis ac magna id pharetra. Donec a orci dolor. Ut aliquet lobortis dignissim. Aliquam quis tortor vel nunc varius pharetra. Ut placerat elit a risus semper finibus vitae eu tellus. Praesent sed sapien id nunc luctus dictum. Nunc rhoncus viverra metus. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nulla id iaculis nibh. Maecenas nec nunc eget eros sodales interdum. Aliquam euismod massa in viverra tincidunt. Aliquam dolor felis, faucibus sed interdum vel, congue non tortor. Ut luctus nibh nisl, vel mollis velit dignissim eget. Integer pellentesque nec enim nec pulvinar. Donec varius at libero posuere varius. &lt;/div&gt; </code></pre> <p>As you can see, there should be some sort of grid system also showing. It works when I'm logged in and doesn't work when I'm logged out which is the completely opposite problem.</p>
[ { "answer_id": 264324, "author": "Greeso", "author_id": 34253, "author_profile": "https://wordpress.stackexchange.com/users/34253", "pm_score": 1, "selected": false, "text": "<p>In the original Twenty Seventeen theme, find which file is used to display the Site Title and the Tagline. Then in your child theme, recreate this file, and edit it to include your text box.</p>\n" }, { "answer_id": 266258, "author": "Martial Foucault", "author_id": 119255, "author_profile": "https://wordpress.stackexchange.com/users/119255", "pm_score": 1, "selected": true, "text": "<p>That works if you put your code in header.php, copied in the childtheme, after the line:</p>\n\n<pre><code>&lt;header id=\"masthead\" class=\"site-header\" role=\"banner\"&gt;\n</code></pre>\n\n<p>My html code is:</p>\n\n<pre><code>&lt;div class=\"logo-right-text\"&gt;\n&lt;span style=\"font-size: 14px; font-weight: bold; color: #555;\"&gt;1800-123-456-22&lt;/span&gt;\n&lt;div class=\"clear\" style=\" height:3px;\"&gt;&lt;/div&gt;\n&lt;span style=\"font-size: 14px; font-weight: bold; color: #555; \"&gt;[email protected]&lt;/span&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p>And CSS:</p>\n\n<pre><code>div.logo-right-text{ margin: 0px 10px; }\ndiv.logo-right-text { float: right; text-align: right; }\n.logo-right-text{ padding-top: 42px; }\n</code></pre>\n\n<p>But finaly I'll try to put these 2 phone and mail in the menu line... if I find how to do ;)</p>\n" } ]
2017/04/20
[ "https://wordpress.stackexchange.com/questions/264313", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/90816/" ]
I've been working on my own theme and for some reason wordpress doesn't seem to be implementing my code. My navigation bar doesn't load right if I'm logged in but loads find if I'm logged out, however any bootstrap coding I put in the body loads right if I'm logged in but doesn't load if I'm logged out. When I'm logged in: [![enter image description here](https://i.stack.imgur.com/kubKb.png)](https://i.stack.imgur.com/kubKb.png) When I'm logged out: [![enter image description here](https://i.stack.imgur.com/PWCiO.png)](https://i.stack.imgur.com/PWCiO.png) Header Code: ``` <head> <meta charset="utf-8"> <title>Bootstrap, from Twitter</title> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- Le styles --> <link href="<?php bloginfo('stylesheet_url');?>" rel="stylesheet"> <!-- Le HTML5 shim, for IE6-8 support of HTML5 elements --> <!--[if lt IE 9]> <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> <?php wp_enqueue_script("jquery"); ?> <?php wp_head(); ?> </head> <?php echo '<body class="'.join(' ', get_body_class()).'">'.PHP_EOL; ?> <section class="navigation"> <div class="navbar navbar-inverse navbar-fixed-top"> <div class="navbar-inner"> <div class="container"> <a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </a> <a class="brand" href="<?php echo site_url(); ?>">AdventureSpace</a> <div class="nav-collapse collapse"> <ul class="nav"> <?php wp_list_pages(array('title_li' => '', 'exclude' => 4)); ?> </ul> </div><!--/.nav-collapse --> </div> </div> </div> <section id="body-content"> ``` I don't see any reason for it to be loading like this. You can even see that when logged it in fails to load the navigation bar correctly but it loads the columns right. I'm using xampp to run wordpress on my laptop right now. **Update - Further Information** my style.css (the commented part was from a tutorial I did which I'll also link below): ``` /* Theme Name: WP Bootstrap Theme URI: http://teamtreehouse.com/how-to-build-a-simple-responsive-wordpress-site-with-twitter-bootstrap Description: A simple responsive theme built with Bootstrap Author: Zac Gordon Author URI: http://zacgordon.com/ Version: 1.0 Tags: responsive, white, bootstrap License: Attribution-ShareAlike 3.0 Unported (CC BY-SA 3.0) License URI: http://creativecommons.org/licenses/by-sa/3.0/ This is an example theme to go along with the Treehouse blog post on <a href="http://teamtreehouse.com/how-to-build-a-responsive-wordpress-site-with-twitter-bootstrap">How to Build a Simple Responsive WordPress Site Using Twitter Bootstrap</a>. */ @import url('bootstrap/css/bootstrap.css'); @import url('bootstrap/css/bootstrap-responsive.css'); body { padding-top: 70px; padding-bottom: 40px; } ``` Header.php: ``` <head> <meta charset="utf-8"> <title>Bootstrap, from Twitter</title> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- Le styles --> <link href="<?php bloginfo('stylesheet_url');?>" rel="stylesheet"> <!-- Le HTML5 shim, for IE6-8 support of HTML5 elements --> <!--[if lt IE 9]> <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> <?php wp_enqueue_script("jquery"); ?> <?php wp_head(); ?> </head> <?php echo '<body class="'.join(' ', get_body_class()).'">'.PHP_EOL; ?> <section class="navigation"> <div class="navbar navbar-inverse navbar-fixed-top"> <div class="navbar-inner"> <div class="container"> <a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </a> <a class="brand" href="<?php echo site_url(); ?>">AdventureSpace</a> <div class="nav-collapse collapse"> <ul class="nav"> <?php wp_list_pages(array('title_li' => '', 'exclude' => 4)); ?> </ul> </div><!--/.nav-collapse --> </div> </div> </div> <section id="body-content"> ``` Footer.php ``` <hr> <footer> <p>© Company 2012</p> </footer> </section> <!-- /container --> </div> <!-- /container --> <?php wp_footer(); ?> </body> </html> ``` functions.php (a lot of whats in here was given as a solution to the navbar being hidden behind the admin bar here [WordPress admin bar overlapping twitter bootstrap navigation](https://wordpress.stackexchange.com/questions/87717/wordpress-admin-bar-overlapping-twitter-bootstrap-navigation)): ``` <?php function wpbootstrap_scripts_with_jquery() { // Register the script like this for a theme: wp_register_script( 'custom-script', get_template_directory_uri() . '/bootstrap/js/bootstrap.js', array( 'jquery' ) ); // For either a plugin or a theme, you can then enqueue the script: wp_enqueue_script( 'custom-script' ); } add_action( 'wp_enqueue_scripts', 'wpbootstrap_scripts_with_jquery' ); if ( function_exists('register_sidebar') ) register_sidebar(array( 'before_widget' => '', 'after_widget' => '', 'before_title' => '<h3>', 'after_title' => '</h3>', )); add_action('wp_head', 'mbe_wp_head'); function mbe_body_class($classes){ if(is_user_logged_in()){ $classes[] = 'body-logged-in'; } else{ $classes[] = 'body-logged-out'; } return $classes; } function mbe_wp_head(){ echo '<style>' .PHP_EOL .'body{ padding-top: 40px !important; }' .PHP_EOL .'body.body-logged-in .navbar-fixed-top{ top: 46px !important; }' .PHP_EOL .'body.logged-in .navbar-fixed-top{ top: 46px !important; }' .PHP_EOL .'@media only screen and (min-width: 783px) {' .PHP_EOL .'body{ padding-top: 40px !important; }' .PHP_EOL .'body.body-logged-in .navbar-fixed-top{ top: 28px !important; }' .PHP_EOL .'body.logged-in .navbar-fixed-top{ top: 28px !important; }' .PHP_EOL .'}</style>' .PHP_EOL; } ?> ``` Original tutorial here `http://blog.teamtreehouse.com/responsive-wordpress-bootstrap-theme-tutorial` Its not a problem with the navbar, if I hadn't followed the instructions above for unhiding it you wouldn't see that dark part under the admin bar that says "AdventureSpace." For some reason my navbar isn't loading properly when I'm logged in (see pictures above) but loads fine when I'm logged out. I'm much less concerned about he navbar however. I would like to fix that but I'm ***much more interested in why my other boostrap code isn't working***: ``` <div class="container"> <div class="row"> <div class="col-md-6">1 of 2</div> <div class="col-md-6">1 of 2</div> </div> <div class="row"> <div class="col">1 of 3</div> <div class="col">1 of 3</div> <div class="col">1 of 3</div> </div> </div> <div class="btn-group" role="group" aria-label="..."> <button type="button" class="btn btn-default">Left</button> <button type="button" class="btn btn-default">Middle</button> <button type="button" class="btn btn-default">Right</button> </div> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam vestibulum ex laoreet venenatis imperdiet. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Ut ligula velit, efficitur a accumsan sit amet, cursus eget metus. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Cras consequat purus finibus lacus condimentum pulvinar. Aenean at commodo nulla, sollicitudin venenatis tortor. Vestibulum id efficitur sapien. Nulla congue tortor in mauris pulvinar, eu ultricies eros convallis. Sed non ligula id nulla lobortis vestibulum. Ut sed libero vel justo imperdiet suscipit a vel lectus. Aenean eget sapien eu eros facilisis finibus vitae et turpis. Nulla facilisi. Sed bibendum vehicula imperdiet. In quis erat sed massa volutpat posuere quis nec purus. Donec sagittis erat ex, congue sodales massa rutrum a. Morbi sed neque vel elit bibendum pretium sit amet vitae sapien. Mauris vitae ligula non magna fringilla efficitur. Vestibulum convallis lacus eget imperdiet accumsan. Integer eget nulla eget urna gravida ultricies quis id lectus. Nulla dictum, mauris sed sollicitudin laoreet, augue magna feugiat leo, eu euismod ipsum massa eu tellus. Sed nec urna facilisis, posuere augue finibus, facilisis est. Proin pulvinar ex nec consequat egestas. Ut rutrum mollis mi, vitae rutrum tortor gravida vel. Nullam eu libero lobortis ligula molestie ultricies. Suspendisse eleifend, ligula ac feugiat ultrices, mi ipsum tincidunt augue, quis dapibus turpis sem accumsan enim. Ut sit amet eleifend arcu, ac condimentum ipsum. Praesent efficitur felis mauris, non ullamcorper elit tempus eu. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Nulla gravida nisl ipsum, id viverra justo finibus nec. Pellentesque placerat euismod lectus, sit amet vulputate diam. Cras ut nisl vel urna euismod fringilla id et turpis. Donec et orci lacus. Curabitur dapibus nisi sit amet lobortis congue. Morbi turpis ex, sollicitudin nec nulla id, molestie lacinia dolor. Donec nec erat quis elit consectetur venenatis sit amet non nulla. Ut lacinia tempus faucibus. Mauris finibus ex sit amet urna feugiat, vel vehicula nisl vestibulum. Duis pulvinar magna ante, tempor pretium orci mollis at. In aliquet risus vel quam hendrerit sagittis. Proin laoreet vel felis ut tempus. Donec efficitur odio in erat vehicula auctor. Vestibulum posuere tortor vitae ultricies pretium. Nam euismod sollicitudin tortor, id interdum orci tincidunt vel. Vivamus lobortis euismod finibus. Duis iaculis turpis nec orci viverra, auctor sodales urna vestibulum. Etiam facilisis ac magna id pharetra. Donec a orci dolor. Ut aliquet lobortis dignissim. Aliquam quis tortor vel nunc varius pharetra. Ut placerat elit a risus semper finibus vitae eu tellus. Praesent sed sapien id nunc luctus dictum. Nunc rhoncus viverra metus. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nulla id iaculis nibh. Maecenas nec nunc eget eros sodales interdum. Aliquam euismod massa in viverra tincidunt. Aliquam dolor felis, faucibus sed interdum vel, congue non tortor. Ut luctus nibh nisl, vel mollis velit dignissim eget. Integer pellentesque nec enim nec pulvinar. Donec varius at libero posuere varius. </div> ``` As you can see, there should be some sort of grid system also showing. It works when I'm logged in and doesn't work when I'm logged out which is the completely opposite problem.
That works if you put your code in header.php, copied in the childtheme, after the line: ``` <header id="masthead" class="site-header" role="banner"> ``` My html code is: ``` <div class="logo-right-text"> <span style="font-size: 14px; font-weight: bold; color: #555;">1800-123-456-22</span> <div class="clear" style=" height:3px;"></div> <span style="font-size: 14px; font-weight: bold; color: #555; ">[email protected]</span> </div> ``` And CSS: ``` div.logo-right-text{ margin: 0px 10px; } div.logo-right-text { float: right; text-align: right; } .logo-right-text{ padding-top: 42px; } ``` But finaly I'll try to put these 2 phone and mail in the menu line... if I find how to do ;)
264,328
<p>After updating to Woocommerce 3.0, in the Woocommerce ORDER page (where you can check all the orders made by customers, with order status, billing address, shipping address, total, etc.) is missing the column with the items purchased by the customer. Before WC update, that column was there. Now it is gone.</p> <p>Could anyone help me to add again this column?</p> <p>Thanks a lot!</p>
[ { "answer_id": 264329, "author": "Sender", "author_id": 118103, "author_profile": "https://wordpress.stackexchange.com/users/118103", "pm_score": 1, "selected": false, "text": "<p>I have already manage to create a column thanks to this:</p>\n\n<pre><code> // ADDING COLUMN TITLES\nadd_filter( 'manage_edit-shop_order_columns', 'custom_shop_order_column',11);\nfunction custom_shop_order_column($columns)\n{\n //add columns\n $columns['my-column1'] = __( 'Column Title','theme_slug');\n return $columns;\n}\n\n// adding the data for each orders by column (example)\nadd_action( 'manage_shop_order_posts_custom_column' , 'custom_orders_list_column_content', 10, 2 );\nfunction custom_orders_list_column_content( $column )\n{\n global $post, $woocommerce, $the_order;\n $order_id = $the_order-&gt;id;\n\n switch ( $column )\n {\n case 'my-column1' :\n $myVarOne = wc_get_order_item_meta( $order_id, '_the_meta_key1', true );\n echo $myVarOne;\n break;\n }\n</code></pre>\n\n<p>But I don't know how to add the data to this columns. I need to add the items purchased by the customers. Is it possible?</p>\n\n<p>Thanks!</p>\n" }, { "answer_id": 294576, "author": "Misha Rudrastyh", "author_id": 85985, "author_profile": "https://wordpress.stackexchange.com/users/85985", "pm_score": 0, "selected": false, "text": "<p>If you want to display the purchased products in a column, you can use this code:</p>\n\n<pre><code>add_action( 'manage_shop_order_posts_custom_column' , 'custom_orders_list_column_content', 10, 2 );\nfunction custom_orders_list_column_content( $column )\n{\n global $the_order;\n $order_id = $the_order-&gt;id;\n\n switch ( $column )\n {\n case 'my-column1' :\n $order_items = $the_order-&gt;get_items();\n foreach( $order_items as $myVarOne ) {\n echo $myVarOne['quantity'] .'&amp;nbsp;&amp;times;&amp;nbsp;'. $myVarOne['name'] .'&lt;br /&gt;';\n }\n break;\n }\n}\n</code></pre>\n\n<p>You can also view the complete code with screenshots in <a href=\"https://rudrastyh.com/woocommerce/columns.html#purchased_products_column\" rel=\"nofollow noreferrer\">this tutorial</a>.</p>\n" }, { "answer_id": 336355, "author": "Scotty G", "author_id": 166793, "author_profile": "https://wordpress.stackexchange.com/users/166793", "pm_score": 1, "selected": false, "text": "<p>I use this to add an <code>Ordered Products</code> column right after the <code>Date</code> column (fits nicely there). Each product is also linked to it's proper edit page.</p>\n\n<pre><code>// ----- add column to orders that shows which products were ordered -----\nfunction ec_order_items_column($columns) {\n $new_columns = array();\n foreach($columns as $key=&gt;$column){\n $new_columns[$key] = $columns[$key];\n if($key === 'order_date') {\n $new_columns['ordered_products'] = __('Ordered Products','woo-custom-ec');\n }\n }\n return $new_columns;\n\n //$columns['order_products'] = \"Purchased Items\";\n //return $columns;\n}\nadd_filter('manage_edit-shop_order_columns', 'ec_order_items_column', 99 );\n\n// ----- add data to new column that shows which products were ordered -----\nfunction ec_order_items_column_cnt($column) {\n global $the_order; // the global order object\n if($column == 'ordered_products') {\n // get items from the order global object\n $order_items = $the_order-&gt;get_items();\n if (!is_wp_error($order_items)) {\n foreach($order_items as $order_item) {\n echo $order_item['quantity'].'&amp;nbsp;&amp;times;&amp;nbsp;&lt;a href=\"'.admin_url('post.php?post='.$order_item['product_id'].'&amp;action=edit' ).'\"&gt;'.$order_item['name'].'&lt;/a&gt;&lt;br /&gt;';\n }\n }\n }\n}\nadd_action('manage_shop_order_posts_custom_column', 'ec_order_items_column_cnt', 99);\n</code></pre>\n\n<p><a href=\"https://i.stack.imgur.com/sIHFn.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/sIHFn.jpg\" alt=\"enter image description here\"></a></p>\n" } ]
2017/04/20
[ "https://wordpress.stackexchange.com/questions/264328", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/118103/" ]
After updating to Woocommerce 3.0, in the Woocommerce ORDER page (where you can check all the orders made by customers, with order status, billing address, shipping address, total, etc.) is missing the column with the items purchased by the customer. Before WC update, that column was there. Now it is gone. Could anyone help me to add again this column? Thanks a lot!
I have already manage to create a column thanks to this: ``` // ADDING COLUMN TITLES add_filter( 'manage_edit-shop_order_columns', 'custom_shop_order_column',11); function custom_shop_order_column($columns) { //add columns $columns['my-column1'] = __( 'Column Title','theme_slug'); return $columns; } // adding the data for each orders by column (example) add_action( 'manage_shop_order_posts_custom_column' , 'custom_orders_list_column_content', 10, 2 ); function custom_orders_list_column_content( $column ) { global $post, $woocommerce, $the_order; $order_id = $the_order->id; switch ( $column ) { case 'my-column1' : $myVarOne = wc_get_order_item_meta( $order_id, '_the_meta_key1', true ); echo $myVarOne; break; } ``` But I don't know how to add the data to this columns. I need to add the items purchased by the customers. Is it possible? Thanks!
264,338
<p>I'm trying to alter a plugin with this line:</p> <pre><code>wp_enqueue_script($this-&gt;_token . '-admin', esc_url($this-&gt;assets_url) . 'js/admin' . $this-&gt;script_suffix . '.js, $scripts, $this-&gt;_version); </code></pre> <p>When I print $this->_version it comes up as '3.0.0' but when the admin.js is printed it comes along as</p> <pre><code>&lt;script type="text/javascript" src="localhost/wp-content/plugins/woocommerce-customer-relationship-manager/assets/js/admin.js"&gt;&lt;/script&gt; </code></pre> <p>Is there any hook that could be preventing the version to be printed?, or any other setting I should be looking for?</p>
[ { "answer_id": 264329, "author": "Sender", "author_id": 118103, "author_profile": "https://wordpress.stackexchange.com/users/118103", "pm_score": 1, "selected": false, "text": "<p>I have already manage to create a column thanks to this:</p>\n\n<pre><code> // ADDING COLUMN TITLES\nadd_filter( 'manage_edit-shop_order_columns', 'custom_shop_order_column',11);\nfunction custom_shop_order_column($columns)\n{\n //add columns\n $columns['my-column1'] = __( 'Column Title','theme_slug');\n return $columns;\n}\n\n// adding the data for each orders by column (example)\nadd_action( 'manage_shop_order_posts_custom_column' , 'custom_orders_list_column_content', 10, 2 );\nfunction custom_orders_list_column_content( $column )\n{\n global $post, $woocommerce, $the_order;\n $order_id = $the_order-&gt;id;\n\n switch ( $column )\n {\n case 'my-column1' :\n $myVarOne = wc_get_order_item_meta( $order_id, '_the_meta_key1', true );\n echo $myVarOne;\n break;\n }\n</code></pre>\n\n<p>But I don't know how to add the data to this columns. I need to add the items purchased by the customers. Is it possible?</p>\n\n<p>Thanks!</p>\n" }, { "answer_id": 294576, "author": "Misha Rudrastyh", "author_id": 85985, "author_profile": "https://wordpress.stackexchange.com/users/85985", "pm_score": 0, "selected": false, "text": "<p>If you want to display the purchased products in a column, you can use this code:</p>\n\n<pre><code>add_action( 'manage_shop_order_posts_custom_column' , 'custom_orders_list_column_content', 10, 2 );\nfunction custom_orders_list_column_content( $column )\n{\n global $the_order;\n $order_id = $the_order-&gt;id;\n\n switch ( $column )\n {\n case 'my-column1' :\n $order_items = $the_order-&gt;get_items();\n foreach( $order_items as $myVarOne ) {\n echo $myVarOne['quantity'] .'&amp;nbsp;&amp;times;&amp;nbsp;'. $myVarOne['name'] .'&lt;br /&gt;';\n }\n break;\n }\n}\n</code></pre>\n\n<p>You can also view the complete code with screenshots in <a href=\"https://rudrastyh.com/woocommerce/columns.html#purchased_products_column\" rel=\"nofollow noreferrer\">this tutorial</a>.</p>\n" }, { "answer_id": 336355, "author": "Scotty G", "author_id": 166793, "author_profile": "https://wordpress.stackexchange.com/users/166793", "pm_score": 1, "selected": false, "text": "<p>I use this to add an <code>Ordered Products</code> column right after the <code>Date</code> column (fits nicely there). Each product is also linked to it's proper edit page.</p>\n\n<pre><code>// ----- add column to orders that shows which products were ordered -----\nfunction ec_order_items_column($columns) {\n $new_columns = array();\n foreach($columns as $key=&gt;$column){\n $new_columns[$key] = $columns[$key];\n if($key === 'order_date') {\n $new_columns['ordered_products'] = __('Ordered Products','woo-custom-ec');\n }\n }\n return $new_columns;\n\n //$columns['order_products'] = \"Purchased Items\";\n //return $columns;\n}\nadd_filter('manage_edit-shop_order_columns', 'ec_order_items_column', 99 );\n\n// ----- add data to new column that shows which products were ordered -----\nfunction ec_order_items_column_cnt($column) {\n global $the_order; // the global order object\n if($column == 'ordered_products') {\n // get items from the order global object\n $order_items = $the_order-&gt;get_items();\n if (!is_wp_error($order_items)) {\n foreach($order_items as $order_item) {\n echo $order_item['quantity'].'&amp;nbsp;&amp;times;&amp;nbsp;&lt;a href=\"'.admin_url('post.php?post='.$order_item['product_id'].'&amp;action=edit' ).'\"&gt;'.$order_item['name'].'&lt;/a&gt;&lt;br /&gt;';\n }\n }\n }\n}\nadd_action('manage_shop_order_posts_custom_column', 'ec_order_items_column_cnt', 99);\n</code></pre>\n\n<p><a href=\"https://i.stack.imgur.com/sIHFn.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/sIHFn.jpg\" alt=\"enter image description here\"></a></p>\n" } ]
2017/04/21
[ "https://wordpress.stackexchange.com/questions/264338", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/116224/" ]
I'm trying to alter a plugin with this line: ``` wp_enqueue_script($this->_token . '-admin', esc_url($this->assets_url) . 'js/admin' . $this->script_suffix . '.js, $scripts, $this->_version); ``` When I print $this->\_version it comes up as '3.0.0' but when the admin.js is printed it comes along as ``` <script type="text/javascript" src="localhost/wp-content/plugins/woocommerce-customer-relationship-manager/assets/js/admin.js"></script> ``` Is there any hook that could be preventing the version to be printed?, or any other setting I should be looking for?
I have already manage to create a column thanks to this: ``` // ADDING COLUMN TITLES add_filter( 'manage_edit-shop_order_columns', 'custom_shop_order_column',11); function custom_shop_order_column($columns) { //add columns $columns['my-column1'] = __( 'Column Title','theme_slug'); return $columns; } // adding the data for each orders by column (example) add_action( 'manage_shop_order_posts_custom_column' , 'custom_orders_list_column_content', 10, 2 ); function custom_orders_list_column_content( $column ) { global $post, $woocommerce, $the_order; $order_id = $the_order->id; switch ( $column ) { case 'my-column1' : $myVarOne = wc_get_order_item_meta( $order_id, '_the_meta_key1', true ); echo $myVarOne; break; } ``` But I don't know how to add the data to this columns. I need to add the items purchased by the customers. Is it possible? Thanks!
264,340
<p>In my most recent project, I'm dealing with a website that included dozens of custom taxonomies, couple of post types, content, etc. and required different templates for different authors or tags.</p> <p>Right now, my template folder has about 70 php files for templates, which is really confusing. </p> <p>I noticed that some themes such as twentyseven manage to store template files in folders and call them in a loop as the following:</p> <p><code>get_template_part( 'template-parts/post/content', get_post_format() );</code></p> <p>But this is in the loop. My templates are entirely different so i can't use the above solution, because i will need to use conditionals for altering anything that is not part of the loop.</p> <p>For example, if i have 3 post types, i have to save 3 template files:</p> <p><code>single-type1.php</code>, <code>single-type2.php</code> and <code>single-type3.php</code>.</p> <p>These templates are entirely different, both in or outside the loop (even different sidebars), so i can't just make a <code>single.php</code> and call the appropriate post type in the loop.</p> <p>Is there anyway to address WordPress about custom template files other than just saving it directly inside the theme's folder?</p>
[ { "answer_id": 264342, "author": "Dave Romsey", "author_id": 2807, "author_profile": "https://wordpress.stackexchange.com/users/2807", "pm_score": 3, "selected": true, "text": "<p>Page templates can be stored within the <code>page-templates</code> or <code>templates</code> subdirectory within a theme, but this does not apply to custom post type or taxonomy templates.</p>\n\n<p>Fortunately, the <code>template_include</code> filter can be used to change the template that will be loaded. In the example below, template files are stored in the <code>/theme-name/templates/</code> directory.</p>\n\n<pre><code>/**\n * Filters the path of the current template before including it.\n * @param string $template The path of the template to include.\n */\nadd_filter( 'template_include', 'wpse_template_include' );\nfunction wpse_template_include( $template ) {\n // Handle taxonomy templates.\n $taxonomy = get_query_var( 'taxonomy' );\n if ( is_tax() &amp;&amp; $taxonomy ) {\n $file = get_theme_file_path() . '/templates/taxonomy-' . $taxonomy . '.php';\n if ( file_exists( $file ) ) {\n $template = $file;\n } \n }\n\n\n // Handle post type archives and singular templates.\n $post_type = get_post_type();\n if ( ! $post_type ) {\n return $template;\n }\n\n if ( is_archive() ) {\n $file = get_theme_file_path() . '/templates/archive-' . $post_type . '.php';\n if ( file_exists( $file ) ) {\n $template = $file;\n }\n }\n\n if ( is_singular() ) {\n $file = get_theme_file_path() . '/templates/single-' . $post_type . '.php';\n if ( file_exists( $file ) ) {\n $template = $file;\n }\n }\n\n return $template;\n}\n</code></pre>\n" }, { "answer_id": 264360, "author": "Dev", "author_id": 104464, "author_profile": "https://wordpress.stackexchange.com/users/104464", "pm_score": 2, "selected": false, "text": "<p>You could use 1 template for all taxonomies and name it taxonomy.php or use template_include in your functions file.</p>\n\n<pre><code>add_filter( 'template_include', 'tax_page_template', 99 );\n\nfunction tax_page_template( $template ) {\n\n if ( is_tax( 'taxonomy' ) ) {\n $new_template = locate_template( array( 'your-tax.php' ) );\n if ( '' != $new_template ) {\n return $new_template ;\n }\n }\n\n return $template;\n}\n</code></pre>\n\n<p>Depending on which theme you are using, you could also use 1 template vis the Page Attributes > Templates drop down menu and modify each template using theme settings.</p>\n" } ]
2017/04/21
[ "https://wordpress.stackexchange.com/questions/264340", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/94498/" ]
In my most recent project, I'm dealing with a website that included dozens of custom taxonomies, couple of post types, content, etc. and required different templates for different authors or tags. Right now, my template folder has about 70 php files for templates, which is really confusing. I noticed that some themes such as twentyseven manage to store template files in folders and call them in a loop as the following: `get_template_part( 'template-parts/post/content', get_post_format() );` But this is in the loop. My templates are entirely different so i can't use the above solution, because i will need to use conditionals for altering anything that is not part of the loop. For example, if i have 3 post types, i have to save 3 template files: `single-type1.php`, `single-type2.php` and `single-type3.php`. These templates are entirely different, both in or outside the loop (even different sidebars), so i can't just make a `single.php` and call the appropriate post type in the loop. Is there anyway to address WordPress about custom template files other than just saving it directly inside the theme's folder?
Page templates can be stored within the `page-templates` or `templates` subdirectory within a theme, but this does not apply to custom post type or taxonomy templates. Fortunately, the `template_include` filter can be used to change the template that will be loaded. In the example below, template files are stored in the `/theme-name/templates/` directory. ``` /** * Filters the path of the current template before including it. * @param string $template The path of the template to include. */ add_filter( 'template_include', 'wpse_template_include' ); function wpse_template_include( $template ) { // Handle taxonomy templates. $taxonomy = get_query_var( 'taxonomy' ); if ( is_tax() && $taxonomy ) { $file = get_theme_file_path() . '/templates/taxonomy-' . $taxonomy . '.php'; if ( file_exists( $file ) ) { $template = $file; } } // Handle post type archives and singular templates. $post_type = get_post_type(); if ( ! $post_type ) { return $template; } if ( is_archive() ) { $file = get_theme_file_path() . '/templates/archive-' . $post_type . '.php'; if ( file_exists( $file ) ) { $template = $file; } } if ( is_singular() ) { $file = get_theme_file_path() . '/templates/single-' . $post_type . '.php'; if ( file_exists( $file ) ) { $template = $file; } } return $template; } ```
264,346
<p>I've uploaded several images to my blog posts. I didn't cared about their size so I've put there even 5mb images which could be easily compressed for 200kb. I know that wordpress already processed them, cutted and customized, but now I'm worried as my whole blog is very big. </p> <p>I would like to delete originals or at least replace them with compressed copies. </p> <p>Can I do it manually, download, delete, compress and upload with the same name ? </p> <p>or </p> <p>Is there any simple plugin which will do the same for me ? </p> <p>Thank you! </p>
[ { "answer_id": 264342, "author": "Dave Romsey", "author_id": 2807, "author_profile": "https://wordpress.stackexchange.com/users/2807", "pm_score": 3, "selected": true, "text": "<p>Page templates can be stored within the <code>page-templates</code> or <code>templates</code> subdirectory within a theme, but this does not apply to custom post type or taxonomy templates.</p>\n\n<p>Fortunately, the <code>template_include</code> filter can be used to change the template that will be loaded. In the example below, template files are stored in the <code>/theme-name/templates/</code> directory.</p>\n\n<pre><code>/**\n * Filters the path of the current template before including it.\n * @param string $template The path of the template to include.\n */\nadd_filter( 'template_include', 'wpse_template_include' );\nfunction wpse_template_include( $template ) {\n // Handle taxonomy templates.\n $taxonomy = get_query_var( 'taxonomy' );\n if ( is_tax() &amp;&amp; $taxonomy ) {\n $file = get_theme_file_path() . '/templates/taxonomy-' . $taxonomy . '.php';\n if ( file_exists( $file ) ) {\n $template = $file;\n } \n }\n\n\n // Handle post type archives and singular templates.\n $post_type = get_post_type();\n if ( ! $post_type ) {\n return $template;\n }\n\n if ( is_archive() ) {\n $file = get_theme_file_path() . '/templates/archive-' . $post_type . '.php';\n if ( file_exists( $file ) ) {\n $template = $file;\n }\n }\n\n if ( is_singular() ) {\n $file = get_theme_file_path() . '/templates/single-' . $post_type . '.php';\n if ( file_exists( $file ) ) {\n $template = $file;\n }\n }\n\n return $template;\n}\n</code></pre>\n" }, { "answer_id": 264360, "author": "Dev", "author_id": 104464, "author_profile": "https://wordpress.stackexchange.com/users/104464", "pm_score": 2, "selected": false, "text": "<p>You could use 1 template for all taxonomies and name it taxonomy.php or use template_include in your functions file.</p>\n\n<pre><code>add_filter( 'template_include', 'tax_page_template', 99 );\n\nfunction tax_page_template( $template ) {\n\n if ( is_tax( 'taxonomy' ) ) {\n $new_template = locate_template( array( 'your-tax.php' ) );\n if ( '' != $new_template ) {\n return $new_template ;\n }\n }\n\n return $template;\n}\n</code></pre>\n\n<p>Depending on which theme you are using, you could also use 1 template vis the Page Attributes > Templates drop down menu and modify each template using theme settings.</p>\n" } ]
2017/04/21
[ "https://wordpress.stackexchange.com/questions/264346", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/111175/" ]
I've uploaded several images to my blog posts. I didn't cared about their size so I've put there even 5mb images which could be easily compressed for 200kb. I know that wordpress already processed them, cutted and customized, but now I'm worried as my whole blog is very big. I would like to delete originals or at least replace them with compressed copies. Can I do it manually, download, delete, compress and upload with the same name ? or Is there any simple plugin which will do the same for me ? Thank you!
Page templates can be stored within the `page-templates` or `templates` subdirectory within a theme, but this does not apply to custom post type or taxonomy templates. Fortunately, the `template_include` filter can be used to change the template that will be loaded. In the example below, template files are stored in the `/theme-name/templates/` directory. ``` /** * Filters the path of the current template before including it. * @param string $template The path of the template to include. */ add_filter( 'template_include', 'wpse_template_include' ); function wpse_template_include( $template ) { // Handle taxonomy templates. $taxonomy = get_query_var( 'taxonomy' ); if ( is_tax() && $taxonomy ) { $file = get_theme_file_path() . '/templates/taxonomy-' . $taxonomy . '.php'; if ( file_exists( $file ) ) { $template = $file; } } // Handle post type archives and singular templates. $post_type = get_post_type(); if ( ! $post_type ) { return $template; } if ( is_archive() ) { $file = get_theme_file_path() . '/templates/archive-' . $post_type . '.php'; if ( file_exists( $file ) ) { $template = $file; } } if ( is_singular() ) { $file = get_theme_file_path() . '/templates/single-' . $post_type . '.php'; if ( file_exists( $file ) ) { $template = $file; } } return $template; } ```
264,355
<p>I am using Enough theme and i want to create a child theme the way suggested in codex i.e. using wp_enqueue_style. I am doing it the way it's explained but left margin more now like it's indented to right. Seems to me some stylesheet loading problem. </p> <p>I have created style.css and functions.php in child theme folder. In parent theme folder there is 1 style.css file and 11 css file inside '/css' directory.</p> <p>I have tried lot of things but not able to do it correctly. Below is how i am trying to load parent theme style sheets.</p> <pre><code>&lt;?php add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' ); function my_theme_enqueue_styles() { wp_enqueue_style( 'styles', get_template_directory_uri() . '/style.css' ); wp_enqueue_style( 'styles', get_template_directory_uri() . '/css/admin-options.css' ); wp_enqueue_style( 'styles', get_template_directory_uri() . '/css/base.css' ); wp_enqueue_style( 'styles', get_template_directory_uri() . '/css/colors.css' ); wp_enqueue_style( 'styles', get_template_directory_uri() . '/css/box-modules.css' ); wp_enqueue_style( 'styles', get_template_directory_uri() . '/css/approach.css' ); wp_enqueue_style( 'styles', get_template_directory_uri() . '/css/comment.css' ); wp_enqueue_style( 'styles', get_template_directory_uri() . '/css/fonts.css' ); wp_enqueue_style( 'styles', get_template_directory_uri() . '/css/layout-fluid.css' ); wp_enqueue_style( 'styles', get_template_directory_uri() . '/css/normalize.css' ); wp_enqueue_style( 'styles', get_template_directory_uri() . '/css/post-format.css' ); wp_enqueue_style( 'styles', get_template_directory_uri() . '/css/ua.css' ); } ?&gt; </code></pre> <p>I am using 'style' as first parameter because in the functions.php in parent theme i.i Enough i have following code, (I have put a line with arrow ------------> in front of the the code line) -</p> <pre><code>/** * * */ if ( !function_exists( "enough_enqueue_scripts_styles" ) ) { function enough_enqueue_scripts_styles() { global $is_IE, $enough_version; $enough_csses = array( "css/normalize.css", "genericons/genericons.css", "css/fonts.css", "css/box-modules.css", "css/comment.css", "css/ua.css", "css/colors.css", "css/base.css", "css/layout-fluid.css", "css/post-format.css", "css/approach.css" ); foreach ( $enough_csses as $ecnough_css_path ) { if ( file_exists( trailingslashit( get_stylesheet_directory() ) . $ecnough_css_path ) ) { wp_enqueue_style( 'enough_' . basename( $ecnough_css_path, '.css' ), trailingslashit( get_stylesheet_directory_uri() ) . $ecnough_css_path, array(), $enough_version ); } else { wp_enqueue_style( 'enough_' . basename( $ecnough_css_path, '.css' ), trailingslashit( get_template_directory_uri() ) . $ecnough_css_path, array(), $enough_version ); } } -----------&gt;wp_enqueue_style( 'styles', get_stylesheet_uri(), array( 'enough_approach' ), $enough_version ); $gallery_style = enough_gallerys_css(); wp_add_inline_style( 'styles', $gallery_style ); wp_enqueue_style( 'enough-web-font', apply_filters( 'enough_web_font', '//fonts.googleapis.com/css?family=Ubuntu:400,700' ) ); wp_enqueue_script( 'jquery' ); wp_enqueue_script( 'comment-reply' ); if ( $is_IE ) { wp_register_script( 'html5shiv', get_template_directory_uri() . '/inc/html5shiv.js', array(), '3', false ); wp_enqueue_script( 'html5shiv' ); } } } </code></pre> <p>Do i need to create all css files in child themes ? or I can have only 1 css file namely style.css in child theme ? What would be the correct way of doing this ? </p> <p><strong>Edited this way</strong> </p> <pre><code>&lt;?php add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' ); function my_theme_enqueue_styles() { wp_enqueue_style( 'parent-style', get_template_directory_uri() . '/style.css' ); wp_enqueue_style( 'style1', get_template_directory_uri() . '/css/admin-options.css' ); wp_enqueue_style( 'style2', get_template_directory_uri() . '/css/base.css' ); wp_enqueue_style( 'style3', get_template_directory_uri() . '/css/colors.css' ); wp_enqueue_style( 'style4', get_template_directory_uri() . '/css/box-modules.css' ); wp_enqueue_style( 'style5', get_template_directory_uri() . '/css/approach.css' ); wp_enqueue_style( 'style6', get_template_directory_uri() . '/css/comment.css' ); wp_enqueue_style( 'style7', get_template_directory_uri() . '/css/fonts.css' ); wp_enqueue_style( 'style8', get_template_directory_uri() . '/css/layout-fluid.css' ); wp_enqueue_style( 'style9', get_template_directory_uri() . '/css/normalize.css' ); wp_enqueue_style( 'style10', get_template_directory_uri() . '/css/post-format.css' ); wp_enqueue_style( 'style11', get_template_directory_uri() . '/css/ua.css' ); } ?&gt; </code></pre> <p>And here is <strong>style.css</strong> in child theme</p> <pre><code>/* Theme Name: Enough Child Theme URI: http://www.tenman.info/wp3/enough/ Description: Satisfied enough necessary minimum structure Responsive Theme. HTML5 , Supports Post Format Archives , You can select your favorite Post Format Author: Tenman Author URI: http://www.tenman.info/wp3/ Version: 1.22 Tags: two-columns,custom-colors, custom-header, custom-background, custom-menu, editor-style, threaded-comments, sticky-post, flexible-header Template: enough Text Domain: enough-child License: GNU General Public License v2.0 License URI: http://www.gnu.org/licenses/gpl-2.0.html */ </code></pre> <p>The images _</p> <p><a href="https://i.stack.imgur.com/6hHRb.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6hHRb.png" alt="Parent Enough"></a> <a href="https://i.stack.imgur.com/fQM14.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/fQM14.png" alt="enter image description here"></a></p>
[ { "answer_id": 264361, "author": "sorrow poetry", "author_id": 106011, "author_profile": "https://wordpress.stackexchange.com/users/106011", "pm_score": 1, "selected": false, "text": "<p>about styles you need to specify a name for each style the cant be the same and its necessary if you are overwriting it in your child and you want the parent styles to come before overwriting.</p>\n\n<p>so if you want to your parents <code>style.css</code> loads after your childs <code>style.css</code> you need to queue it in your <code>functions.php</code> file so add this in your child themes <code>functions.php</code>:</p>\n\n<pre><code>&lt;?php\nfunction my_theme_enqueue_styles() {\n\n $parent_style = 'enough_style'; // needs to be same as parent style\n\n wp_enqueue_style( $parent_style, get_template_directory_uri() . '/style.css');\n}\nadd_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles',100 ); //it will be queued after base.css and overwrites it\n?&gt;\n</code></pre>\n\n<p>i tested this code and it works well now. your <code>style.css</code> is ok and u dont need to change it.</p>\n" }, { "answer_id": 264365, "author": "Vinod Dalvi", "author_id": 14347, "author_profile": "https://wordpress.stackexchange.com/users/14347", "pm_score": 1, "selected": true, "text": "<p>It is very best described in the WordPress <a href=\"https://codex.wordpress.org/Child_Themes\" rel=\"nofollow noreferrer\">Child theme codex</a> page.</p>\n\n<p>Basically to load child theme and parent theme stylesheet files, you have to just add following code in the functions.php file of your child theme.</p>\n\n<p>\n\n<pre><code>function my_theme_enqueue_styles() {\n\n $parent_style = 'parent-style';\n\n wp_enqueue_style( $parent_style, get_template_directory_uri() . '/style.css' );\n wp_enqueue_style( 'styles',\n get_stylesheet_directory_uri() . '/style.css',\n array( $parent_style, 'enough_base' ),\n wp_get_theme()-&gt;get('Version')\n );\n}\nadd_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles', 99 );\n</code></pre>\n\n<p>You don't need to enqueue other parent theme CSS files if you are not changing them.</p>\n" } ]
2017/04/21
[ "https://wordpress.stackexchange.com/questions/264355", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/118115/" ]
I am using Enough theme and i want to create a child theme the way suggested in codex i.e. using wp\_enqueue\_style. I am doing it the way it's explained but left margin more now like it's indented to right. Seems to me some stylesheet loading problem. I have created style.css and functions.php in child theme folder. In parent theme folder there is 1 style.css file and 11 css file inside '/css' directory. I have tried lot of things but not able to do it correctly. Below is how i am trying to load parent theme style sheets. ``` <?php add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' ); function my_theme_enqueue_styles() { wp_enqueue_style( 'styles', get_template_directory_uri() . '/style.css' ); wp_enqueue_style( 'styles', get_template_directory_uri() . '/css/admin-options.css' ); wp_enqueue_style( 'styles', get_template_directory_uri() . '/css/base.css' ); wp_enqueue_style( 'styles', get_template_directory_uri() . '/css/colors.css' ); wp_enqueue_style( 'styles', get_template_directory_uri() . '/css/box-modules.css' ); wp_enqueue_style( 'styles', get_template_directory_uri() . '/css/approach.css' ); wp_enqueue_style( 'styles', get_template_directory_uri() . '/css/comment.css' ); wp_enqueue_style( 'styles', get_template_directory_uri() . '/css/fonts.css' ); wp_enqueue_style( 'styles', get_template_directory_uri() . '/css/layout-fluid.css' ); wp_enqueue_style( 'styles', get_template_directory_uri() . '/css/normalize.css' ); wp_enqueue_style( 'styles', get_template_directory_uri() . '/css/post-format.css' ); wp_enqueue_style( 'styles', get_template_directory_uri() . '/css/ua.css' ); } ?> ``` I am using 'style' as first parameter because in the functions.php in parent theme i.i Enough i have following code, (I have put a line with arrow ------------> in front of the the code line) - ``` /** * * */ if ( !function_exists( "enough_enqueue_scripts_styles" ) ) { function enough_enqueue_scripts_styles() { global $is_IE, $enough_version; $enough_csses = array( "css/normalize.css", "genericons/genericons.css", "css/fonts.css", "css/box-modules.css", "css/comment.css", "css/ua.css", "css/colors.css", "css/base.css", "css/layout-fluid.css", "css/post-format.css", "css/approach.css" ); foreach ( $enough_csses as $ecnough_css_path ) { if ( file_exists( trailingslashit( get_stylesheet_directory() ) . $ecnough_css_path ) ) { wp_enqueue_style( 'enough_' . basename( $ecnough_css_path, '.css' ), trailingslashit( get_stylesheet_directory_uri() ) . $ecnough_css_path, array(), $enough_version ); } else { wp_enqueue_style( 'enough_' . basename( $ecnough_css_path, '.css' ), trailingslashit( get_template_directory_uri() ) . $ecnough_css_path, array(), $enough_version ); } } ----------->wp_enqueue_style( 'styles', get_stylesheet_uri(), array( 'enough_approach' ), $enough_version ); $gallery_style = enough_gallerys_css(); wp_add_inline_style( 'styles', $gallery_style ); wp_enqueue_style( 'enough-web-font', apply_filters( 'enough_web_font', '//fonts.googleapis.com/css?family=Ubuntu:400,700' ) ); wp_enqueue_script( 'jquery' ); wp_enqueue_script( 'comment-reply' ); if ( $is_IE ) { wp_register_script( 'html5shiv', get_template_directory_uri() . '/inc/html5shiv.js', array(), '3', false ); wp_enqueue_script( 'html5shiv' ); } } } ``` Do i need to create all css files in child themes ? or I can have only 1 css file namely style.css in child theme ? What would be the correct way of doing this ? **Edited this way** ``` <?php add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' ); function my_theme_enqueue_styles() { wp_enqueue_style( 'parent-style', get_template_directory_uri() . '/style.css' ); wp_enqueue_style( 'style1', get_template_directory_uri() . '/css/admin-options.css' ); wp_enqueue_style( 'style2', get_template_directory_uri() . '/css/base.css' ); wp_enqueue_style( 'style3', get_template_directory_uri() . '/css/colors.css' ); wp_enqueue_style( 'style4', get_template_directory_uri() . '/css/box-modules.css' ); wp_enqueue_style( 'style5', get_template_directory_uri() . '/css/approach.css' ); wp_enqueue_style( 'style6', get_template_directory_uri() . '/css/comment.css' ); wp_enqueue_style( 'style7', get_template_directory_uri() . '/css/fonts.css' ); wp_enqueue_style( 'style8', get_template_directory_uri() . '/css/layout-fluid.css' ); wp_enqueue_style( 'style9', get_template_directory_uri() . '/css/normalize.css' ); wp_enqueue_style( 'style10', get_template_directory_uri() . '/css/post-format.css' ); wp_enqueue_style( 'style11', get_template_directory_uri() . '/css/ua.css' ); } ?> ``` And here is **style.css** in child theme ``` /* Theme Name: Enough Child Theme URI: http://www.tenman.info/wp3/enough/ Description: Satisfied enough necessary minimum structure Responsive Theme. HTML5 , Supports Post Format Archives , You can select your favorite Post Format Author: Tenman Author URI: http://www.tenman.info/wp3/ Version: 1.22 Tags: two-columns,custom-colors, custom-header, custom-background, custom-menu, editor-style, threaded-comments, sticky-post, flexible-header Template: enough Text Domain: enough-child License: GNU General Public License v2.0 License URI: http://www.gnu.org/licenses/gpl-2.0.html */ ``` The images \_ [![Parent Enough](https://i.stack.imgur.com/6hHRb.png)](https://i.stack.imgur.com/6hHRb.png) [![enter image description here](https://i.stack.imgur.com/fQM14.png)](https://i.stack.imgur.com/fQM14.png)
It is very best described in the WordPress [Child theme codex](https://codex.wordpress.org/Child_Themes) page. Basically to load child theme and parent theme stylesheet files, you have to just add following code in the functions.php file of your child theme. ``` function my_theme_enqueue_styles() { $parent_style = 'parent-style'; wp_enqueue_style( $parent_style, get_template_directory_uri() . '/style.css' ); wp_enqueue_style( 'styles', get_stylesheet_directory_uri() . '/style.css', array( $parent_style, 'enough_base' ), wp_get_theme()->get('Version') ); } add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles', 99 ); ``` You don't need to enqueue other parent theme CSS files if you are not changing them.
264,363
<p>What's the best way to set the <code>required</code> atribute on html forms in wordpress, for instance I would like post-content to be required, so this code need to be changed:</p> <pre><code>&lt;textarea class="wp-editor-area" style="height: 300px; margin-top: 37px;" autocomplete="off" cols="40" name="content" id="content"&gt;&lt;/textarea&gt; </code></pre> <p>To appear like this:</p> <pre><code>&lt;textarea required class="wp-editor-area" style="height: 300px; margin-top: 37px;" autocomplete="off" cols="40" name="content" id="content"&gt;&lt;/textarea&gt; </code></pre> <p>How can do it by a filter or action hook? This same solution I will also use it for other fields in the publish post form.</p> <p>What I want is to add the HTML5 <code>required</code> attribute on certain fields, once the page has been rendered.</p> <p><a href="https://www.w3schools.com/tags/att_input_required.asp" rel="nofollow noreferrer">https://www.w3schools.com/tags/att_input_required.asp</a> <a href="https://www.w3schools.com/tags/att_textarea_required.asp" rel="nofollow noreferrer">https://www.w3schools.com/tags/att_textarea_required.asp</a></p>
[ { "answer_id": 264399, "author": "JItendra Rana", "author_id": 87433, "author_profile": "https://wordpress.stackexchange.com/users/87433", "pm_score": 2, "selected": false, "text": "<p>Don't rely entirely on JavaScript validations. Use below hook for Server side validation. </p>\n\n<pre><code>function check_if_post_content_set( $maybe_empty, $postarr ) {\n// Check if post is already created. IMPORTANT\nif($postarr['ID'] &amp;&amp; (int)$postarr['ID'] &gt; 0){\n if( !$postarr['post_content'] OR $postarr['post_content'] == '' OR $postarr['post_content'] == NULL ){\n $maybe_empty = true;\n }\n}\nreturn $maybe_empty;\n}\nadd_filter( 'wp_insert_post_empty_content', 'check_if_post_content_set', 999999, 2 );\n</code></pre>\n" }, { "answer_id": 264461, "author": "TorryVic", "author_id": 116259, "author_profile": "https://wordpress.stackexchange.com/users/116259", "pm_score": 1, "selected": true, "text": "<p>Finally I have solved it as follows:</p>\n\n<pre><code>add_action( 'admin_enqueue_scripts', array($this, 'my_admin_scripts') );\n\nfunction my_admin_scripts($page) {\n global $post;\n\n if ($page == \"post-new.php\" OR $page == \"post.php\") {\n wp_register_script( 'my-custom-admin-scripts', plugins_url('/js/my-admin-post.js',dirname(__FILE__)), array('jquery', 'jquery-ui-sortable' ) , null, true );\n wp_enqueue_script( 'my-custom-admin-scripts' ); \n } \n}\n</code></pre>\n\n<p>And put the required atribute by JQuery in the next js code (/js/my-admin-post.js):</p>\n\n<pre><code>// JavaScript Document\njQuery(document).ready(function($) {\n $('#title').attr('required', true);\n $('#content').attr('required', true);\n $('#_my_custom_field').attr('required', true); \n});\n</code></pre>\n" } ]
2017/04/21
[ "https://wordpress.stackexchange.com/questions/264363", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/116259/" ]
What's the best way to set the `required` atribute on html forms in wordpress, for instance I would like post-content to be required, so this code need to be changed: ``` <textarea class="wp-editor-area" style="height: 300px; margin-top: 37px;" autocomplete="off" cols="40" name="content" id="content"></textarea> ``` To appear like this: ``` <textarea required class="wp-editor-area" style="height: 300px; margin-top: 37px;" autocomplete="off" cols="40" name="content" id="content"></textarea> ``` How can do it by a filter or action hook? This same solution I will also use it for other fields in the publish post form. What I want is to add the HTML5 `required` attribute on certain fields, once the page has been rendered. <https://www.w3schools.com/tags/att_input_required.asp> <https://www.w3schools.com/tags/att_textarea_required.asp>
Finally I have solved it as follows: ``` add_action( 'admin_enqueue_scripts', array($this, 'my_admin_scripts') ); function my_admin_scripts($page) { global $post; if ($page == "post-new.php" OR $page == "post.php") { wp_register_script( 'my-custom-admin-scripts', plugins_url('/js/my-admin-post.js',dirname(__FILE__)), array('jquery', 'jquery-ui-sortable' ) , null, true ); wp_enqueue_script( 'my-custom-admin-scripts' ); } } ``` And put the required atribute by JQuery in the next js code (/js/my-admin-post.js): ``` // JavaScript Document jQuery(document).ready(function($) { $('#title').attr('required', true); $('#content').attr('required', true); $('#_my_custom_field').attr('required', true); }); ```
264,366
<p>I'm facing a serious problem , I have to get some posts from wordpress website to my ionic app , so I activated the json api for wordpress but when I try to get specefic posts I can't find them in the json file. this is the website <a href="http://www.jneyne.com" rel="nofollow noreferrer">http://www.jneyne.com</a> and those are the posts(Dar Boumakhlouf,Dar Gaïa...) <a href="http://www.jneyne.com/accommodation/" rel="nofollow noreferrer">http://www.jneyne.com/accommodation/</a></p>
[ { "answer_id": 264399, "author": "JItendra Rana", "author_id": 87433, "author_profile": "https://wordpress.stackexchange.com/users/87433", "pm_score": 2, "selected": false, "text": "<p>Don't rely entirely on JavaScript validations. Use below hook for Server side validation. </p>\n\n<pre><code>function check_if_post_content_set( $maybe_empty, $postarr ) {\n// Check if post is already created. IMPORTANT\nif($postarr['ID'] &amp;&amp; (int)$postarr['ID'] &gt; 0){\n if( !$postarr['post_content'] OR $postarr['post_content'] == '' OR $postarr['post_content'] == NULL ){\n $maybe_empty = true;\n }\n}\nreturn $maybe_empty;\n}\nadd_filter( 'wp_insert_post_empty_content', 'check_if_post_content_set', 999999, 2 );\n</code></pre>\n" }, { "answer_id": 264461, "author": "TorryVic", "author_id": 116259, "author_profile": "https://wordpress.stackexchange.com/users/116259", "pm_score": 1, "selected": true, "text": "<p>Finally I have solved it as follows:</p>\n\n<pre><code>add_action( 'admin_enqueue_scripts', array($this, 'my_admin_scripts') );\n\nfunction my_admin_scripts($page) {\n global $post;\n\n if ($page == \"post-new.php\" OR $page == \"post.php\") {\n wp_register_script( 'my-custom-admin-scripts', plugins_url('/js/my-admin-post.js',dirname(__FILE__)), array('jquery', 'jquery-ui-sortable' ) , null, true );\n wp_enqueue_script( 'my-custom-admin-scripts' ); \n } \n}\n</code></pre>\n\n<p>And put the required atribute by JQuery in the next js code (/js/my-admin-post.js):</p>\n\n<pre><code>// JavaScript Document\njQuery(document).ready(function($) {\n $('#title').attr('required', true);\n $('#content').attr('required', true);\n $('#_my_custom_field').attr('required', true); \n});\n</code></pre>\n" } ]
2017/04/21
[ "https://wordpress.stackexchange.com/questions/264366", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/118128/" ]
I'm facing a serious problem , I have to get some posts from wordpress website to my ionic app , so I activated the json api for wordpress but when I try to get specefic posts I can't find them in the json file. this is the website <http://www.jneyne.com> and those are the posts(Dar Boumakhlouf,Dar Gaïa...) <http://www.jneyne.com/accommodation/>
Finally I have solved it as follows: ``` add_action( 'admin_enqueue_scripts', array($this, 'my_admin_scripts') ); function my_admin_scripts($page) { global $post; if ($page == "post-new.php" OR $page == "post.php") { wp_register_script( 'my-custom-admin-scripts', plugins_url('/js/my-admin-post.js',dirname(__FILE__)), array('jquery', 'jquery-ui-sortable' ) , null, true ); wp_enqueue_script( 'my-custom-admin-scripts' ); } } ``` And put the required atribute by JQuery in the next js code (/js/my-admin-post.js): ``` // JavaScript Document jQuery(document).ready(function($) { $('#title').attr('required', true); $('#content').attr('required', true); $('#_my_custom_field').attr('required', true); }); ```
264,398
<p>I'm trying to improve my learning WordPress is very new, and the first theme. My problem is,</p> <p><strong>With the function "wp_nav_menu" into the "ul" tag,</strong></p> <pre><code>data-hover = "dropdown" data-animations = "zoomIn zoomIn zoomIn zoomIn" </code></pre> <p><strong>I want to add html attributes, how can I do that ?,</strong></p> <p>My aim is to make a hover dropdown menu.</p> <p>I've added pictures and source code below.</p> <p>Thank you very much in advance for your help.</p> <p><a href="https://i.stack.imgur.com/WxdZt.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WxdZt.png" alt="enter image description here"></a></p> <p><a href="https://i.stack.imgur.com/97O5P.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/97O5P.png" alt="enter image description here"></a></p>
[ { "answer_id": 264400, "author": "MagniGeeks Technologies", "author_id": 116950, "author_profile": "https://wordpress.stackexchange.com/users/116950", "pm_score": 1, "selected": true, "text": "<p><a href=\"https://developer.wordpress.org/reference/functions/wp_nav_menu/\" rel=\"nofollow noreferrer\">wp_nav_menu</a> has all the documentation written there.</p>\n\n<p>You just need to put \"ul\" in the parameter \"container\".</p>\n\n<p>So your modified function call will be,</p>\n\n<pre><code>wp_nav_menu( array(\n 'theme_location' =&gt; 'main-menu',\n 'container =&gt; 'ul',\n 'container_id' =&gt; '', // put id of ul if needed\n 'menu_class' =&gt; '' // as needed\n) );\n</code></pre>\n\n<p>For custom attributes you need to use Walker class, as you have used in your function,</p>\n\n<pre><code>wp_nav_menu( array(\n 'theme_location' =&gt; 'main-menu',\n 'container =&gt; 'ul',\n 'container_id' =&gt; '', // put id of ul if needed\n 'walker' =&gt; new MainMenu_Walker()\n) );\n</code></pre>\n\n<p>Then write the custom walker class for you menu,</p>\n\n<pre><code>/**\n * Custom walker class.\n */\nclass MainMenu_Walker extends Walker_Nav_Menu {\n\n /**\n * Starts the list before the elements are added.\n *\n * Adds classes to the unordered list sub-menus.\n *\n * @param string $output Passed by reference. Used to append additional content.\n * @param int $depth Depth of menu item. Used for padding.\n * @param array $args An array of arguments. @see wp_nav_menu()\n */\n function start_lvl( &amp;$output, $depth = 0, $args = array() ) {\n // Depth-dependent classes.\n $indent = ( $depth &gt; 0 ? str_repeat( \"\\t\", $depth ) : '' ); // code indent\n $display_depth = ( $depth + 1); // because it counts the first submenu as 0\n $classes = array(\n 'sub-menu',\n ( $display_depth % 2 ? 'menu-odd' : 'menu-even' ),\n ( $display_depth &gt;=2 ? 'sub-sub-menu' : '' ),\n 'menu-depth-' . $display_depth\n );\n $class_names = implode( ' ', $classes );\n\n // Build HTML for output.\n $output .= \"\\n\" . $indent . '&lt;ul class=\"' . $class_names . '\" data-hover=\"dropdown\" data-animations=\"zoomIn zoomIn zoomIn zoomIn\"&gt;' . \"\\n\";\n }\n\n /**\n * Start the element output.\n *\n * Adds main/sub-classes to the list items and links.\n *\n * @param string $output Passed by reference. Used to append additional content.\n * @param object $item Menu item data object.\n * @param int $depth Depth of menu item. Used for padding.\n * @param array $args An array of arguments. @see wp_nav_menu()\n * @param int $id Current item ID.\n */\n function start_el( &amp;$output, $item, $depth = 0, $args = array(), $id = 0 ) {\n global $wp_query;\n $indent = ( $depth &gt; 0 ? str_repeat( \"\\t\", $depth ) : '' ); // code indent\n\n // Depth-dependent classes.\n $depth_classes = array(\n ( $depth == 0 ? 'main-menu-item' : 'sub-menu-item' ),\n ( $depth &gt;=2 ? 'sub-sub-menu-item' : '' ),\n ( $depth % 2 ? 'menu-item-odd' : 'menu-item-even' ),\n 'menu-item-depth-' . $depth\n );\n $depth_class_names = esc_attr( implode( ' ', $depth_classes ) );\n\n // Passed classes.\n $classes = empty( $item-&gt;classes ) ? array() : (array) $item-&gt;classes;\n $class_names = esc_attr( implode( ' ', apply_filters( 'nav_menu_css_class', array_filter( $classes ), $item ) ) );\n\n // Build HTML.\n $output .= $indent . '&lt;li id=\"nav-menu-item-'. $item-&gt;ID . '\" class=\"' . $depth_class_names . ' ' . $class_names . '\"&gt;';\n\n // Link attributes.\n $attributes = ! empty( $item-&gt;attr_title ) ? ' title=\"' . esc_attr( $item-&gt;attr_title ) .'\"' : '';\n $attributes .= ! empty( $item-&gt;target ) ? ' target=\"' . esc_attr( $item-&gt;target ) .'\"' : '';\n $attributes .= ! empty( $item-&gt;xfn ) ? ' rel=\"' . esc_attr( $item-&gt;xfn ) .'\"' : '';\n $attributes .= ! empty( $item-&gt;url ) ? ' href=\"' . esc_attr( $item-&gt;url ) .'\"' : '';\n $attributes .= ' class=\"menu-link ' . ( $depth &gt; 0 ? 'sub-menu-link' : 'main-menu-link' ) . '\"';\n\n // Build HTML output and pass through the proper filter.\n $item_output = sprintf( '%1$s&lt;a%2$s&gt;%3$s%4$s%5$s&lt;/a&gt;%6$s',\n $args-&gt;before,\n $attributes,\n $args-&gt;link_before,\n apply_filters( 'the_title', $item-&gt;title, $item-&gt;ID ),\n $args-&gt;link_after,\n $args-&gt;after\n );\n $output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args );\n }\n}\n</code></pre>\n\n<p>I have added your html attributes to the inside <code>start_lvl</code> function. You can debug this code and modify as you need it.</p>\n\n<p>I have taken this code from <a href=\"https://developer.wordpress.org/reference/functions/wp_nav_menu/#Using_a_Custom_Walker_Function\" rel=\"nofollow noreferrer\">WordPress Menu Custom Walker Class</a></p>\n" }, { "answer_id": 264412, "author": "AddWeb Solution Pvt Ltd", "author_id": 73643, "author_profile": "https://wordpress.stackexchange.com/users/73643", "pm_score": 0, "selected": false, "text": "<p>You need to call walker class to customize your menu structure. Like :</p>\n\n<pre><code>wp_nav_menu( array(\n 'menu' =&gt; '[menu name]',\n 'walker' =&gt; new WPDocs_Walker_Nav_Menu()\n) );\n</code></pre>\n\n<p>And in your WPDocs_Walker_Nav_Menu class you need to extends Walker_Nav_Menu class so that you can overright default function, like :</p>\n\n<pre><code>class WPDocs_Walker_Nav_Menu extends Walker_Nav_Menu {\n// customise default function of Walker_Nav_Menu class.\n}\n</code></pre>\n\n<p>Following tutorial may help you to customize the menu structure:\n<a href=\"http://www.kriesi.at/archives/improve-your-wordpress-navigation-menu-output\" rel=\"nofollow noreferrer\">http://www.kriesi.at/archives/improve-your-wordpress-navigation-menu-output</a></p>\n\n<p>Hope this will helps you.</p>\n\n<p>Thanks!</p>\n" }, { "answer_id": 274373, "author": "Stephan", "author_id": 124437, "author_profile": "https://wordpress.stackexchange.com/users/124437", "pm_score": 2, "selected": false, "text": "<p>You don't need a walker. You can pass 'items_wrap' through wp_nav_menu():</p>\n\n<pre><code>&lt;?php wp_nav_menu( array(\n 'theme_location' =&gt; 'main-menu',\n 'menu_id' =&gt; '',\n 'items_wrap' =&gt; '&lt;ul data-hover=\"dropdown\" data-animations=\"zoomIn zoomIn zoomIn zoomIn\" class=\"%2$s\" id=\"%1$s\"&gt;%3$s&lt;/ul&gt;',\n 'container' =&gt; ''\n) ); ?&gt;\n</code></pre>\n" } ]
2017/04/21
[ "https://wordpress.stackexchange.com/questions/264398", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/118135/" ]
I'm trying to improve my learning WordPress is very new, and the first theme. My problem is, **With the function "wp\_nav\_menu" into the "ul" tag,** ``` data-hover = "dropdown" data-animations = "zoomIn zoomIn zoomIn zoomIn" ``` **I want to add html attributes, how can I do that ?,** My aim is to make a hover dropdown menu. I've added pictures and source code below. Thank you very much in advance for your help. [![enter image description here](https://i.stack.imgur.com/WxdZt.png)](https://i.stack.imgur.com/WxdZt.png) [![enter image description here](https://i.stack.imgur.com/97O5P.png)](https://i.stack.imgur.com/97O5P.png)
[wp\_nav\_menu](https://developer.wordpress.org/reference/functions/wp_nav_menu/) has all the documentation written there. You just need to put "ul" in the parameter "container". So your modified function call will be, ``` wp_nav_menu( array( 'theme_location' => 'main-menu', 'container => 'ul', 'container_id' => '', // put id of ul if needed 'menu_class' => '' // as needed ) ); ``` For custom attributes you need to use Walker class, as you have used in your function, ``` wp_nav_menu( array( 'theme_location' => 'main-menu', 'container => 'ul', 'container_id' => '', // put id of ul if needed 'walker' => new MainMenu_Walker() ) ); ``` Then write the custom walker class for you menu, ``` /** * Custom walker class. */ class MainMenu_Walker extends Walker_Nav_Menu { /** * Starts the list before the elements are added. * * Adds classes to the unordered list sub-menus. * * @param string $output Passed by reference. Used to append additional content. * @param int $depth Depth of menu item. Used for padding. * @param array $args An array of arguments. @see wp_nav_menu() */ function start_lvl( &$output, $depth = 0, $args = array() ) { // Depth-dependent classes. $indent = ( $depth > 0 ? str_repeat( "\t", $depth ) : '' ); // code indent $display_depth = ( $depth + 1); // because it counts the first submenu as 0 $classes = array( 'sub-menu', ( $display_depth % 2 ? 'menu-odd' : 'menu-even' ), ( $display_depth >=2 ? 'sub-sub-menu' : '' ), 'menu-depth-' . $display_depth ); $class_names = implode( ' ', $classes ); // Build HTML for output. $output .= "\n" . $indent . '<ul class="' . $class_names . '" data-hover="dropdown" data-animations="zoomIn zoomIn zoomIn zoomIn">' . "\n"; } /** * Start the element output. * * Adds main/sub-classes to the list items and links. * * @param string $output Passed by reference. Used to append additional content. * @param object $item Menu item data object. * @param int $depth Depth of menu item. Used for padding. * @param array $args An array of arguments. @see wp_nav_menu() * @param int $id Current item ID. */ function start_el( &$output, $item, $depth = 0, $args = array(), $id = 0 ) { global $wp_query; $indent = ( $depth > 0 ? str_repeat( "\t", $depth ) : '' ); // code indent // Depth-dependent classes. $depth_classes = array( ( $depth == 0 ? 'main-menu-item' : 'sub-menu-item' ), ( $depth >=2 ? 'sub-sub-menu-item' : '' ), ( $depth % 2 ? 'menu-item-odd' : 'menu-item-even' ), 'menu-item-depth-' . $depth ); $depth_class_names = esc_attr( implode( ' ', $depth_classes ) ); // Passed classes. $classes = empty( $item->classes ) ? array() : (array) $item->classes; $class_names = esc_attr( implode( ' ', apply_filters( 'nav_menu_css_class', array_filter( $classes ), $item ) ) ); // Build HTML. $output .= $indent . '<li id="nav-menu-item-'. $item->ID . '" class="' . $depth_class_names . ' ' . $class_names . '">'; // Link attributes. $attributes = ! empty( $item->attr_title ) ? ' title="' . esc_attr( $item->attr_title ) .'"' : ''; $attributes .= ! empty( $item->target ) ? ' target="' . esc_attr( $item->target ) .'"' : ''; $attributes .= ! empty( $item->xfn ) ? ' rel="' . esc_attr( $item->xfn ) .'"' : ''; $attributes .= ! empty( $item->url ) ? ' href="' . esc_attr( $item->url ) .'"' : ''; $attributes .= ' class="menu-link ' . ( $depth > 0 ? 'sub-menu-link' : 'main-menu-link' ) . '"'; // Build HTML output and pass through the proper filter. $item_output = sprintf( '%1$s<a%2$s>%3$s%4$s%5$s</a>%6$s', $args->before, $attributes, $args->link_before, apply_filters( 'the_title', $item->title, $item->ID ), $args->link_after, $args->after ); $output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args ); } } ``` I have added your html attributes to the inside `start_lvl` function. You can debug this code and modify as you need it. I have taken this code from [WordPress Menu Custom Walker Class](https://developer.wordpress.org/reference/functions/wp_nav_menu/#Using_a_Custom_Walker_Function)
264,407
<p>I'm developing a plugin, with a login system.</p> <p>I need to conditionally remove a menu entry from a nav menu on the frontend, if <code>$_SESSION['member-user']</code> is set.</p> <p>For example, I want a 'register' link to only appear if <code>$_SESSION['member-user']</code> is not set</p> <p>I did try to search in codex without success. Thank you!</p> <p>EDIT:</p> <p>To explain, the menu is configured from admin of wordpress website. I need to delete the link by my plugin. The menu is not echoed from my plugin, but configured from admin (the admin will use my plugin).</p> <p>Thank you</p> <p>NEW EDIT:</p> <p>The process of my plugin is the following:</p> <p>In "readme" you will read:</p> <p>1 - create a page with shortcode [login] inside and connect to a menu voice "User" > "Login" 2 - create a page with shortcode [balance] inside and connect to a menu voice "User > "Balance"</p> <p>If user is logged (not a wordpress user, login is external), I need to remove that first page "Login" (or "Register", not very important in this case)...</p> <p>I hope it is more clear now... thank you to all!</p>
[ { "answer_id": 264411, "author": "joetek", "author_id": 62298, "author_profile": "https://wordpress.stackexchange.com/users/62298", "pm_score": 0, "selected": false, "text": "<p>You can just wrap the output in your plugin with a conditional like this:</p>\n\n<pre><code>&lt;ul&gt;\n &lt;li&gt;&lt;a href=\"login\"&gt;Login&lt;/a&gt;&lt;/li&gt;\n &lt;?php if ( !$_SESSION['member-user'] ) : ?&gt;\n &lt;li&gt;&lt;a href=\"register\"&gt;Register&lt;/a&gt;&lt;/li&gt;\n &lt;?php endif; ?&gt;\n&lt;/ul&gt;\n</code></pre>\n" }, { "answer_id": 264413, "author": "Punitkumar Patel", "author_id": 117461, "author_profile": "https://wordpress.stackexchange.com/users/117461", "pm_score": 1, "selected": false, "text": "<p>you can write like below for WordPress : </p>\n\n<pre><code>&lt;?php\nif ( !is_user_logged_in() ) { ?&gt;\n &lt;ul&gt;\n &lt;li&gt;&lt;a href=\"login\"&gt;Login&lt;/a&gt;&lt;/li&gt;\n &lt;li&gt;&lt;a href=\"register\"&gt;Register&lt;/a&gt;&lt;/li&gt;\n &lt;/ul&gt;\n&lt;?php } \n</code></pre>\n" }, { "answer_id": 264427, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 1, "selected": false, "text": "<p>One way to do this is to have 2 menus, and show a different menu depending on wether the user is logged in or not, e.g.:</p>\n\n<pre><code>wp_nav_menu( array(\n 'theme_location' =&gt; is_user_logged_in() ? 'logged-in-menu' : 'logged-out-menu'\n) );\n</code></pre>\n\n<p>You can swap out the <code>is_user_logged_in()</code> call with a check of your own</p>\n" }, { "answer_id": 264478, "author": "JItendra Rana", "author_id": 87433, "author_profile": "https://wordpress.stackexchange.com/users/87433", "pm_score": 0, "selected": false, "text": "<p>As you are developing plugin. You can use following code to add menu links dynamically based on SESSION value </p>\n\n<pre><code>function new_nav_menu_items($items) {\nif(isset($_SESSION['member-user'])){\n $loginlink = '\n &lt;li class=\"home\"&gt;&lt;a href=\"' .get_page_link('YOUR_LOGIN_PAGE_ID_HERE').'?from='.$post_slug.'\"&gt;' . __('Login') . '&lt;/a&gt;&lt;/li&gt;\n &lt;li class=\"home\"&gt;&lt;a href=\"' .get_page_link('YOUR_REGISTER_PAGE_ID_HERE').'?from='.$post_slug.'\"&gt;' . __('Register') . '&lt;/a&gt;&lt;/li&gt;\n ';\n $items = $items . $loginlink;\n} else {\n $accountlink = '\n &lt;li class=\"home\"&gt;&lt;a href=\"' .get_page_link('YOUR_MY_ACCOUNT_PAGE_ID_HERE').'?from='.$post_slug.'\"&gt;' . __('My Account') . '&lt;/a&gt;&lt;/li&gt;\n &lt;li class=\"home\"&gt;&lt;a href=\"' .get_page_link('YOUR_LOGOUT_LINK_HERE').'?from='.$post_slug.'\"&gt;' . __('Logout') . '&lt;/a&gt;&lt;/li&gt;\n ';\n $items = $items . $accountlink;\n}\nreturn $items;\n}\nadd_filter( 'wp_nav_menu_items', 'new_nav_menu_items' );\n</code></pre>\n" } ]
2017/04/21
[ "https://wordpress.stackexchange.com/questions/264407", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/115372/" ]
I'm developing a plugin, with a login system. I need to conditionally remove a menu entry from a nav menu on the frontend, if `$_SESSION['member-user']` is set. For example, I want a 'register' link to only appear if `$_SESSION['member-user']` is not set I did try to search in codex without success. Thank you! EDIT: To explain, the menu is configured from admin of wordpress website. I need to delete the link by my plugin. The menu is not echoed from my plugin, but configured from admin (the admin will use my plugin). Thank you NEW EDIT: The process of my plugin is the following: In "readme" you will read: 1 - create a page with shortcode [login] inside and connect to a menu voice "User" > "Login" 2 - create a page with shortcode [balance] inside and connect to a menu voice "User > "Balance" If user is logged (not a wordpress user, login is external), I need to remove that first page "Login" (or "Register", not very important in this case)... I hope it is more clear now... thank you to all!
you can write like below for WordPress : ``` <?php if ( !is_user_logged_in() ) { ?> <ul> <li><a href="login">Login</a></li> <li><a href="register">Register</a></li> </ul> <?php } ```
264,415
<p>Seems like a simple problem but I'm having issues dealing with it.</p> <p>Here's the layout I need</p> <p><strong>loop one</strong></p> <p>Feature </p> <p><strong>loop two</strong></p> <p>Secondary</p> <p>tert - tert - tert</p> <p>Secondary</p> <p>tert - tert - tert</p> <p>Secondary</p> <p>etc</p> <p>Easy enough to do feature as a separate loop. But I want to repeat the 1 col (secondary) 3 (tert) col layout. The problem is the container(s) around the tert elements, and closing them at the right stage as the loop could feasibly end at a single or two terts or after a Secondary. Here's what I have so far.</p> <pre><code>&lt;?php $args = array( 'post_type' =&gt; 'advice', 'offset'=&gt;1 ); $counter = 0; $offset = 2; // the query $the_query = new WP_Query( $args ); ?&gt; &lt;?php if ( $the_query-&gt;have_posts() ) : ?&gt; &lt;?php echo '&lt;div class="clearfix"&gt;'; ?&gt; &lt;?php while ( $the_query-&gt;have_posts() ) : $the_query-&gt;the_post(); ?&gt; &lt;?php if ($counter % 4 == 0) { get_template_part('templates/content', 'advice-secondary'); $offset++; $counter++; } else { if ( $offset % 3 == 0 ){ echo '&lt;/div&gt;'; echo '&lt;div class="three-split-bg bg-light"&gt;'; echo '&lt;div class="container wrap"&gt;'; } get_template_part('templates/content', 'advice-tert'); $offset++; $counter++; }?&gt; &lt;?php endwhile; ?&gt; &lt;?php echo '&lt;/div&gt;'; ?&gt; &lt;?php else : ?&gt; &lt;p&gt;&lt;?php _e( 'Sorry, no posts matched your criteria.' ); ?&gt;&lt;/p&gt; &lt;?php endif; ?&gt; </code></pre>
[ { "answer_id": 264417, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 2, "selected": false, "text": "<p>You could use 3 separate loops, and break out of each loop early once you've got enough posts.</p>\n\n<p>For example, here is a 2 column grid with a single query:</p>\n\n<pre><code>$q = new WP_Query( ... );\n\nif ( $q-&gt;have_posts() ) {\n ?&gt;\n &lt;div class=\"columns\"&gt;\n &lt;div&gt;\n &lt;?php\n $counter = 0;\n while( $q-&gt;have_posts() ) {\n $q-&gt;the_post();\n the_title();\n $counter++;\n if ( $counter === $q-&gt;post_count/2 ) {\n break;\n }\n }\n ?&gt;\n &lt;/div&gt;\n &lt;div&gt;\n &lt;?php\n $counter = 0;\n while( $q-&gt;have_posts() ) {\n $q-&gt;the_post();\n the_title();\n $counter++;\n if ( $counter === $q-&gt;post_count/2 ) {\n break;\n }\n }\n ?&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n &lt;?php\n} else {\n echo 'No posts found';\n}\n</code></pre>\n\n<p>Notice how I counted each post as it was displayed, then exited the loop early when the counter was halfway through?</p>\n\n<h3>Arbitrary Columns</h3>\n\n<p>Note that here the columns are all of the same design, and the conditional check has been changed.</p>\n\n<pre><code>$q = new WP_Query( ... );\n\nif ( $q-&gt;have_posts() ) {\n ?&gt;\n &lt;div class=\"columns\"&gt;\n &lt;?php\n $columns = 2;\n for ( $i = 1; $i &lt; $columns; $i++ ) {\n echo '&lt;div&gt;';\n $counter = 0;\n while ( $q-&gt;have_posts() ) {\n $q-&gt;the_post();\n get_template_part( 'column','post' );\n $counter++;\n if ( $counter &gt; $q-&gt;post_count/$columns ) {\n break;\n }\n }\n echo '&lt;/div&gt;';\n }\n ?&gt;\n &lt;/div&gt;\n &lt;?php\n} else {\n echo 'No posts found';\n}\n</code></pre>\n\n<p>Note the <code>get_template_part</code> call, simplifying the template.</p>\n\n<p>With these 2 examples, and some basic math you can turn these into any combination of columns</p>\n\n<p>Alternatively, have rows of posts floated to the left and make each post 50% width or fixed width, using CSS to avoid PHP entirely</p>\n" }, { "answer_id": 264674, "author": "epluribusunum", "author_id": 103782, "author_profile": "https://wordpress.stackexchange.com/users/103782", "pm_score": 0, "selected": false, "text": "<p>OK I found a solution. It is far from an elegant one though, I feel like my conditional statements could be improved greatly if anyone could help me with that:</p>\n\n<pre><code>....\nwhile ( $the_query-&gt;have_posts() ) : $the_query-&gt;the_post();\nif($counter == 0):\n get_template_part('templates/content', 'advice-secondary');\n $counter++;\n\n\n else:\n if($counter == 1){\n echo '&lt;div class=\"three-split-bg bg-light\"&gt;\n &lt;div class=\"container wrap\"&gt;\n &lt;div class=\"row\"&gt;';\n };\n\n echo '&lt;div class=\"text-left col-xs-6 col-md-4 content\"&gt;';\n get_template_part('templates/content', 'advice-tert');\n echo '&lt;/div&gt;';\n $counter++;\n\n if ($the_query-&gt;current_post +1 == $the_query-&gt;found_posts || $counter % 4 == 0) {\n $counter = 0;\n\n echo '&lt;/div&gt;\n &lt;/div&gt;\n &lt;/div&gt;';\n };\n\n endif;\nendwhile;\n...\n</code></pre>\n" }, { "answer_id": 264679, "author": "Kristian Kalvå", "author_id": 97184, "author_profile": "https://wordpress.stackexchange.com/users/97184", "pm_score": 0, "selected": false, "text": "<p>Do you really need multiple loops? Are you getting different content for each section? If not you can manage with one single loop and display differently with flexbox.</p>\n\n<pre><code>.parent {\n display: flex;\n flex-direction; row;\n flex-wrap: wrap;\n}\n\n.children {\n flex: 1 1 33,33%;\n}\n\n.children:nth-child(1),\n.children:nth-child(5) {\n flex-basis: 100%;\n}\n</code></pre>\n\n<p>Something like that would help. You can create more complex child selectors for more repetition.</p>\n" } ]
2017/04/21
[ "https://wordpress.stackexchange.com/questions/264415", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/103782/" ]
Seems like a simple problem but I'm having issues dealing with it. Here's the layout I need **loop one** Feature **loop two** Secondary tert - tert - tert Secondary tert - tert - tert Secondary etc Easy enough to do feature as a separate loop. But I want to repeat the 1 col (secondary) 3 (tert) col layout. The problem is the container(s) around the tert elements, and closing them at the right stage as the loop could feasibly end at a single or two terts or after a Secondary. Here's what I have so far. ``` <?php $args = array( 'post_type' => 'advice', 'offset'=>1 ); $counter = 0; $offset = 2; // the query $the_query = new WP_Query( $args ); ?> <?php if ( $the_query->have_posts() ) : ?> <?php echo '<div class="clearfix">'; ?> <?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?> <?php if ($counter % 4 == 0) { get_template_part('templates/content', 'advice-secondary'); $offset++; $counter++; } else { if ( $offset % 3 == 0 ){ echo '</div>'; echo '<div class="three-split-bg bg-light">'; echo '<div class="container wrap">'; } get_template_part('templates/content', 'advice-tert'); $offset++; $counter++; }?> <?php endwhile; ?> <?php echo '</div>'; ?> <?php else : ?> <p><?php _e( 'Sorry, no posts matched your criteria.' ); ?></p> <?php endif; ?> ```
You could use 3 separate loops, and break out of each loop early once you've got enough posts. For example, here is a 2 column grid with a single query: ``` $q = new WP_Query( ... ); if ( $q->have_posts() ) { ?> <div class="columns"> <div> <?php $counter = 0; while( $q->have_posts() ) { $q->the_post(); the_title(); $counter++; if ( $counter === $q->post_count/2 ) { break; } } ?> </div> <div> <?php $counter = 0; while( $q->have_posts() ) { $q->the_post(); the_title(); $counter++; if ( $counter === $q->post_count/2 ) { break; } } ?> </div> </div> <?php } else { echo 'No posts found'; } ``` Notice how I counted each post as it was displayed, then exited the loop early when the counter was halfway through? ### Arbitrary Columns Note that here the columns are all of the same design, and the conditional check has been changed. ``` $q = new WP_Query( ... ); if ( $q->have_posts() ) { ?> <div class="columns"> <?php $columns = 2; for ( $i = 1; $i < $columns; $i++ ) { echo '<div>'; $counter = 0; while ( $q->have_posts() ) { $q->the_post(); get_template_part( 'column','post' ); $counter++; if ( $counter > $q->post_count/$columns ) { break; } } echo '</div>'; } ?> </div> <?php } else { echo 'No posts found'; } ``` Note the `get_template_part` call, simplifying the template. With these 2 examples, and some basic math you can turn these into any combination of columns Alternatively, have rows of posts floated to the left and make each post 50% width or fixed width, using CSS to avoid PHP entirely