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 \"re...
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 MySetti...
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...
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['...
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-...
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...
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 d...
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 d...
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; Hos...
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 ...
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_de...
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_de...
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_...
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_...
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 b...
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 ...
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 ...
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...
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;cf...
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 nor...
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 nor...
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'...
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'...
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 LOO...
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=\...
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=\...
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 'blo...
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 ...
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>Rena...
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>Rena...
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>Rena...
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));...
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...
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...
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=\"...
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 direc...
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$pos...
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$pos...
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\...
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...
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 u...
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 );\nfunctio...
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, 'ca...
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...
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...
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...
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...
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 ...
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...
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...
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...
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 ...
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 ...
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 ...
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 ...
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 /man...
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'=...
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()</co...
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_cust...
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...
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...
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...
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>exc...
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 u...
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=\"noreferr...
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_noti...
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><c...
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><c...
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><c...
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 bu...
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 an...
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<...
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)...
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...
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...
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>\...
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>\...
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>\...
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...
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...
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 sol...
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 sol...
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...
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...
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<pr...
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_men...
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>Ge...
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('pa...
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. The...
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; ">contact@mondomain.com</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. The...
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; ">contact@mondomain.com</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_...
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_...
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 w...
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 w...
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 ...
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>...
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>...
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 ...
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;...
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...
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