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
324,079
<p>I want to give a post a classname on the homepage (index) if the post on the single page has no content. So when the post itself exists but there is no content, I want to give a classname to that specific post/article which will be shown on the homepage.</p> <p>My question: can this be done? If so, how?</p>
[ { "answer_id": 324087, "author": "Frank P. Walentynowicz", "author_id": 32851, "author_profile": "https://wordpress.stackexchange.com/users/32851", "pm_score": 1, "selected": false, "text": "<p>As Tom J Nowell mentioned in his comment, it is not clear what do you want to accomplish. If y...
2018/12/28
[ "https://wordpress.stackexchange.com/questions/324079", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/62192/" ]
I want to give a post a classname on the homepage (index) if the post on the single page has no content. So when the post itself exists but there is no content, I want to give a classname to that specific post/article which will be shown on the homepage. My question: can this be done? If so, how?
As Tom J Nowell mentioned in his comment, it is not clear what do you want to accomplish. If you want to just show your empty content `div`, you can use CSS as follows: ``` div:empty { width: 100%; height: 20px; margin-bottom: 10px; background: #ff0000; } ``` It will show your empty content `div` as a nice, red band.
324,091
<p>I'm trying to create custom columns block in Gutenberg. Is it possible to add class to the wrapper of the element in the editor based on the attributes? I'd like to switch <code>???</code> to class based e.g. <code>columns-4</code>. Otherwise it's not possible to use <code>flex</code>. </p> <pre><code>&lt;div id="..." class="wp-block editor-block-list__block ???" data-type="my-blocks/column" tabindex="0" aria-label="Block: Single Column"&gt; &lt;div&gt; &lt;div class="this-can-be-set-in-edit-or-attributes"&gt; ... &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre>
[ { "answer_id": 324095, "author": "Runnick", "author_id": 121208, "author_profile": "https://wordpress.stackexchange.com/users/121208", "pm_score": 4, "selected": true, "text": "<p>Actually it can be done with the <a href=\"https://wordpress.org/gutenberg/handbook/designers-developers/dev...
2018/12/28
[ "https://wordpress.stackexchange.com/questions/324091", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/121208/" ]
I'm trying to create custom columns block in Gutenberg. Is it possible to add class to the wrapper of the element in the editor based on the attributes? I'd like to switch `???` to class based e.g. `columns-4`. Otherwise it's not possible to use `flex`. ``` <div id="..." class="wp-block editor-block-list__block ???" data-type="my-blocks/column" tabindex="0" aria-label="Block: Single Column"> <div> <div class="this-can-be-set-in-edit-or-attributes"> ... </div> </div> </div> ```
Actually it can be done with the [filter](https://wordpress.org/gutenberg/handbook/designers-developers/developers/filters/block-filters/#editor-blocklistblock): ``` const { createHigherOrderComponent } = wp.compose; const withCustomClassName = createHigherOrderComponent( ( BlockListBlock ) => { return ( props ) => { if(props.attributes.size) { return <BlockListBlock { ...props } className={ "block-" + props.attributes.size } />; } else { return <BlockListBlock {...props} /> } }; }, 'withClientIdClassName' ); wp.hooks.addFilter( 'editor.BlockListBlock', 'my-plugin/with-client-id-class-name', withCustomClassName ); ```
324,127
<p>I have this PHP code that shows a related posts element created using advanced custom fields plugin. I want to create a shortcode inside functions.php with the code and then use the shortcode in a text element of a page builder. Would someone kindly assist me with the modified code to put inside functions.php? Thanks</p> <pre><code>&lt;?php $posts = get_field('related_posts', false, false); $loop = new WP_Query(array('post_type' =&gt; 'post', 'posts_per_page' =&gt; 3, 'post__in' =&gt; $posts, 'post_status' =&gt; 'publish', 'orderby' =&gt; 'post__in', 'order' =&gt; 'ASC' )); if($loop-&gt;have_posts()) { ?&gt; &lt;div class="rel-posts"&gt; &lt;?php while ($loop-&gt;have_posts()) : $loop-&gt;the_post(); ?&gt; &lt;div class="related-post"&gt; &lt;a href="&lt;?php the_permalink(); ?&gt;"&gt;&lt;?php the_post_thumbnail('td_218x150'); ?&gt;&lt;/a&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;/div&gt; &lt;?php endwhile; ?&gt; &lt;/div&gt; &lt;?php } wp_reset_query(); ?&gt; </code></pre>
[ { "answer_id": 324108, "author": "John Dee", "author_id": 131224, "author_profile": "https://wordpress.stackexchange.com/users/131224", "pm_score": 0, "selected": false, "text": "<p>Just delete the data from what you're showing the client. If a person doesn't understand what the API is, ...
2018/12/29
[ "https://wordpress.stackexchange.com/questions/324127", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/-1/" ]
I have this PHP code that shows a related posts element created using advanced custom fields plugin. I want to create a shortcode inside functions.php with the code and then use the shortcode in a text element of a page builder. Would someone kindly assist me with the modified code to put inside functions.php? Thanks ``` <?php $posts = get_field('related_posts', false, false); $loop = new WP_Query(array('post_type' => 'post', 'posts_per_page' => 3, 'post__in' => $posts, 'post_status' => 'publish', 'orderby' => 'post__in', 'order' => 'ASC' )); if($loop->have_posts()) { ?> <div class="rel-posts"> <?php while ($loop->have_posts()) : $loop->the_post(); ?> <div class="related-post"> <a href="<?php the_permalink(); ?>"><?php the_post_thumbnail('td_218x150'); ?></a> <h3><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3> </div> <?php endwhile; ?> </div> <?php } wp_reset_query(); ?> ```
I'm not entirely sure what will be better explanation, or why this one (the real one) is not enough. In your stats you see URLs of requests and not paths to files. URL has nothing to do with files on server. Yes - if the requests targets physical file, then that file exists, but... There are plenty URLs that are not connected to any file - mod\_rewrite takes care of them. For example there is no directory like `/rss/` anywhere in your WP installation directory. There is no directory like `/category/uncaregorized/`, and yet - both of these URLs work and you can find them in stats... I don't see anything wrong in explaining, that your client sees HTTP requests and not file paths. And these `/wp-json/*` requests are requests to WP REST API. PS. You don't see them in Google Analytics, because there is no tracking code in REST API, so there requests are not logged to GA. But AWStats are more like server logs, so all requests get logged.
324,158
<p>I have a blank theme purely to redirect to my custom front-end. I created a <code>functions.php</code> and put <code>add_theme_support()</code> inside it and to no avail.</p> <p>index.php:</p> <pre><code>&lt;meta content="0; URL='https://headless-cms.test''" http-equiv"refresh"&gt; &lt;!-- just in case the meta tag is not read properly, here is plan B: a JS redirect --&gt; &lt;script type="text/javascript"&gt; window.location = 'https://headless-cms.test'; &lt;/script&gt; </code></pre> <p>functions.php</p> <pre><code>add_action( 'after_setup_theme', 'headless_theme_setup' ); function headless_theme_setup() { add_theme_support( 'post-thumbnails'); } // Also tried these and still didn't show //add_theme_support('post-thumbnails', array( // 'post', // 'page', //)); //add_theme_support( 'post-thumbnails' ); </code></pre> <p>I refreshed the admin panel and checked under <code>screen options</code> and did not see it. I'm using WP 5.0.2.</p>
[ { "answer_id": 324131, "author": "Md. Ehsanul Haque Kanan", "author_id": 75705, "author_profile": "https://wordpress.stackexchange.com/users/75705", "pm_score": 1, "selected": true, "text": "<p>You can try using <a href=\"https://wordpress.org/plugins/bulkpress/\" rel=\"nofollow noreferr...
2018/12/29
[ "https://wordpress.stackexchange.com/questions/324158", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/145214/" ]
I have a blank theme purely to redirect to my custom front-end. I created a `functions.php` and put `add_theme_support()` inside it and to no avail. index.php: ``` <meta content="0; URL='https://headless-cms.test''" http-equiv"refresh"> <!-- just in case the meta tag is not read properly, here is plan B: a JS redirect --> <script type="text/javascript"> window.location = 'https://headless-cms.test'; </script> ``` functions.php ``` add_action( 'after_setup_theme', 'headless_theme_setup' ); function headless_theme_setup() { add_theme_support( 'post-thumbnails'); } // Also tried these and still didn't show //add_theme_support('post-thumbnails', array( // 'post', // 'page', //)); //add_theme_support( 'post-thumbnails' ); ``` I refreshed the admin panel and checked under `screen options` and did not see it. I'm using WP 5.0.2.
You can try using [BulkPress](https://wordpress.org/plugins/bulkpress/). It allows you to create hundreds of categories very easily. Follow these steps: 1. Install and activate the plugin. 2. In the left side bar, hover your cursor on **Bulkpress**. Then click on **Terms**. 3. A new page will appear. In **Taxonomy** field, choose **Category**. 4. Insert your **Categories** in the **Terms** field. 5. Choose your desired **Parent**, if required. 6. Finally, click on the **Add Terms** button.
324,174
<p>can anyone help me i am trying to create a plugin for gallery but at the initiating a problem occurred,when i activate the plugin it activating but problem is that it does not appearing at left menu ,</p> <p><code>this is my code of plugin startup:|</code></p> <pre><code>&lt;?php /* Plugin Name:JaissGallery Plugin URI:WWW.GOOGLE.COM description: &gt;-Jaiss gallery plugin Version: 0.1 Author: Mr. Tahrid abbas Author URI: http://mrtotallyawesome.com */ function doctors_gallery(){ add_menu_page( "doctorsGallery", "Doctors Gallery", "Manage_options", "DoctorsGallery", "Doc_gallery_view" ); } add_action('admin_menu','doctors_gallery'); function Doc_gallery_view(){ echo "ghfhgfgh"; } </code></pre> <p>can somebody tell me please what i am missing there ?</p>
[ { "answer_id": 324131, "author": "Md. Ehsanul Haque Kanan", "author_id": 75705, "author_profile": "https://wordpress.stackexchange.com/users/75705", "pm_score": 1, "selected": true, "text": "<p>You can try using <a href=\"https://wordpress.org/plugins/bulkpress/\" rel=\"nofollow noreferr...
2018/12/29
[ "https://wordpress.stackexchange.com/questions/324174", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/144155/" ]
can anyone help me i am trying to create a plugin for gallery but at the initiating a problem occurred,when i activate the plugin it activating but problem is that it does not appearing at left menu , `this is my code of plugin startup:|` ``` <?php /* Plugin Name:JaissGallery Plugin URI:WWW.GOOGLE.COM description: >-Jaiss gallery plugin Version: 0.1 Author: Mr. Tahrid abbas Author URI: http://mrtotallyawesome.com */ function doctors_gallery(){ add_menu_page( "doctorsGallery", "Doctors Gallery", "Manage_options", "DoctorsGallery", "Doc_gallery_view" ); } add_action('admin_menu','doctors_gallery'); function Doc_gallery_view(){ echo "ghfhgfgh"; } ``` can somebody tell me please what i am missing there ?
You can try using [BulkPress](https://wordpress.org/plugins/bulkpress/). It allows you to create hundreds of categories very easily. Follow these steps: 1. Install and activate the plugin. 2. In the left side bar, hover your cursor on **Bulkpress**. Then click on **Terms**. 3. A new page will appear. In **Taxonomy** field, choose **Category**. 4. Insert your **Categories** in the **Terms** field. 5. Choose your desired **Parent**, if required. 6. Finally, click on the **Add Terms** button.
324,209
<p>I'm still learning PHP and MySQL and need to create a unique number in Wordpress site (as a order number ID) every time, when user fill and submit "order" form from frontend and save it to database. Next submit will create a number+1. Website is not running on Woocommerce. No cart, checkout, products...</p> <p>Thanks for help! :)</p>
[ { "answer_id": 324212, "author": "Md. Ehsanul Haque Kanan", "author_id": 75705, "author_profile": "https://wordpress.stackexchange.com/users/75705", "pm_score": -1, "selected": false, "text": "<p>You can get the unique ID number by using the merge tag {submission:sequence}. It allows you...
2018/12/30
[ "https://wordpress.stackexchange.com/questions/324209", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/157966/" ]
I'm still learning PHP and MySQL and need to create a unique number in Wordpress site (as a order number ID) every time, when user fill and submit "order" form from frontend and save it to database. Next submit will create a number+1. Website is not running on Woocommerce. No cart, checkout, products... Thanks for help! :)
in order to do this use ``` AUTO_INCREMENT PRIMARY KEY ``` while you define your table. Your table should be something like this: ``` CREATE TABLE `order` ( `order_id` INT(11) UNSIGNED AUTO_INCREMENT PRIMARY KEY, `user_group_id` INT(11) UNSIGNED NOT NULL, `status` BIT, `meta` VARCHAR ( 255 ), `value` TEXT, `update_time` TIMESTAMP )DEFAULT CHARSET = utf8; ``` remember that you could change other columns, the important one is `order_id` which is auto increment
324,221
<p>I have this custom post type:</p> <pre><code>function create_posttype() { register_post_type( 'companies', array( 'labels' =&gt; array( 'name' =&gt; __( 'شرکتهای عضو' ), 'singular_name' =&gt; __( 'شرکت' ) ), 'supports' =&gt; array('title', 'editor', 'custom-fields', 'excerpt', 'thumbnail'), 'public' =&gt; true, 'has_archive' =&gt; true, 'rewrite' =&gt; array('slug' =&gt; 'companies'), ) ); } add_action( 'init', 'create_posttype' ); </code></pre> <p>Which shows classic editor in WordPress admin area. I tried to replace 'editor' with 'gutenberg' in the supports array which doesn't work. I also added this code to my function as suggested <a href="https://stackoverflow.com/questions/52199629/how-to-disable-gutenberg-editor-for-certain-post-types/52199630">here</a>:</p> <pre><code>add_filter('gutenberg_can_edit_post_type', 'prefix_disable_gutenberg'); function prefix_disable_gutenberg($current_status, $post_type) { if ($post_type === 'companies') return true; return $current_status; } </code></pre> <p>How can I have a Gutenberg editor on my custom post type?</p>
[ { "answer_id": 324222, "author": "Alvaro", "author_id": 16533, "author_profile": "https://wordpress.stackexchange.com/users/16533", "pm_score": 7, "selected": true, "text": "<p>For Gutenberg to work in a Custom Post Type you need to enable both the <code>editor</code> in <code>supports</...
2018/12/30
[ "https://wordpress.stackexchange.com/questions/324221", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/109403/" ]
I have this custom post type: ``` function create_posttype() { register_post_type( 'companies', array( 'labels' => array( 'name' => __( 'شرکتهای عضو' ), 'singular_name' => __( 'شرکت' ) ), 'supports' => array('title', 'editor', 'custom-fields', 'excerpt', 'thumbnail'), 'public' => true, 'has_archive' => true, 'rewrite' => array('slug' => 'companies'), ) ); } add_action( 'init', 'create_posttype' ); ``` Which shows classic editor in WordPress admin area. I tried to replace 'editor' with 'gutenberg' in the supports array which doesn't work. I also added this code to my function as suggested [here](https://stackoverflow.com/questions/52199629/how-to-disable-gutenberg-editor-for-certain-post-types/52199630): ``` add_filter('gutenberg_can_edit_post_type', 'prefix_disable_gutenberg'); function prefix_disable_gutenberg($current_status, $post_type) { if ($post_type === 'companies') return true; return $current_status; } ``` How can I have a Gutenberg editor on my custom post type?
For Gutenberg to work in a Custom Post Type you need to enable both the `editor` in `supports` (which you already have) and `show_in_rest`. So add `'show_in_rest' => true,` to your post registration arguments array.
324,229
<p>I'm currently using this code within my plugin on a custom widgets textarea to enable codemirror.</p> <pre><code>(function ($) { $(document).ready( function(){ var coinmedi_es_&lt;?php echo $wid_id; ?&gt; = wp.codeEditor.defaultSettings ? _.clone( wp.codeEditor.defaultSettings ) : {}; coinmedi_es_&lt;?php echo $wid_id; ?&gt;.codemirror = _.extend( {}, coinmedi_es_&lt;?php echo $wid_id; ?&gt;.codemirror, { mode: 'htmlmixed', lineNumbers: true, indentUnit: 2, tabSize: 2, autoRefresh:true } ); var cm_editor_&lt;?php echo $wid_id; ?&gt; = wp.codeEditor.initialize($('#&lt;?php echo $textarea_id; ?&gt;') , coinmedi_es_&lt;?php echo $wid_id; ?&gt; ); $(document).on('keyup', '.CodeMirror-code', function(){ $('#&lt;?php echo $textarea_id; ?&gt;').html(cm_editor_&lt;?php echo $wid_id; ?&gt;.codemirror.getValue()); $('#&lt;?php echo $textarea_id; ?&gt;').trigger('change'); }); }); })(jQuery); </code></pre> <p>Everything is working fine for HTML but when I try to add javascript eg.</p> <pre><code>&lt;script&gt; alert('1') &lt;/script&gt; </code></pre> <p>It accepts the javascript and highlights as it should but when I click the save button nothing is posted for this textarea. When I remove the javascript it saves as it should. Where am I going wrong, I can't seem to pinpoint why it's not saving. Any help would be appreciated. </p> <p>Edit: Update method</p> <pre><code>$instance['ad-code'] = ( ! empty( $new_instance['ad-code'] ) ) ? $new_instance['ad-code'] : ''; </code></pre>
[ { "answer_id": 324222, "author": "Alvaro", "author_id": 16533, "author_profile": "https://wordpress.stackexchange.com/users/16533", "pm_score": 7, "selected": true, "text": "<p>For Gutenberg to work in a Custom Post Type you need to enable both the <code>editor</code> in <code>supports</...
2018/12/30
[ "https://wordpress.stackexchange.com/questions/324229", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/155953/" ]
I'm currently using this code within my plugin on a custom widgets textarea to enable codemirror. ``` (function ($) { $(document).ready( function(){ var coinmedi_es_<?php echo $wid_id; ?> = wp.codeEditor.defaultSettings ? _.clone( wp.codeEditor.defaultSettings ) : {}; coinmedi_es_<?php echo $wid_id; ?>.codemirror = _.extend( {}, coinmedi_es_<?php echo $wid_id; ?>.codemirror, { mode: 'htmlmixed', lineNumbers: true, indentUnit: 2, tabSize: 2, autoRefresh:true } ); var cm_editor_<?php echo $wid_id; ?> = wp.codeEditor.initialize($('#<?php echo $textarea_id; ?>') , coinmedi_es_<?php echo $wid_id; ?> ); $(document).on('keyup', '.CodeMirror-code', function(){ $('#<?php echo $textarea_id; ?>').html(cm_editor_<?php echo $wid_id; ?>.codemirror.getValue()); $('#<?php echo $textarea_id; ?>').trigger('change'); }); }); })(jQuery); ``` Everything is working fine for HTML but when I try to add javascript eg. ``` <script> alert('1') </script> ``` It accepts the javascript and highlights as it should but when I click the save button nothing is posted for this textarea. When I remove the javascript it saves as it should. Where am I going wrong, I can't seem to pinpoint why it's not saving. Any help would be appreciated. Edit: Update method ``` $instance['ad-code'] = ( ! empty( $new_instance['ad-code'] ) ) ? $new_instance['ad-code'] : ''; ```
For Gutenberg to work in a Custom Post Type you need to enable both the `editor` in `supports` (which you already have) and `show_in_rest`. So add `'show_in_rest' => true,` to your post registration arguments array.
324,230
<p>I have a freelancer working on a program for me. </p> <p>I gave him access to the theme folder via FTP. He uploaded <a href="http://phpminiadmin.sourceforge.net/" rel="nofollow noreferrer">phpMiniAdmin</a> to that folder and, somehow, obtained the database credentials, which he then used to sign in. </p> <p>How did he manage to obtain those credentials? Is there a vulnerability that can be used once you can upload files to the server?</p>
[ { "answer_id": 324231, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 2, "selected": false, "text": "<p>If they can upload files then they can upload a php file that can read the database credentials from wp...
2018/12/30
[ "https://wordpress.stackexchange.com/questions/324230", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/136273/" ]
I have a freelancer working on a program for me. I gave him access to the theme folder via FTP. He uploaded [phpMiniAdmin](http://phpminiadmin.sourceforge.net/) to that folder and, somehow, obtained the database credentials, which he then used to sign in. How did he manage to obtain those credentials? Is there a vulnerability that can be used once you can upload files to the server?
All he needed to do is to put this PHP code in any template file and run it: ``` var_dump(DB_NAME, DB_USER, DB_PASSWORD, DB_HOST); ``` One line and it will print all the DB credentials. As you can see - no vulnerabilities are needed. All PHP code has access to these credentials. And it has to - otherwise it wouldn’t be able to access DB...
324,243
<p>I'm working on converting my old NucleusCMS blogs to WordPress. I have created a set of tables locally and began the conversion process. I've been fine right up to image &quot;conversion&quot;. I think I can pull the old image and add it to the library using <a href="https://wordpress.stackexchange.com/questions/238294/programmatically-adding-images-to-the-media-library-with-wp-generate-attachment">this answer</a>. After that, I'm sort of lost.</p> <p>What I want to do is, having just programmatically added a media item (picture), then use that image by programmatically adding it to a specific post with the dimensions and alt text I just pulled (via regex) from the source I was working from.</p> <h3>Step 1. I need to get a pointer or id or something for the freshly added media.</h3> <p>I don't 100% know what I am doing with WordPress itself so I do not know how to get a handle on the media I just added.</p> <h3>Step 2. I need to make that image be part of a post.</h3> <p>As for how I add it to the post (in the right size) in whatever format WordPress uses natively...</p> <p><em>I need help with both steps.</em></p>
[ { "answer_id": 340400, "author": "Antti Koskinen", "author_id": 144392, "author_profile": "https://wordpress.stackexchange.com/users/144392", "pm_score": 1, "selected": false, "text": "<p>Building upon the accepted answer on the linked question, I think something like this might work.</p...
2018/12/30
[ "https://wordpress.stackexchange.com/questions/324243", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/109240/" ]
I'm working on converting my old NucleusCMS blogs to WordPress. I have created a set of tables locally and began the conversion process. I've been fine right up to image "conversion". I think I can pull the old image and add it to the library using [this answer](https://wordpress.stackexchange.com/questions/238294/programmatically-adding-images-to-the-media-library-with-wp-generate-attachment). After that, I'm sort of lost. What I want to do is, having just programmatically added a media item (picture), then use that image by programmatically adding it to a specific post with the dimensions and alt text I just pulled (via regex) from the source I was working from. ### Step 1. I need to get a pointer or id or something for the freshly added media. I don't 100% know what I am doing with WordPress itself so I do not know how to get a handle on the media I just added. ### Step 2. I need to make that image be part of a post. As for how I add it to the post (in the right size) in whatever format WordPress uses natively... *I need help with both steps.*
Hey I used this code for something similar(I was also downloading remote image and uploading to WordPress site). Please have a look: ``` $image_url = $value;//This is the sanitized image url. $image = pathinfo($image_url);//Extracting information into array. $image_name = $image['basename']; $upload_dir = wp_upload_dir(); $image_data = file_get_contents($image_url); $unique_file_name = wp_unique_filename($upload_dir['path'], $image_name); $filename = basename($unique_file_name); $postarr = array( 'post_title' => $post_title, 'post_content' => $post_content, 'post_type' => 'post',//or whatever is your post type slug. 'post_status' => 'publish', 'meta_input' => array( //If you have any meta data, that will go here. ), ); $insert_id = wp_insert_post($postarr, true); if (!is_wp_error($insert_id)) { if ($image != '') { // Check folder permission and define file location if (wp_mkdir_p($upload_dir['path'])) { $file = $upload_dir['path'] . '/' . $filename; } else { $file = $upload_dir['basedir'] . '/' . $filename; } // Create the image file on the server file_put_contents($file, $image_data); // Check image file type $wp_filetype = wp_check_filetype($filename, null); // Set attachment data $attachment = array( 'post_mime_type' => $wp_filetype['type'], 'post_title' => sanitize_file_name($filename), 'post_content' => '', 'post_status' => 'inherit', ); // Create the attachment $attach_id = wp_insert_attachment($attachment, $file, $insert_id); // Include image.php require_once ABSPATH . 'wp-admin/includes/image.php'; // Define attachment metadata $attach_data = wp_generate_attachment_metadata($attach_id, $file); // Assign metadata to attachment wp_update_attachment_metadata($attach_id, $attach_data); // And finally assign featured image to post $thumbnail = set_post_thumbnail($insert_id, $attach_id); } } ```
324,244
<p>So I am trying to add a button at the end of my blog posts, here is the code I have in the plugin so far: </p> <pre><code>&lt;?php /* Plugin Name: etc.... */ function shares_content() { ?&gt; &lt;div class='social-shares-container'&gt; &lt;a href='https://www.facebook.com/sharer/sharer.php?u=&lt;?php echo the_permalink(); ?&gt;'&gt;Share on Facebook&lt;/a&gt; &lt;/div&gt; &lt;?php } function shares_add_buttons($content) { global $post; if (!is_page() &amp;&amp; is_object($post)) { return $content . shares_content(); } return $content; } add_filter('the_content', 'shares_add_buttons'); ?&gt; </code></pre> <p>This adds the link just before my content, but if I do something like this, it adds the new content in the desired place (after <code>the_content</code>):</p> <pre><code>function shares_add_buttons($content) { global $post; if (!is_page() &amp;&amp; is_object($post)) { return $content . 'some random content'; } return $content; } </code></pre> <p>Could anyone tell me why this is please?</p>
[ { "answer_id": 324246, "author": "Krzysiek Dróżdż", "author_id": 34172, "author_profile": "https://wordpress.stackexchange.com/users/34172", "pm_score": 0, "selected": false, "text": "<p>In this line:</p>\n\n<pre><code>return $content . shares_content();\n</code></pre>\n\n<p>You concaten...
2018/12/30
[ "https://wordpress.stackexchange.com/questions/324244", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/155705/" ]
So I am trying to add a button at the end of my blog posts, here is the code I have in the plugin so far: ``` <?php /* Plugin Name: etc.... */ function shares_content() { ?> <div class='social-shares-container'> <a href='https://www.facebook.com/sharer/sharer.php?u=<?php echo the_permalink(); ?>'>Share on Facebook</a> </div> <?php } function shares_add_buttons($content) { global $post; if (!is_page() && is_object($post)) { return $content . shares_content(); } return $content; } add_filter('the_content', 'shares_add_buttons'); ?> ``` This adds the link just before my content, but if I do something like this, it adds the new content in the desired place (after `the_content`): ``` function shares_add_buttons($content) { global $post; if (!is_page() && is_object($post)) { return $content . 'some random content'; } return $content; } ``` Could anyone tell me why this is please?
Your `shares_content` function directly outputs content, which won't work if you're trying to assign the results to a variable or use it in a `return` statement within another function. You can change it to `return` the string: ``` function shares_content() { $content = "<div class='social-shares-container'><a href='https://www.facebook.com/sharer/sharer.php?u=%s'>Share on Facebook</a></div>"; return sprintf( $content, get_permalink() ); } ``` It's also worth pointing out here the use of `get_permalink()`. If you look at the source code, that function also `return`s its value. There is another API function, `the_permalink()`, which contains an `echo` instead of a `return`. That would also break your filter output. Most WordPress functions have two versions like this.
324,306
<p>When I visit website using Wordpress Dashboard, browser is showing 'cPanel, Inc. Certification Authority';</p> <p><a href="https://i.stack.imgur.com/u0wYQ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/u0wYQ.png" alt="enter image description here"></a></p> <p>But, when I access it directly typing the domain in the URL Bar, no Certification icon is being displayed.</p> <p><a href="https://i.stack.imgur.com/yOTBU.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/yOTBU.png" alt="enter image description here"></a></p> <p>What it means? And how can I fix it?</p>
[ { "answer_id": 324246, "author": "Krzysiek Dróżdż", "author_id": 34172, "author_profile": "https://wordpress.stackexchange.com/users/34172", "pm_score": 0, "selected": false, "text": "<p>In this line:</p>\n\n<pre><code>return $content . shares_content();\n</code></pre>\n\n<p>You concaten...
2018/12/31
[ "https://wordpress.stackexchange.com/questions/324306", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/158048/" ]
When I visit website using Wordpress Dashboard, browser is showing 'cPanel, Inc. Certification Authority'; [![enter image description here](https://i.stack.imgur.com/u0wYQ.png)](https://i.stack.imgur.com/u0wYQ.png) But, when I access it directly typing the domain in the URL Bar, no Certification icon is being displayed. [![enter image description here](https://i.stack.imgur.com/yOTBU.png)](https://i.stack.imgur.com/yOTBU.png) What it means? And how can I fix it?
Your `shares_content` function directly outputs content, which won't work if you're trying to assign the results to a variable or use it in a `return` statement within another function. You can change it to `return` the string: ``` function shares_content() { $content = "<div class='social-shares-container'><a href='https://www.facebook.com/sharer/sharer.php?u=%s'>Share on Facebook</a></div>"; return sprintf( $content, get_permalink() ); } ``` It's also worth pointing out here the use of `get_permalink()`. If you look at the source code, that function also `return`s its value. There is another API function, `the_permalink()`, which contains an `echo` instead of a `return`. That would also break your filter output. Most WordPress functions have two versions like this.
324,320
<p>I'm using a plugin (Comet Cache) to save static versions of a particular page I have on my site. </p> <p>Inside the plugin, I have the cache set to clear every 2 hours (that way this page can show the latest, non-cached) version of data its pulling from. </p> <p>The only issue is, for this page to get cached again, someone has to manually browser to it. </p> <p>I'm trying to automate this with WP Cron where it triggers a page load of the content. I've also been thinking of doing this with Python outside of WordPress. </p> <p>Would there be a best practices way of doing this? Thanks</p>
[ { "answer_id": 324246, "author": "Krzysiek Dróżdż", "author_id": 34172, "author_profile": "https://wordpress.stackexchange.com/users/34172", "pm_score": 0, "selected": false, "text": "<p>In this line:</p>\n\n<pre><code>return $content . shares_content();\n</code></pre>\n\n<p>You concaten...
2018/12/31
[ "https://wordpress.stackexchange.com/questions/324320", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/145165/" ]
I'm using a plugin (Comet Cache) to save static versions of a particular page I have on my site. Inside the plugin, I have the cache set to clear every 2 hours (that way this page can show the latest, non-cached) version of data its pulling from. The only issue is, for this page to get cached again, someone has to manually browser to it. I'm trying to automate this with WP Cron where it triggers a page load of the content. I've also been thinking of doing this with Python outside of WordPress. Would there be a best practices way of doing this? Thanks
Your `shares_content` function directly outputs content, which won't work if you're trying to assign the results to a variable or use it in a `return` statement within another function. You can change it to `return` the string: ``` function shares_content() { $content = "<div class='social-shares-container'><a href='https://www.facebook.com/sharer/sharer.php?u=%s'>Share on Facebook</a></div>"; return sprintf( $content, get_permalink() ); } ``` It's also worth pointing out here the use of `get_permalink()`. If you look at the source code, that function also `return`s its value. There is another API function, `the_permalink()`, which contains an `echo` instead of a `return`. That would also break your filter output. Most WordPress functions have two versions like this.
324,327
<p><strong>Scenario</strong></p> <p>I'm considering writing a custom wp-json endpoint to list ALL permalinks for everyone post in my wordpress.</p> <p><strong>Question</strong></p> <p>Is it possible to do this with a rest query + filters? eg. <a href="http://wpsite.com/wp-json/wp/v2/posts?filter%5Bonly-permalinks%5D" rel="nofollow noreferrer">http://wpsite.com/wp-json/wp/v2/posts?filter[only-permalinks]</a></p> <h1>Current Solution</h1> <p>I ended up writing a custom endpoint, code below:</p> <p><em>added to the bottom of functions.php</em></p> <pre><code>function get_all_slugs() { $posts = get_posts( array( 'numberposts' =&gt; -1, 'post_type' =&gt; &quot;screen&quot;, ) ); if ( empty( $posts ) ) { return null; } $posts_data = array(); foreach( $posts as $post ) { $id = $post-&gt;ID; $posts_data[] = (object) array( 'id' =&gt; $id, 'slug' =&gt; $post-&gt;post_name, //'title' =&gt; $post-&gt;post_title, ); } return $posts_data; } add_action( 'rest_api_init', function () { register_rest_route( 'row/v1', '/all-slugs', array( // /(?P&lt;post_type&gt;\d+)', array( 'methods' =&gt; 'GET', 'callback' =&gt; 'get_all_slugs', ) ); } ); </code></pre>
[ { "answer_id": 324332, "author": "Justin Waulters", "author_id": 137235, "author_profile": "https://wordpress.stackexchange.com/users/137235", "pm_score": 2, "selected": false, "text": "<p>I don't believe there is a default endpoint to let you get <em>all</em> the posts and return <em>on...
2018/12/31
[ "https://wordpress.stackexchange.com/questions/324327", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/13170/" ]
**Scenario** I'm considering writing a custom wp-json endpoint to list ALL permalinks for everyone post in my wordpress. **Question** Is it possible to do this with a rest query + filters? eg. [http://wpsite.com/wp-json/wp/v2/posts?filter[only-permalinks]](http://wpsite.com/wp-json/wp/v2/posts?filter%5Bonly-permalinks%5D) Current Solution ================ I ended up writing a custom endpoint, code below: *added to the bottom of functions.php* ``` function get_all_slugs() { $posts = get_posts( array( 'numberposts' => -1, 'post_type' => "screen", ) ); if ( empty( $posts ) ) { return null; } $posts_data = array(); foreach( $posts as $post ) { $id = $post->ID; $posts_data[] = (object) array( 'id' => $id, 'slug' => $post->post_name, //'title' => $post->post_title, ); } return $posts_data; } add_action( 'rest_api_init', function () { register_rest_route( 'row/v1', '/all-slugs', array( // /(?P<post_type>\d+)', array( 'methods' => 'GET', 'callback' => 'get_all_slugs', ) ); } ); ```
> > Is it possible to do this with a rest query + filters? eg. > <http://wpsite.com/wp-json/wp/v2/posts?filter[only-permalinks]> > > > Yes, since 4.9.8 (see [#43874](https://core.trac.wordpress.org/ticket/43874)) it's possible to render only fields needed with the `_fields` parameter. Examples -------- Render only the *permalinks*: <https://example.com/wp-json/wp/v2/posts?_fields=link> ``` [ { link: "https://example.com/foo/" }, { link: "https://example.com/bar/" }, ] ``` Render only the *post IDs* and *permalinks*: <https://example.com/wp-json/wp/v2/posts?_fields=id,link> ``` [ { id: 123, link: "https://example.com/foo/" }, { id: 234, link: "https://example.com/bar/" }, ] ``` Render only the *post IDs* and the *slugs*: <https://example.com/wp-json/wp/v2/posts?_fields=id,slug> ``` [ { id: 123, slug: "foo" }, { id: 234, slug: "bar" }, ] ``` Fetching All Available Items ---------------------------- Currently we have to fetch all available items with paging, like: ``` https://example.comwp-json/wp/v2/posts?_fields=slug&per_page=100&page=1 https://example.comwp-json/wp/v2/posts?_fields=slug&per_page=100&page=2 ... ``` where `per_page` is 10 by default and with maximum value of 100. Fetching all items in a single request can result in fatal errors if the number of items exceeds the available resources. The ticket [#43998](https://core.trac.wordpress.org/ticket/43998) to allow unbound requests (something like `per_page=-1`) for logged in users, was closed as *wontfix* because it doesn't scale and has performance issues. There's a ticket [#45140](https://core.trac.wordpress.org/ticket/45140) to increase the upper bound for `per_page` to few hundreds. Usually there's no need to display so many items in a user interface and there exists javascript techniques to handle the pagination. If more is really needed then one could filter the rest query via `rest_{$post_type}_query` to override the maximum default value of `posts_per_page`, at the risk of fatal errors if available resources are exceeded.
324,345
<p>i moved my site from http to https now i want to redirect the user into the new url but evry time i'm trying to edit .htaccess file i'm getting an error </p> <p>this is the working file content where xxxz is site name</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] &lt;/IfModule&gt; # END WordPress RewriteCond %{HTTP_HOST} ^xxxz\.qa$ [OR] RewriteCond %{HTTP_HOST} ^www\.xxxz\.qa$ RewriteCond %{REQUEST_URI} !^/\.well-known/cpanel-dcv/[0-9a-zA-Z_-]+$ RewriteCond %{REQUEST_URI} !^/\.well-known/pki-validation/[A-F0-9] {32}\.txt(?:\ Comodo\ DCV)?$ RewriteRule ^/?$ "http\:\/\/xxxz\.com\.qa" [R=301,L] </code></pre> <p>what i'm trying to edit is to add the following code in the top of the file as i read </p> <pre><code>RewriteEngine on RewriteCond %{HTTP_HOST} ^xxxz.com.qa [NC,OR] RewriteCond %{HTTP_HOST} ^www.xxxz.com.qa [NC] RewriteRule ^(.*)$ https://www.xxxz.com.qa/$1 [L,R=301,NC] </code></pre> <p>but its not working so what do u think </p>
[ { "answer_id": 324355, "author": "Md. Ehsanul Haque Kanan", "author_id": 75705, "author_profile": "https://wordpress.stackexchange.com/users/75705", "pm_score": 0, "selected": false, "text": "<p>The best way for setting up Permanent 301 Redirects is by editing .htaccess with the required...
2019/01/01
[ "https://wordpress.stackexchange.com/questions/324345", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/82887/" ]
i moved my site from http to https now i want to redirect the user into the new url but evry time i'm trying to edit .htaccess file i'm getting an error this is the working file content where xxxz is site name ``` # 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 RewriteCond %{HTTP_HOST} ^xxxz\.qa$ [OR] RewriteCond %{HTTP_HOST} ^www\.xxxz\.qa$ RewriteCond %{REQUEST_URI} !^/\.well-known/cpanel-dcv/[0-9a-zA-Z_-]+$ RewriteCond %{REQUEST_URI} !^/\.well-known/pki-validation/[A-F0-9] {32}\.txt(?:\ Comodo\ DCV)?$ RewriteRule ^/?$ "http\:\/\/xxxz\.com\.qa" [R=301,L] ``` what i'm trying to edit is to add the following code in the top of the file as i read ``` RewriteEngine on RewriteCond %{HTTP_HOST} ^xxxz.com.qa [NC,OR] RewriteCond %{HTTP_HOST} ^www.xxxz.com.qa [NC] RewriteRule ^(.*)$ https://www.xxxz.com.qa/$1 [L,R=301,NC] ``` but its not working so what do u think
> > > ``` > RewriteCond %{HTTP_HOST} ^xxxz.com.qa [NC,OR] > RewriteCond %{HTTP_HOST} ^www.xxxz.com.qa [NC] > RewriteRule ^(.*)$ https://www.xxxz.com.qa/$1 [L,R=301,NC] > > ``` > > This will result in a redirect loop as it will repeatedly redirect `https://www.xxxz.com.qa/<url>` to `https://www.xxxz.com.qa/<url>` again and again... If you want to redirect from HTTP then you need to check that the request was for HTTP before redirecting to HTTPS. For example: ``` RewriteCond %{HTTPS} off RewriteRule (.*) https://%{HTTP_HOST}/$1 [R=301,L] ``` No need for the `NC` flag, as you are simply matching everything anyway. --- However, this conflicts with the existing directives at the end of your file: > > > ``` > RewriteCond %{HTTP_HOST} ^xxxz\.qa$ [OR] > RewriteCond %{HTTP_HOST} ^www\.xxxz\.qa$ > RewriteCond %{REQUEST_URI} !^/\.well-known/cpanel-dcv/[0-9a-zA-Z_-]+$ > RewriteCond %{REQUEST_URI} !^/\.well-known/pki-validation/[A-F0-9] {32}\.txt(?:\ Comodo\ DCV)?$ > RewriteRule ^/?$ "http\:\/\/xxxz\.com\.qa" [R=301,L] > > ``` > > These directives should probably be deleted. (Fortunately, they probably aren't doing anything anyway - because they are *after* the WordPress front-controller.)
324,441
<p>How do I get all terms matching:</p> <ol> <li>custom taxonomy "<code>company</code>"</li> <li>only where term meta (ACF field) "<code>tags</code>" value matches a given string, "<code>Publishing</code>"</li> <li>only if the term has any posts of custom type "<code>article</code>"</li> <li>but those posts must only have a taxonomy "<code>format</code>" value of term "<code>viewpoint</code>" or one of its children</li> </ol> <p>... ?</p> <p>My current code fulfils 1) and 2) above - but I do not how how to add the additional constraints of 3) "<code>article</code>" and 4) "<code>format</code>"...</p> <pre><code> $args = array( 'meta_query' =&gt; array( array( 'key' =&gt; 'tags', 'value' =&gt; 'Publishing', 'compare' =&gt; 'LIKE' ) ), 'taxonomy' =&gt; 'company', 'hide_empty' =&gt; false, 'number' =&gt; 10, ); $orgs_matched = get_terms($args); echo '&lt;ul class="list-group list-unstyled"&gt;'; foreach ($orgs_matched as $matching_org) { echo '&lt;li class="list-group-item d-flex justify-content-between align-items-center"&gt;'; echo '&lt;span&gt;&lt;img src="https://www.google.com/s2/favicons?domain='.get_field( 'domain', $matching_org ).'" class="mr-2"&gt;&lt;a href="' . esc_url( get_term_link( $matching_org ) ) . '" alt="' . esc_attr( sprintf( __( 'View all post filed under %s', 'my_localization_domain' ), $matching_org-&gt;name ) ) . '"&gt;' . $matching_org-&gt;name . '&lt;/a&gt;&lt;/span&gt;'; echo '&lt;span class="badge badge-primary badge-pill"&gt;'.$matching_org-&gt;count.'&lt;/span&gt;'; echo '&lt;/li&gt;'; } echo '&lt;/ul&gt;'; </code></pre> <p>In my setup, "<code>article</code>" posts can have associations with:</p> <ul> <li>"<code>format</code>" taxonomy term, with name values including "<code>viewpoint</code>".</li> <li>"<code>company</code>" taxonomy terms, which themselves have an ACF Checkbox field, "<code>tags</code>", one of whose values is "<code>Publishing</code>". </li> </ul> <p>I want to get only the "<code>company</code>" terms which have a "<code>tags</code>" value of "<code>Publishing</code>" - but I am only interested in getting those companies which have associated "<code>article</code>" posts that also have taxonomy "<code>format</code>" values of "<code>viewpoint</code>" or beneath.</p> <p>For each resulting "<code>company</code>' term, I would want to count the number of "<code>article</code>" posts of taxonomy format "<code>viewpoint</code>" and beneath.</p> <h1>Update:</h1> <p>I'm contemplating the method below. Basically, the standard <code>get_terms</code> below, which works, and then <strong>stepping through the resulting array to filter out any terms which don't have the term</strong> in question...</p> <pre><code> $args_for_short = array( 'taxonomy' =&gt; 'company', // ACF "tag" checkbox field 'meta_query' =&gt; array( array( 'key' =&gt; 'tags', 'value' =&gt; 'Publishing', 'compare' =&gt; 'LIKE' ) ), 'orderby' =&gt; 'count', 'order' =&gt; 'desc', 'hide_empty' =&gt; false, 'number' =&gt; 10, ); // array: actual term objects $orgs_list_short = get_terms($args_for_short); // Strip non-Viewpoints out of the terms array $orgs_list_short_filtered = array(); foreach ($orgs_list_short as $org_short_single) { // Get all posts of type 'article' // For each 'article' // Examine associated "format" terms // If 'format' term "viewpoint" or child is not present // Remove this term from the term object array } </code></pre>
[ { "answer_id": 324355, "author": "Md. Ehsanul Haque Kanan", "author_id": 75705, "author_profile": "https://wordpress.stackexchange.com/users/75705", "pm_score": 0, "selected": false, "text": "<p>The best way for setting up Permanent 301 Redirects is by editing .htaccess with the required...
2019/01/02
[ "https://wordpress.stackexchange.com/questions/324441", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/39300/" ]
How do I get all terms matching: 1. custom taxonomy "`company`" 2. only where term meta (ACF field) "`tags`" value matches a given string, "`Publishing`" 3. only if the term has any posts of custom type "`article`" 4. but those posts must only have a taxonomy "`format`" value of term "`viewpoint`" or one of its children ... ? My current code fulfils 1) and 2) above - but I do not how how to add the additional constraints of 3) "`article`" and 4) "`format`"... ``` $args = array( 'meta_query' => array( array( 'key' => 'tags', 'value' => 'Publishing', 'compare' => 'LIKE' ) ), 'taxonomy' => 'company', 'hide_empty' => false, 'number' => 10, ); $orgs_matched = get_terms($args); echo '<ul class="list-group list-unstyled">'; foreach ($orgs_matched as $matching_org) { echo '<li class="list-group-item d-flex justify-content-between align-items-center">'; echo '<span><img src="https://www.google.com/s2/favicons?domain='.get_field( 'domain', $matching_org ).'" class="mr-2"><a href="' . esc_url( get_term_link( $matching_org ) ) . '" alt="' . esc_attr( sprintf( __( 'View all post filed under %s', 'my_localization_domain' ), $matching_org->name ) ) . '">' . $matching_org->name . '</a></span>'; echo '<span class="badge badge-primary badge-pill">'.$matching_org->count.'</span>'; echo '</li>'; } echo '</ul>'; ``` In my setup, "`article`" posts can have associations with: * "`format`" taxonomy term, with name values including "`viewpoint`". * "`company`" taxonomy terms, which themselves have an ACF Checkbox field, "`tags`", one of whose values is "`Publishing`". I want to get only the "`company`" terms which have a "`tags`" value of "`Publishing`" - but I am only interested in getting those companies which have associated "`article`" posts that also have taxonomy "`format`" values of "`viewpoint`" or beneath. For each resulting "`company`' term, I would want to count the number of "`article`" posts of taxonomy format "`viewpoint`" and beneath. Update: ======= I'm contemplating the method below. Basically, the standard `get_terms` below, which works, and then **stepping through the resulting array to filter out any terms which don't have the term** in question... ``` $args_for_short = array( 'taxonomy' => 'company', // ACF "tag" checkbox field 'meta_query' => array( array( 'key' => 'tags', 'value' => 'Publishing', 'compare' => 'LIKE' ) ), 'orderby' => 'count', 'order' => 'desc', 'hide_empty' => false, 'number' => 10, ); // array: actual term objects $orgs_list_short = get_terms($args_for_short); // Strip non-Viewpoints out of the terms array $orgs_list_short_filtered = array(); foreach ($orgs_list_short as $org_short_single) { // Get all posts of type 'article' // For each 'article' // Examine associated "format" terms // If 'format' term "viewpoint" or child is not present // Remove this term from the term object array } ```
> > > ``` > RewriteCond %{HTTP_HOST} ^xxxz.com.qa [NC,OR] > RewriteCond %{HTTP_HOST} ^www.xxxz.com.qa [NC] > RewriteRule ^(.*)$ https://www.xxxz.com.qa/$1 [L,R=301,NC] > > ``` > > This will result in a redirect loop as it will repeatedly redirect `https://www.xxxz.com.qa/<url>` to `https://www.xxxz.com.qa/<url>` again and again... If you want to redirect from HTTP then you need to check that the request was for HTTP before redirecting to HTTPS. For example: ``` RewriteCond %{HTTPS} off RewriteRule (.*) https://%{HTTP_HOST}/$1 [R=301,L] ``` No need for the `NC` flag, as you are simply matching everything anyway. --- However, this conflicts with the existing directives at the end of your file: > > > ``` > RewriteCond %{HTTP_HOST} ^xxxz\.qa$ [OR] > RewriteCond %{HTTP_HOST} ^www\.xxxz\.qa$ > RewriteCond %{REQUEST_URI} !^/\.well-known/cpanel-dcv/[0-9a-zA-Z_-]+$ > RewriteCond %{REQUEST_URI} !^/\.well-known/pki-validation/[A-F0-9] {32}\.txt(?:\ Comodo\ DCV)?$ > RewriteRule ^/?$ "http\:\/\/xxxz\.com\.qa" [R=301,L] > > ``` > > These directives should probably be deleted. (Fortunately, they probably aren't doing anything anyway - because they are *after* the WordPress front-controller.)
324,447
<p>www.beautifulcreationsphotography.co.uk</p> <p>I have a client who used to have a Wordpress blog, however for some reason its carrying over to her new site and causing havok with Yoast.</p> <p>Ive added in this filter below but it doesnt seem to have worked.</p> <pre><code>add_filter( 'jetpack_enable_open_graph', '__return_false' ); </code></pre> <p>Any ideas?</p>
[ { "answer_id": 324448, "author": "RiddleMeThis", "author_id": 86845, "author_profile": "https://wordpress.stackexchange.com/users/86845", "pm_score": 0, "selected": false, "text": "<p>Make sure you are not seeing a cached version of the site.</p>\n\n<p>Also, try adding priority to the fi...
2019/01/02
[ "https://wordpress.stackexchange.com/questions/324447", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/23874/" ]
www.beautifulcreationsphotography.co.uk I have a client who used to have a Wordpress blog, however for some reason its carrying over to her new site and causing havok with Yoast. Ive added in this filter below but it doesnt seem to have worked. ``` add_filter( 'jetpack_enable_open_graph', '__return_false' ); ``` Any ideas?
The site above does not use Jetpack's Open Graph Meta Tags. It uses Yoast SEO's own tags. In fact, on any site, if you use the Yoast SEO plugin and have activated the Open Graph meta tags under SEO > Social > Facebook, Jetpack's own Open Graph Meta Tags will never be added. Only the tags from Yoast will appear on your site. The 2 plugins are built to work well together, so you have no risk of having a duplicate set of tags if you use the 2 plugins together, and you do not need to add any code snippets. That said, Facebook does cache information about each page on your site, so it is possible that even after you update Open Graph Meta Tags on a site, the old title / description / image is still used when sharing links on Facebook because you are seeing cached data. You can refresh that cache manually by using Facebook's Debug tool: <https://developers.facebook.com/tools/debug/> You can click on "Scape again" there to refresh the data.
324,509
<p>I tried it all and since i am not so good in this coding, I want to hide a category and his posts from the homepage I tried all plugins especially wp hide post but it needs pro version and seems Support is not answering on my emails so i rather do not buy that i tried the code that i found everywhere see below,</p> <p>however my theme has his own categories for products <code>(taxonomy=download_category&amp;post_type=download)</code> the code i found and tried in many ways to change</p> <pre><code>function exclude_category($query) { if ( $query-&gt;is_home() ) { $query-&gt;set( 'cat', '-156, -58,-154,-155' ); } return $query; } add_filter( 'pre_get_posts', 'exclude_category' ); so 1 of the things i tried was function exclude_category_download($query) { if ( $query-&gt;is_home() ) { $query-&gt;set('cat', '-156, -58,-154,-155'); } return $query; } add_filter('pre_get_posts', 'exclude_category_download'); </code></pre> <p>I am completely lost could really use some help</p>
[ { "answer_id": 324473, "author": "Krzysiek Dróżdż", "author_id": 34172, "author_profile": "https://wordpress.stackexchange.com/users/34172", "pm_score": 0, "selected": false, "text": "<p>Function names have to be unique in PHP, so if some function is assigned to given hook, then there is...
2019/01/03
[ "https://wordpress.stackexchange.com/questions/324509", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/158239/" ]
I tried it all and since i am not so good in this coding, I want to hide a category and his posts from the homepage I tried all plugins especially wp hide post but it needs pro version and seems Support is not answering on my emails so i rather do not buy that i tried the code that i found everywhere see below, however my theme has his own categories for products `(taxonomy=download_category&post_type=download)` the code i found and tried in many ways to change ``` function exclude_category($query) { if ( $query->is_home() ) { $query->set( 'cat', '-156, -58,-154,-155' ); } return $query; } add_filter( 'pre_get_posts', 'exclude_category' ); so 1 of the things i tried was function exclude_category_download($query) { if ( $query->is_home() ) { $query->set('cat', '-156, -58,-154,-155'); } return $query; } add_filter('pre_get_posts', 'exclude_category_download'); ``` I am completely lost could really use some help
I read the whole core files in wordpress. And it is split multiple file across the core folders actually it is very smart of them to do such a thing
324,601
<p><a href="https://i.stack.imgur.com/GMWYk.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/GMWYk.png" alt="enter image description here"></a></p> <p>Hi, my website im doing now is nurulsazlinprubsntakaful.com</p> <p>i want to delete home ---> Home as per pic i attach.</p> <p>i read its about breadcrumbs. i also use inspect function in web browser.i get code like this from some discussion in other forum. .title-box { display: none; }</p> <p>i put in additional css. still not solve.</p> <p>im very new in wordpress. hope someone can help me...tq2.</p> <p>other than that, i also awant to delete icon share. </p>
[ { "answer_id": 324602, "author": "Frank P. Walentynowicz", "author_id": 32851, "author_profile": "https://wordpress.stackexchange.com/users/32851", "pm_score": 2, "selected": true, "text": "<p>First, check your theme's settings, if breadcrumbs can be turned on/off. If not, the following ...
2019/01/04
[ "https://wordpress.stackexchange.com/questions/324601", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/158296/" ]
[![enter image description here](https://i.stack.imgur.com/GMWYk.png)](https://i.stack.imgur.com/GMWYk.png) Hi, my website im doing now is nurulsazlinprubsntakaful.com i want to delete home ---> Home as per pic i attach. i read its about breadcrumbs. i also use inspect function in web browser.i get code like this from some discussion in other forum. .title-box { display: none; } i put in additional css. still not solve. im very new in wordpress. hope someone can help me...tq2. other than that, i also awant to delete icon share.
First, check your theme's settings, if breadcrumbs can be turned on/off. If not, the following CSS will hide breadcrumbs: ``` nav.breadcrumbs { display: none; } ``` Put the above lines, into Customize -> Additional CSS, or into your theme's `style.css`. To remove sharing buttons, use the following CSS: ``` div.share.js-share { display: none; } ```
324,643
<p>The WordPress block API for Gutenberg has a <code>withInstanceId</code> <a href="https://github.com/WordPress/gutenberg/tree/master/packages/compose/src/with-instance-id" rel="nofollow noreferrer">package</a>. </p> <p>They say, </p> <blockquote> <p>Some components need to generate a unique id for each instance. This could serve as suffixes to element ID's for example. Wrapping a component with withInstanceId provides a unique instanceId to serve this purpose.</p> </blockquote> <p>and show an example:</p> <pre><code>/** * WordPress dependencies */ import { withInstanceId } from '@wordpress/compose'; function MyCustomElement( { instanceId } ) { return ( &lt;div id={ `my-custom-element-${ instanceId }` }&gt; content &lt;/div&gt; ); } export default withInstanceId( MyCustomElement ); </code></pre> <p>It seems like it is just being used for html ids? As to not have duplicate id names? Is there any other usage for it? If i just export my component using <code>export default withInstanceId( MyCustomElement )</code> will the entire component have a unique id?</p>
[ { "answer_id": 324647, "author": "Alvaro", "author_id": 16533, "author_profile": "https://wordpress.stackexchange.com/users/16533", "pm_score": 2, "selected": true, "text": "<p>The generated <code>id</code> is added to the component's props. So it can be accessed through <code>this.props...
2019/01/04
[ "https://wordpress.stackexchange.com/questions/324643", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/1613/" ]
The WordPress block API for Gutenberg has a `withInstanceId` [package](https://github.com/WordPress/gutenberg/tree/master/packages/compose/src/with-instance-id). They say, > > Some components need to generate a unique id for each instance. This > could serve as suffixes to element ID's for example. Wrapping a > component with withInstanceId provides a unique instanceId to serve > this purpose. > > > and show an example: ``` /** * WordPress dependencies */ import { withInstanceId } from '@wordpress/compose'; function MyCustomElement( { instanceId } ) { return ( <div id={ `my-custom-element-${ instanceId }` }> content </div> ); } export default withInstanceId( MyCustomElement ); ``` It seems like it is just being used for html ids? As to not have duplicate id names? Is there any other usage for it? If i just export my component using `export default withInstanceId( MyCustomElement )` will the entire component have a unique id?
The generated `id` is added to the component's props. So it can be accessed through `this.props.instanceId` inside the component. In the example you posted it is being used to assign a unique [id attribute](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/id) to the html element. However it can be used for custom logic inside react. Just as an example, you can assign each component an `id` and then save its data to the redux store, that way when you need to access the data from an element inside the store you can use its `id` to find it.
324,649
<p>I have following scenario:</p> <pre><code>my-domain-name.com/google.com my-domain-name.com/twitter.com </code></pre> <p>I need a custom permalink structure to pass <code>google.com</code> or <code>twitter.com</code> to <code>domain_name</code> query variable.</p> <p>I have tried following code:</p> <pre><code>add_rewrite_tag('%domain_name%', '([^&amp;]+)'); add_rewrite_rule('^/([^/]*)/?','index.php?domain_name=$matches[1]','top'); </code></pre> <p>But not working</p> <p>For better example Check this site: <code>http://currentlydown.com/facebook.com</code> I am trying to do the similar</p>
[ { "answer_id": 324713, "author": "rifi2k", "author_id": 158385, "author_profile": "https://wordpress.stackexchange.com/users/158385", "pm_score": 2, "selected": false, "text": "<p>I'm not sure if I should assume that you were issuing your examples inside of the init hook, but if not that...
2019/01/04
[ "https://wordpress.stackexchange.com/questions/324649", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/68993/" ]
I have following scenario: ``` my-domain-name.com/google.com my-domain-name.com/twitter.com ``` I need a custom permalink structure to pass `google.com` or `twitter.com` to `domain_name` query variable. I have tried following code: ``` add_rewrite_tag('%domain_name%', '([^&]+)'); add_rewrite_rule('^/([^/]*)/?','index.php?domain_name=$matches[1]','top'); ``` But not working For better example Check this site: `http://currentlydown.com/facebook.com` I am trying to do the similar
The problem was solved by just one line of code. I am thankful to @rifi2k for long discussion and proposing different solutions. Here is the solutions: Add following code to functions.php ``` function custom_rewrite_basic() { add_rewrite_tag('%domain_name%', '([a-z]{1,60}\.[a-z]{2,})'); } add_action('init', 'custom_rewrite_basic'); ``` Then from permalink settings, select `Custom Structure` and add newly created tag by only in our case its `/%domain_name%/` save settings.
324,660
<p>When trying to edit a wordpress post (page) the editor loads indefinitely, console shows JS error with post.php / polyfill, see code below. To me it seems to be a typo and I have no idea where the line is injected so I could change it manually. </p> <p>Disabling all plugins did not change anything, neither did disabling Gutenberg. I am not much of a coder, nevertheless it seems to me there should not be a double quotation mark after the last 'defer"... in the line of code.</p> <p>I am running WP 5.0.2 on Apache (Domainfactory) in a managed server environment, Theme is Enfold by Kriesi. Re-installing Wordpress and the theme (copied from working installations) changed nothing so far.</p> <p>The reported error in the console is "Uncaught SyntaxError: missing ) after argument list" in <a href="https://.../wp-admin/post.php?post=23&amp;action=edit&amp;lang=de&amp;classic-editor=1:238" rel="nofollow noreferrer">https://.../wp-admin/post.php?post=23&amp;action=edit&amp;lang=de&amp;classic-editor=1:238</a></p> <p>There it says</p> <pre><code>( 'fetch' in window ) || document.write( '&lt;script src="https://12345678-123.ch/wp-includes/js/dist/vendor/wp-polyfill-fetch.min.js?ver=3.0.0' defer='defer"&gt;&lt;/scr' + 'ipt&gt;' );( document.contains ) || document.write( '&lt;script src="https://12345678-123.ch/wp-includes/js/dist/vendor/wp-polyfill-node-contains.min.js?ver=3.26.0-0' defer='defer"&gt;&lt;/scr' + 'ipt&gt;' );( window.FormData &amp;&amp; window.FormData.prototype.keys ) || document.write( '&lt;script src="https://12345678-123.ch/wp-includes/js/dist/vendor/wp-polyfill-formdata.min.js?ver=3.0.12' defer='defer"&gt;&lt;/scr' + 'ipt&gt;' );( Element.prototype.matches &amp;&amp; Element.prototype.closest ) || document.write( '&lt;script src="https://12345678-123.ch/wp-includes/js/dist/vendor/wp-polyfill-element-closest.min.js?ver=2.0.2' defer='defer"&gt;&lt;/scr' + 'ipt&gt;' ); </code></pre> <p>Any idea would be much appreciated.</p>
[ { "answer_id": 325650, "author": "Kostiantyn Petlia", "author_id": 104932, "author_profile": "https://wordpress.stackexchange.com/users/104932", "pm_score": 2, "selected": true, "text": "<p>Here is an answer: <a href=\"https://wordpress.stackexchange.com/questions/325570/wordpress-v5-0-3...
2019/01/04
[ "https://wordpress.stackexchange.com/questions/324660", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/110944/" ]
When trying to edit a wordpress post (page) the editor loads indefinitely, console shows JS error with post.php / polyfill, see code below. To me it seems to be a typo and I have no idea where the line is injected so I could change it manually. Disabling all plugins did not change anything, neither did disabling Gutenberg. I am not much of a coder, nevertheless it seems to me there should not be a double quotation mark after the last 'defer"... in the line of code. I am running WP 5.0.2 on Apache (Domainfactory) in a managed server environment, Theme is Enfold by Kriesi. Re-installing Wordpress and the theme (copied from working installations) changed nothing so far. The reported error in the console is "Uncaught SyntaxError: missing ) after argument list" in <https://.../wp-admin/post.php?post=23&action=edit&lang=de&classic-editor=1:238> There it says ``` ( 'fetch' in window ) || document.write( '<script src="https://12345678-123.ch/wp-includes/js/dist/vendor/wp-polyfill-fetch.min.js?ver=3.0.0' defer='defer"></scr' + 'ipt>' );( document.contains ) || document.write( '<script src="https://12345678-123.ch/wp-includes/js/dist/vendor/wp-polyfill-node-contains.min.js?ver=3.26.0-0' defer='defer"></scr' + 'ipt>' );( window.FormData && window.FormData.prototype.keys ) || document.write( '<script src="https://12345678-123.ch/wp-includes/js/dist/vendor/wp-polyfill-formdata.min.js?ver=3.0.12' defer='defer"></scr' + 'ipt>' );( Element.prototype.matches && Element.prototype.closest ) || document.write( '<script src="https://12345678-123.ch/wp-includes/js/dist/vendor/wp-polyfill-element-closest.min.js?ver=2.0.2' defer='defer"></scr' + 'ipt>' ); ``` Any idea would be much appreciated.
Here is an answer: [WordPress v5.0.3 Gutenberg & JS error "Uncaught SyntaxError: missing ) after argument list"](https://wordpress.stackexchange.com/questions/325570/wordpress-v5-0-3-gutenberg-js-error-uncaught-syntaxerror-missing-after-arg) The simplest way: Find & delete PHP Hook which added 'defer' to script (in the function.php file). Or if you have skills you can edit the code of the hook. Reason: Confusion/conflict with quotes (' & ") witch break down JS. About 'defer' you can read here: <https://www.w3schools.com/tags/att_script_defer.asp> This is probably due to speed optimization on your website.
324,751
<p>I want to obtain a path of all parents for current page. Something similar to breadcrub but used only for pages listed in menu.</p> <p>For example if i have following structure:</p> <pre><code>L Menu L Sub menu L Current page L Sub menu 2 L Menu 2 </code></pre> <p>I want to obtain:</p> <pre><code>Menu &gt;&gt; Sub Menu &gt;&gt; Current page </code></pre> <p>I am using WordPress 5.0.2. I tried various plugins but they show only current page instead of whole path.</p> <p>How do i solve this issue?</p>
[ { "answer_id": 324767, "author": "Milo", "author_id": 4771, "author_profile": "https://wordpress.stackexchange.com/users/4771", "pm_score": 3, "selected": true, "text": "<p>The <a href=\"https://developer.wordpress.org/reference/functions/wp_get_nav_menu_items/\" rel=\"nofollow noreferre...
2019/01/05
[ "https://wordpress.stackexchange.com/questions/324751", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/158330/" ]
I want to obtain a path of all parents for current page. Something similar to breadcrub but used only for pages listed in menu. For example if i have following structure: ``` L Menu L Sub menu L Current page L Sub menu 2 L Menu 2 ``` I want to obtain: ``` Menu >> Sub Menu >> Current page ``` I am using WordPress 5.0.2. I tried various plugins but they show only current page instead of whole path. How do i solve this issue?
The [`wp_get_nav_menu_items`](https://developer.wordpress.org/reference/functions/wp_get_nav_menu_items/) function will give you an array of menu item objects for a given menu. These objects contain a mixture of data specific to that unique menu item, as well as the post/page/link data the menu item refers to. You can use this array of menu items to find the current page, and then check the parent field of the item to get each parent in a loop. Here's an example that should get you most of the way there. Use it by calling `wpd_nav_menu_breadcrumbs( 'your menu' )` in your template. Read the comments to see what's happening in each section. ``` // helper function to find a menu item in an array of items function wpd_get_menu_item( $field, $object_id, $items ){ foreach( $items as $item ){ if( $item->$field == $object_id ) return $item; } return false; } function wpd_nav_menu_breadcrumbs( $menu ){ // get menu items by menu id, slug, name, or object $items = wp_get_nav_menu_items( $menu ); if( false === $items ){ echo 'Menu not found'; return; } // get the menu item for the current page $item = wpd_get_menu_item( 'object_id', get_queried_object_id(), $items ); if( false === $item ){ return; } // start an array of objects for the crumbs $menu_item_objects = array( $item ); // loop over menu items to get the menu item parents while( 0 != $item->menu_item_parent ){ $item = wpd_get_menu_item( 'ID', $item->menu_item_parent, $items ); array_unshift( $menu_item_objects, $item ); } // output crumbs $crumbs = array(); foreach( $menu_item_objects as $menu_item ){ $link = '<a href="%s">%s</a>'; $crumbs[] = sprintf( $link, $menu_item->url, $menu_item->title ); } echo join( ' > ', $crumbs ); } ``` \*disclaimer: not rigorously tested, use at your own risk
324,762
<p>Based on research here and elsewhere, I have the following code that sets a cookie on a site:</p> <pre><code>add_action( 'init', 'my_set_cookie',1 ); function my_set_cookie() { if (! $_COOKIE['mycookie']) { $guid = 'xxxx'; // normally a real guid value so it will be unique setcookie('mycookie', $guid, time()+(3600*24*30),'/'); } return; } </code></pre> <p>But even though the <code>init</code> hook is used, and with a priority of '1', I still get 'headers already sent' error for the 'setcookie' statement. Using another priority (say '99') also gives the error.</p> <p>Is there a different hook to use to set the cookie?</p>
[ { "answer_id": 324786, "author": "Krzysiek Dróżdż", "author_id": 34172, "author_profile": "https://wordpress.stackexchange.com/users/34172", "pm_score": 2, "selected": false, "text": "<p>It’s a problem as old as WP, or even older...</p>\n\n<p>You can’t set cookies, or send any other head...
2019/01/06
[ "https://wordpress.stackexchange.com/questions/324762", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/29416/" ]
Based on research here and elsewhere, I have the following code that sets a cookie on a site: ``` add_action( 'init', 'my_set_cookie',1 ); function my_set_cookie() { if (! $_COOKIE['mycookie']) { $guid = 'xxxx'; // normally a real guid value so it will be unique setcookie('mycookie', $guid, time()+(3600*24*30),'/'); } return; } ``` But even though the `init` hook is used, and with a priority of '1', I still get 'headers already sent' error for the 'setcookie' statement. Using another priority (say '99') also gives the error. Is there a different hook to use to set the cookie?
After trying various hooks to try to set the cookie before the theme loaded it's header.php file (none of the hooks worked, even those very early in the 'load cycle'), I figure that I might temporarily disable the error so that the cookie can be set. I based my answer on [this question](https://stackoverflow.com/a/26154061/1466973). Now, I realize that this is not a standard way of doing it, and probably not recommended, but my justification is that if a theme is not doing things 'normally' or 'correct', and therefore causing the 'headers already sent' error message to display on the screen, then quickly bypassing that error display (and then restoring whatever error trapping settings are in place) is a solution that will work in my situation. It appears from my testing that even if 'headers already sent' happens, the cookie is set properly. That doesn't really sound like it should work, but it appeared to work in my testing. So, the technique I used is * get the current error settings to be used later * turn off display of errors * do things that cause the error (in my case, set the cookie) * restore the error settings to original valuess Here is the code that I used. Again, probably not 'kosher', but it worked in my case. ``` // some themes cause a 'headers already sent' message, so we bypass it here // by turning off that error message while we set the cookie. // see https://stackoverflow.com/a/26154061/1466973 // $random_guid is a guid set previously $previousErrorLevel = error_reporting(); error_reporting(\E_ERROR); setcookie('cookie_name', $random_guid,time()+(3600*24*30),'/'); error_reporting($previousErrorLevel); ``` Since it worked for my case, I am marking my answer as correct, although the other answer is valid. And I expect a couple of downvotes, as this is not kosher. But it worked for my problem and circumstances.
324,795
<pre><code>add_filter( 'woocommerce_order_button_text', 'woo_custom_order_button_text' ); function woo_custom_order_button_text() { return __( 'Your new button text here', 'woocommerce' ); } </code></pre> <p>Above is the example how we can change the woocommerce "Place order" Text, but what if we want to change the CSS also how can we have the whole button customized along with our own button classes and CSS.</p>
[ { "answer_id": 324796, "author": "Md. Ehsanul Haque Kanan", "author_id": 75705, "author_profile": "https://wordpress.stackexchange.com/users/75705", "pm_score": 0, "selected": false, "text": "<p>You have to put your PHP codes at the bottom of <strong>functions.php</strong> file of your c...
2019/01/06
[ "https://wordpress.stackexchange.com/questions/324795", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/152578/" ]
``` add_filter( 'woocommerce_order_button_text', 'woo_custom_order_button_text' ); function woo_custom_order_button_text() { return __( 'Your new button text here', 'woocommerce' ); } ``` Above is the example how we can change the woocommerce "Place order" Text, but what if we want to change the CSS also how can we have the whole button customized along with our own button classes and CSS.
I will try to answer your question. since you know how the text can be changed - let me take it for CSS. View in the browser - The browser is rendering the button like this → ``` <button type="submit" class="button alt" name="woocommerce_checkout_place_order" id="place_order" value="Confirm order" data-value="Confirm order">Confirm order</button> ``` [![enter image description here](https://i.stack.imgur.com/Tmt8C.png)](https://i.stack.imgur.com/Tmt8C.png) Now create a folder by the name of "woocommerce" in your child theme/theme and create a folder by the name of checkout, and in that folder put payment.php from [woo commerce template.](https://github.com/woocommerce/woocommerce/blob/master/templates/checkout/payment.php) (Look for the latest template) and change the button class there with class that you want. You are all done.
324,908
<p>I have been follow a tutorial here: <a href="https://rudrastyh.com/gutenberg/remove-default-blocks.html" rel="noreferrer">https://rudrastyh.com/gutenberg/remove-default-blocks.html</a> Where it discusses how to remove default Gutenberg blocks like so:</p> <pre><code>add_filter( 'allowed_block_types', 'misha_allowed_block_types', 10, 2 ); function misha_allowed_block_types( $allowed_blocks, $post ) { $allowed_blocks = array( 'core/image', 'core/paragraph', 'core/heading', 'core/list' ); if( $post-&gt;post_type === 'page' ) { $allowed_blocks[] = 'core/shortcode'; } return $allowed_blocks; } </code></pre> <p>So what this is doing is limiting the default Gutenberg blocks to image, paragraph, heading, and list. I then set the page post type to also allow for the shortcode block. So this works fine, but I am now having an issue where it removes the functionality of reusable blocks and I can't figure out what needs to be added to add that functionality back.</p> <p>I tried commenting on that article, but the author wasn't able to think of a solution currently. I was wondering if anyone had any ideas on adding the reusable block functionality back after adding the above code snippet?</p>
[ { "answer_id": 324929, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 5, "selected": true, "text": "<p>The <em>reusable block</em> is registered with the <code>core/block</code> name.</p>\n\n<p>I tried to add it t...
2019/01/07
[ "https://wordpress.stackexchange.com/questions/324908", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/153404/" ]
I have been follow a tutorial here: <https://rudrastyh.com/gutenberg/remove-default-blocks.html> Where it discusses how to remove default Gutenberg blocks like so: ``` add_filter( 'allowed_block_types', 'misha_allowed_block_types', 10, 2 ); function misha_allowed_block_types( $allowed_blocks, $post ) { $allowed_blocks = array( 'core/image', 'core/paragraph', 'core/heading', 'core/list' ); if( $post->post_type === 'page' ) { $allowed_blocks[] = 'core/shortcode'; } return $allowed_blocks; } ``` So what this is doing is limiting the default Gutenberg blocks to image, paragraph, heading, and list. I then set the page post type to also allow for the shortcode block. So this works fine, but I am now having an issue where it removes the functionality of reusable blocks and I can't figure out what needs to be added to add that functionality back. I tried commenting on that article, but the author wasn't able to think of a solution currently. I was wondering if anyone had any ideas on adding the reusable block functionality back after adding the above code snippet?
The *reusable block* is registered with the `core/block` name. I tried to add it to the *allowed blocks* in the `allowed_block_types` filter, here's an example: ``` add_filter( 'allowed_block_types', 'wpse324908_allowed_block_types', 10, 2 ); function wpse324908_allowed_block_types( $allowed_blocks, $post ) { $allowed_blocks = array( 'core/block', // <-- Include to show reusable blocks in the block inserter. 'core/image', 'core/paragraph', ); return $allowed_blocks; } ``` and it showed the *reusable blocks* within the *block inserter*, if at least two other blocks were included as well: [![Reusable](https://i.stack.imgur.com/4hbq7.png)](https://i.stack.imgur.com/4hbq7.png) Looking at the `/wp-includes/js/dist/editor.js` we can e.g. see this check for `core/block` regarding including reusable blocks in the block inserter: ``` var selectors_canIncludeReusableBlockInInserter = function canIncludeReusableBlockInInserter(state, reusableBlock, rootClientId) { if (!selectors_canInsertBlockTypeUnmemoized(state, 'core/block', rootClientId)) { return false; } ```
324,923
<p>I'm a newbie at even trying to work with PHP, but thinking there may be a simple solution to this. EXIF exposure data is only displaying an "s", so there must be an error. </p> <p>I'd also like to display FNumber as "Aperture" with common f-stop, such as "f2.8", but it shows a fraction 28/10. Is there PHP code that can be inserted directly to the template file to convert this? In Wordpress image.php, there is code for simplifying fractions, but these values are not being passed through the file - they are being modified directly in the template file. There's definitely something wrong with this...</p> <pre><code>&lt;dt&gt;EXIF data:&lt;/dt&gt; &lt;dd&gt;&lt;ul&gt; &lt;?php foreach ($exif as $key =&gt; $value): if (($key != "Width") &amp;&amp; ($key != "Height") &amp;&amp; ($key !="DateTime")): ?&gt;&lt;li&gt;&lt;strong&gt;&lt;?php if ($key == "model") { echo "Camera"; } elseif ($key == "ExposureTime") { echo "Exposure"; $newvalue = explode("(", $value); $newvalue = substr($newvalue[2], 0, -1)."s"; } elseif ($key == "FNumber") { echo "Aperture"; } else { echo $key; } ?&gt;&lt;/strong&gt;: &lt;?php if (!$newvalue) { echo $value; } else { echo $newvalue; $newvalue = ''; } ?&gt;&lt;/li&gt; &lt;?php endif; endforeach; ?&gt; &lt;/ul&gt;&lt;/dd&gt;&lt;/dl&gt; </code></pre> <p>Here is the var_export($exif) info:</p> <pre><code>array ( 'Model' =&gt; 'Canon EOS 30D', 'DateTime' =&gt; '2006:12:23 08:35:02', 'ExposureTime' =&gt; '1/100', 'FNumber' =&gt; '28/10', 'ExposureProgram' =&gt; 3, 'ISOSpeedRatings' =&gt; 200, 'ExifVersion' =&gt; '0221', 'ApertureValue' =&gt; '194698/65536', 'ExposureBiasValue' =&gt; '-1/3', 'MeteringMode' =&gt; 5, 'FocalLength' =&gt; '70/1', ) </code></pre>
[ { "answer_id": 324929, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 5, "selected": true, "text": "<p>The <em>reusable block</em> is registered with the <code>core/block</code> name.</p>\n\n<p>I tried to add it t...
2019/01/07
[ "https://wordpress.stackexchange.com/questions/324923", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/158549/" ]
I'm a newbie at even trying to work with PHP, but thinking there may be a simple solution to this. EXIF exposure data is only displaying an "s", so there must be an error. I'd also like to display FNumber as "Aperture" with common f-stop, such as "f2.8", but it shows a fraction 28/10. Is there PHP code that can be inserted directly to the template file to convert this? In Wordpress image.php, there is code for simplifying fractions, but these values are not being passed through the file - they are being modified directly in the template file. There's definitely something wrong with this... ``` <dt>EXIF data:</dt> <dd><ul> <?php foreach ($exif as $key => $value): if (($key != "Width") && ($key != "Height") && ($key !="DateTime")): ?><li><strong><?php if ($key == "model") { echo "Camera"; } elseif ($key == "ExposureTime") { echo "Exposure"; $newvalue = explode("(", $value); $newvalue = substr($newvalue[2], 0, -1)."s"; } elseif ($key == "FNumber") { echo "Aperture"; } else { echo $key; } ?></strong>: <?php if (!$newvalue) { echo $value; } else { echo $newvalue; $newvalue = ''; } ?></li> <?php endif; endforeach; ?> </ul></dd></dl> ``` Here is the var\_export($exif) info: ``` array ( 'Model' => 'Canon EOS 30D', 'DateTime' => '2006:12:23 08:35:02', 'ExposureTime' => '1/100', 'FNumber' => '28/10', 'ExposureProgram' => 3, 'ISOSpeedRatings' => 200, 'ExifVersion' => '0221', 'ApertureValue' => '194698/65536', 'ExposureBiasValue' => '-1/3', 'MeteringMode' => 5, 'FocalLength' => '70/1', ) ```
The *reusable block* is registered with the `core/block` name. I tried to add it to the *allowed blocks* in the `allowed_block_types` filter, here's an example: ``` add_filter( 'allowed_block_types', 'wpse324908_allowed_block_types', 10, 2 ); function wpse324908_allowed_block_types( $allowed_blocks, $post ) { $allowed_blocks = array( 'core/block', // <-- Include to show reusable blocks in the block inserter. 'core/image', 'core/paragraph', ); return $allowed_blocks; } ``` and it showed the *reusable blocks* within the *block inserter*, if at least two other blocks were included as well: [![Reusable](https://i.stack.imgur.com/4hbq7.png)](https://i.stack.imgur.com/4hbq7.png) Looking at the `/wp-includes/js/dist/editor.js` we can e.g. see this check for `core/block` regarding including reusable blocks in the block inserter: ``` var selectors_canIncludeReusableBlockInInserter = function canIncludeReusableBlockInInserter(state, reusableBlock, rootClientId) { if (!selectors_canInsertBlockTypeUnmemoized(state, 'core/block', rootClientId)) { return false; } ```
324,927
<p>I want to use the WYWISWYG on my blog page for an introduction text, but can't seem to bring back the WYSIWYG Editor on the page the page I defined as my blog posts page.</p> <p>Is there any way to force WP to still show the WYSIWYG on the Blog posts page?</p> <p><a href="https://i.stack.imgur.com/sjDej.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/sjDej.png" alt="enter image description here"></a></p>
[ { "answer_id": 324928, "author": "RiddleMeThis", "author_id": 86845, "author_profile": "https://wordpress.stackexchange.com/users/86845", "pm_score": 3, "selected": true, "text": "<p><strong>Pre WP 4.9</strong></p>\n\n<pre><code>if( ! function_exists( 'fix_no_editor_on_posts_page' ) ) {\...
2019/01/07
[ "https://wordpress.stackexchange.com/questions/324927", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/8895/" ]
I want to use the WYWISWYG on my blog page for an introduction text, but can't seem to bring back the WYSIWYG Editor on the page the page I defined as my blog posts page. Is there any way to force WP to still show the WYSIWYG on the Blog posts page? [![enter image description here](https://i.stack.imgur.com/sjDej.png)](https://i.stack.imgur.com/sjDej.png)
**Pre WP 4.9** ``` if( ! function_exists( 'fix_no_editor_on_posts_page' ) ) { /** * Add the wp-editor back into WordPress after it was removed in 4.2.2. * * @param Object $post * @return void */ function fix_no_editor_on_posts_page( $post ) { if( isset( $post ) && $post->ID != get_option('page_for_posts') ) { return; } remove_action( 'edit_form_after_title', '_wp_posts_page_notice' ); add_post_type_support( 'page', 'editor' ); } add_action( 'edit_form_after_title', 'fix_no_editor_on_posts_page', 0 ); } ``` **WP 4.9** ``` if( ! function_exists( 'fix_no_editor_on_posts_page' ) ) { function fix_no_editor_on_posts_page( $post_type, $post ) { if( isset( $post ) && $post->ID != get_option('page_for_posts') ) { return; } remove_action( 'edit_form_after_title', '_wp_posts_page_notice' ); add_post_type_support( 'page', 'editor' ); } add_action( 'add_meta_boxes', 'fix_no_editor_on_posts_page', 0, 2 ); } ``` [Full Details Here](https://wordpress.stackexchange.com/a/193756/86845)
324,935
<p>I have a WP site which I have not looked at for a while. I have just logged in to update aspects of it, including WP itself, now on 5.0.2. </p> <p>Now if I click on any of the Dashboard links - Posts, Appearance etc - I get Page Not Found. If I delete the HTAccess then it works again ... until WP reinstates it. There is nothing special about the site.</p> <p>The HTAccess is the standard WP one:</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] &lt;/IfModule&gt; # END WordPress </code></pre> <p>How can I track down what is going wrong?</p>
[ { "answer_id": 324936, "author": "Highly Irregular", "author_id": 76260, "author_profile": "https://wordpress.stackexchange.com/users/76260", "pm_score": 1, "selected": false, "text": "<p>I've had this issue on a small number of sites (out of around 60 that I help manage), and I'm wonder...
2019/01/08
[ "https://wordpress.stackexchange.com/questions/324935", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/38223/" ]
I have a WP site which I have not looked at for a while. I have just logged in to update aspects of it, including WP itself, now on 5.0.2. Now if I click on any of the Dashboard links - Posts, Appearance etc - I get Page Not Found. If I delete the HTAccess then it works again ... until WP reinstates it. There is nothing special about the site. The HTAccess is the standard WP one: ``` # 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 ``` How can I track down what is going wrong?
I've had this issue on a small number of sites (out of around 60 that I help manage), and I'm wondering if the issue is caused by caching (by a plugin or theme). If you have a caching plugin, or a theme that does caching, there should be a tool in the Dashboard for emptying/clearing/deleting the cache. Click this, and see if it fixes the issue. I've only tried this once, but it did work. I believe it is generally recommended to clear the cache whenever a software update is installed (plugin, theme, or WordPress), so that might be something you could try to add to your process in future to prevent the issue.
324,958
<pre><code>&lt;?php function consultation_user_profile_fields($user){ if ( user_can( $user-&gt;ID, "subscriber" ) ) { ?&gt; &lt;h3&gt;Consultation&lt;/h3&gt; &lt;?php $query = new WP_Query( array( 'posts_per_page' =&gt; -1, 'post_type' =&gt; 'consultation', 'post_status' =&gt; 'publish' ) ); if ($query-&gt;have_posts()) : while($query-&gt;have_posts()) : $query-&gt;the_post(); $hasAccess = ''; if ( is_object( $user ) &amp;&amp; isset( $user-&gt;ID ) ) { $hasAccess = get_user_meta( $user&gt;ID,'consultation'.get_the_ID(), true ); } ?&gt; &lt;div class="consultation"&gt; &lt;span&gt;Has access&amp;nbsp;&lt;/span&gt; &lt;div class="title"&gt;&lt;?php the_title(); ?&gt;&lt;/div&gt; &lt;input type="checkbox" id="consultation[&lt;?= get_the_ID(); ?&gt;]" class="regular-text" name="consultation[&lt;?= get_the_ID(); ?&gt;]" value="1" &lt;?= ($hasAccess == 1 ? 'checked' : ''); ?&gt;/&gt; &lt;/div&gt; &lt;?php endwhile; endif; } else { return; } } add_action( 'show_user_profile', 'consultation_user_profile_fields' ); add_action( 'edit_user_profile', 'consultation_user_profile_fields' ); add_action( "user_new_form", "consultation_user_profile_fields" ); function save_consultation_user_profile_fields($user_id){ if(!current_user_can('manage_options')) return false; foreach ($_POST['consultation'] as $key =&gt; $val) { update_user_meta($user_id,'consultation'.$key,$_POST['consultation'][$key]); } # save my custom field } add_action( 'user_register', 'save_consultation_user_profile_fields'); add_action('personal_options_update','save_consultation_user_profile_fields' ); add_action( 'edit_user_profile_update','save_consultation_user_profile_fields' ); </code></pre>
[ { "answer_id": 324936, "author": "Highly Irregular", "author_id": 76260, "author_profile": "https://wordpress.stackexchange.com/users/76260", "pm_score": 1, "selected": false, "text": "<p>I've had this issue on a small number of sites (out of around 60 that I help manage), and I'm wonder...
2019/01/08
[ "https://wordpress.stackexchange.com/questions/324958", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/158575/" ]
``` <?php function consultation_user_profile_fields($user){ if ( user_can( $user->ID, "subscriber" ) ) { ?> <h3>Consultation</h3> <?php $query = new WP_Query( array( 'posts_per_page' => -1, 'post_type' => 'consultation', 'post_status' => 'publish' ) ); if ($query->have_posts()) : while($query->have_posts()) : $query->the_post(); $hasAccess = ''; if ( is_object( $user ) && isset( $user->ID ) ) { $hasAccess = get_user_meta( $user>ID,'consultation'.get_the_ID(), true ); } ?> <div class="consultation"> <span>Has access&nbsp;</span> <div class="title"><?php the_title(); ?></div> <input type="checkbox" id="consultation[<?= get_the_ID(); ?>]" class="regular-text" name="consultation[<?= get_the_ID(); ?>]" value="1" <?= ($hasAccess == 1 ? 'checked' : ''); ?>/> </div> <?php endwhile; endif; } else { return; } } add_action( 'show_user_profile', 'consultation_user_profile_fields' ); add_action( 'edit_user_profile', 'consultation_user_profile_fields' ); add_action( "user_new_form", "consultation_user_profile_fields" ); function save_consultation_user_profile_fields($user_id){ if(!current_user_can('manage_options')) return false; foreach ($_POST['consultation'] as $key => $val) { update_user_meta($user_id,'consultation'.$key,$_POST['consultation'][$key]); } # save my custom field } add_action( 'user_register', 'save_consultation_user_profile_fields'); add_action('personal_options_update','save_consultation_user_profile_fields' ); add_action( 'edit_user_profile_update','save_consultation_user_profile_fields' ); ```
I've had this issue on a small number of sites (out of around 60 that I help manage), and I'm wondering if the issue is caused by caching (by a plugin or theme). If you have a caching plugin, or a theme that does caching, there should be a tool in the Dashboard for emptying/clearing/deleting the cache. Click this, and see if it fixes the issue. I've only tried this once, but it did work. I believe it is generally recommended to clear the cache whenever a software update is installed (plugin, theme, or WordPress), so that might be something you could try to add to your process in future to prevent the issue.
324,962
<p>I have a wordpress website in which I have a specific page for dictionary. This page is actually a custom page and does these things:</p> <ul> <li><code>site.com/dictionary</code> lists all the words</li> <li><code>site.com/dictionary/?w=word</code> shows the definition of the word</li> </ul> <p>now I want the URL to be cleaned up and becomes like this:</p> <pre><code>site.com/dictionary/word </code></pre> <p>I have made these lines in <code>.htaccess</code> but I get <code>404</code> error:</p> <pre><code>&lt;IfModule mod_rewrite.c&gt; RewriteEngine On RewriteBase /dictionary/ RewriteRule (.*) ?w=$1 [L] &lt;/IfModule&gt; </code></pre> <p>May you help me with this?</p> <p>update:</p> <p>I have tried the solution here: <a href="https://stackoverflow.com/questions/27162489/">https://stackoverflow.com/questions/27162489/</a> but this also didn't work for me.</p>
[ { "answer_id": 324968, "author": "André Kelling", "author_id": 136930, "author_profile": "https://wordpress.stackexchange.com/users/136930", "pm_score": 1, "selected": false, "text": "<p>You can't just rewrite the URL.</p>\n\n<p>You would need to refactor a lot code when using that other...
2019/01/08
[ "https://wordpress.stackexchange.com/questions/324962", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/89930/" ]
I have a wordpress website in which I have a specific page for dictionary. This page is actually a custom page and does these things: * `site.com/dictionary` lists all the words * `site.com/dictionary/?w=word` shows the definition of the word now I want the URL to be cleaned up and becomes like this: ``` site.com/dictionary/word ``` I have made these lines in `.htaccess` but I get `404` error: ``` <IfModule mod_rewrite.c> RewriteEngine On RewriteBase /dictionary/ RewriteRule (.*) ?w=$1 [L] </IfModule> ``` May you help me with this? update: I have tried the solution here: <https://stackoverflow.com/questions/27162489/> but this also didn't work for me.
You can do this with the internal rewrite system, which is parsed in php, not htaccess. First, add the rule. This assumes you have created a root page under `Pages` with the slug `dictionary`. ``` function wpd_dictionary_rewrite(){ add_rewrite_tag( '%dictionary_word%', '([^/]+)' ); add_rewrite_rule( '^dictionary/([^/]+)/?$', 'index.php?pagename=dictionary&dictionary_word=$matches[1]', 'top' ); } add_action( 'init', 'wpd_dictionary_rewrite' ); ``` This code would go in your theme's `functions.php` file, or your own plugin. Visit the `Settings > Permalinks` page to flush rules after adding this. Now you can visit `site.com/dictionary/word` and the requested word will be available in the template with `get_query_var('dictionary_word')`. If the code relies on `$_GET['w']` and you can't / don't want to change this, you can hook before the code runs and set the value manually: ``` function wpd_set_dictionary_word(){ if( false !== get_query_var( 'dictionary_word', false ) ){ $_GET['w'] = get_query_var( 'dictionary_word' ); } } add_action( 'wp', 'wpd_set_dictionary_word' ); ```
324,970
<p>I was looking for a clean way to group my search results by posttype. I currently have 3 post types: <em>Page</em>, <em>Post</em> and <em>Glossary</em>. After a long search <a href="https://wordpress.stackexchange.com/a/181807/75046">this answer</a> in this thread got me what I needed. </p> <p>The only problem is that there is no check for when a post type has no search results. If a post type has 0 results, e.g. <em>Glossary</em>, it still shows the post type title (and the container around the post type). I want the post type <code>li.search-results-post-type-item</code> to be hidden in that case.</p> <p>I am not looking for a css/js hacky <code>display: none;</code> solution. I can't imagine this can't be done with PHP.</p> <p>Thanks in advance!</p> <h2>Current situation</h2> <p><strong>Posts</strong></p> <ul> <li>Post search result 1</li> <li>Post search result 2</li> <li>etc.</li> </ul> <p><strong>Pages</strong></p> <ul> <li>Page search result 1</li> <li>Page search result 2</li> <li>etc.</li> </ul> <p><strong>Glossary</strong></p> <p>(empty)</p> <h2>Desired situation</h2> <p><strong>Posts</strong></p> <ul> <li>Post search result 1</li> <li>Post search result 2</li> <li>etc.</li> </ul> <p><strong>Pages</strong></p> <ul> <li>Page search result 1</li> <li>Page search result 2</li> <li>etc.</li> </ul> <hr> <p>My code so far:</p> <pre><code>&lt;?php $search_query = new WP_Query( array( 'posts_per_page' =&gt; 10, 's' =&gt; esc_attr( $_POST['keyword'] ), 'paged' =&gt; $paged, 'post_status' =&gt; 'publish' ) ); if( $search_query-&gt;have_posts() ) : ?&gt; &lt;div class="search-suggestions-list-header"&gt; &lt;?php echo $search_query-&gt;found_posts.' results found'; ?&gt; &lt;/div&gt; &lt;ul class="search-results-list"&gt; &lt;?php $types = array( 'post', 'page', 'glossary' ); foreach( $types as $type ) : ?&gt; &lt;li class="search-results-post-type-item post-type-&lt;?php echo $type ?&gt;"&gt; &lt;header class="post-type-header"&gt; &lt;h5 class="post-type-title"&gt; &lt;?php $post_type_obj = get_post_type_object( $type ); echo $post_type_obj-&gt;labels-&gt;name ?&gt; &lt;/h5&gt; &lt;/header&gt; &lt;ul class="search-results-list"&gt; &lt;?php while( $search_query-&gt;have_posts() ): $search_query-&gt;the_post(); if( $type == get_post_type() ) : ?&gt; &lt;li class="search-results-list-item"&gt; &lt;h4 class="entry-title"&gt;&lt;?php the_title();?&gt;&lt;/h4&gt; &lt;/li&gt; &lt;?php endif; endwhile; wp_reset_postdata(); ?&gt; &lt;/ul&gt; &lt;/li&gt; &lt;?php endforeach; ?&gt; &lt;/ul&gt; &lt;?php else: echo '&lt;div class="search-suggestions-no-results"&gt; &lt;p&gt;' . __('Sorry, no results found', 'text-domain') . '&lt;/p&gt; &lt;/div&gt;'; endif; </code></pre>
[ { "answer_id": 324971, "author": "Community", "author_id": -1, "author_profile": "https://wordpress.stackexchange.com/users/-1", "pm_score": -1, "selected": false, "text": "<p>Try to put <code>&lt;?php wp_reset_postdata(); ?&gt;</code> just after endif and check it is working or not and ...
2019/01/08
[ "https://wordpress.stackexchange.com/questions/324970", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/75046/" ]
I was looking for a clean way to group my search results by posttype. I currently have 3 post types: *Page*, *Post* and *Glossary*. After a long search [this answer](https://wordpress.stackexchange.com/a/181807/75046) in this thread got me what I needed. The only problem is that there is no check for when a post type has no search results. If a post type has 0 results, e.g. *Glossary*, it still shows the post type title (and the container around the post type). I want the post type `li.search-results-post-type-item` to be hidden in that case. I am not looking for a css/js hacky `display: none;` solution. I can't imagine this can't be done with PHP. Thanks in advance! Current situation ----------------- **Posts** * Post search result 1 * Post search result 2 * etc. **Pages** * Page search result 1 * Page search result 2 * etc. **Glossary** (empty) Desired situation ----------------- **Posts** * Post search result 1 * Post search result 2 * etc. **Pages** * Page search result 1 * Page search result 2 * etc. --- My code so far: ``` <?php $search_query = new WP_Query( array( 'posts_per_page' => 10, 's' => esc_attr( $_POST['keyword'] ), 'paged' => $paged, 'post_status' => 'publish' ) ); if( $search_query->have_posts() ) : ?> <div class="search-suggestions-list-header"> <?php echo $search_query->found_posts.' results found'; ?> </div> <ul class="search-results-list"> <?php $types = array( 'post', 'page', 'glossary' ); foreach( $types as $type ) : ?> <li class="search-results-post-type-item post-type-<?php echo $type ?>"> <header class="post-type-header"> <h5 class="post-type-title"> <?php $post_type_obj = get_post_type_object( $type ); echo $post_type_obj->labels->name ?> </h5> </header> <ul class="search-results-list"> <?php while( $search_query->have_posts() ): $search_query->the_post(); if( $type == get_post_type() ) : ?> <li class="search-results-list-item"> <h4 class="entry-title"><?php the_title();?></h4> </li> <?php endif; endwhile; wp_reset_postdata(); ?> </ul> </li> <?php endforeach; ?> </ul> <?php else: echo '<div class="search-suggestions-no-results"> <p>' . __('Sorry, no results found', 'text-domain') . '</p> </div>'; endif; ```
To avoid types with no results you can e.g. * one additional time go through the loop and count the occurrences of each type, the number of returned results is not large (only 10 per page) * display the type title when you encounter the first post with the given type (move to inside `while` loop, I know, less readable code) * go through the loop one time and collect post titles to the table divided into types First option ------------ ``` <ul class="search-results-list"> <?php $types = array( 'post', 'page', 'glossary' ); $occurrences = []; while( $search_query->have_posts() ) { $search_query->next_post(); $type = $search_query->post->post_type; if ( !isset($occurrences[$type]) ) $occurrences[$type] = 1; else $occurrences[$type] += 1; } rewind_posts(); foreach( $types as $type ) : if ( !isset($occurrences[$type]) ) continue; ?> <li class="search-results-post-type-item post-type-<?php echo $type ?>"> // // remaining code // </li> <?php endforeach; ?> </ul> ``` Second option ------------- ``` $types = array( 'post', 'page', 'glossary' ); foreach( $types as $type ) : $type_header_printed = false; ?> <?php while( $search_query->have_posts() ): $search_query->the_post(); if( $type == get_post_type() ) : // -- post type header ----- if ( !$type_header_printed ) : $type_header_printed = true; ?> <li class="search-results-post-type-item post-type-<?php echo $type ?>"> <header class="post-type-header"> <h5 class="post-type-title"> <?php $post_type_obj = get_post_type_object( $type ); echo $post_type_obj->labels->name ?> </h5> </header> <ul class="search-results-list"> <?php // -- header end ----- endif; ?> <li class="search-results-list-item"> <h4 class="entry-title"><?php the_title();?></h4> </li> <?php endif; endwhile; rewind_posts(); if ( $type_header_printed ) : ?> </ul> </li> <?php endif; ?> <?php endforeach; ?> ``` Third option ------------ ``` <ul class="search-results-list"> <?php $types = array( 'post', 'page', 'glossary' ); $posts_titles = []; while( $search_query->have_posts() ) { $search_query->the_post(); $type = $search_query->post->post_type; if ( !isset($posts_titles[$type]) ) $posts_titles[$type] = []; $posts_titles[$type][] = get_the_title(); } rewind_posts(); foreach( $types as $type ) : if ( !isset($posts_titles[$type]) ) continue; ?> <li class="search-results-post-type-item post-type-<?php echo $type ?>"> <header class="post-type-header"> <h5 class="post-type-title"> <?php $post_type_obj = get_post_type_object( $type ); echo $post_type_obj->labels->name ?> </h5> </header> <ul class="search-results-list"> <?php foreach( $posts_titles[$type] as $title ) : ?> <li class="search-results-list-item"> <h4 class="entry-title"><?php echo htmlspecialchars($title); ?></h4> </li> <?php endforeach; ?> </ul> </li> <?php endforeach; ?> </ul> ```
324,979
<p>I've registered a sidebar component in the block editor. I'd like to access the <code>state</code> of the component (<code>MyPlugin</code>) from outside of that component, in some arbitrary JavaScript in the same file. Is it possible to access the state via e.g. the <code>wp</code> object?</p> <p>Or, is it possible, and would it be better to do this using <code>props</code>?</p> <pre><code>class MyPlugin extends Component { constructor() { super( ...arguments ); // initial state this.state = { key: 'my_key', value: '' } } render() { return el( PluginPostStatusInfo, { className: 'my-panel-class' }, el( TextControl, { name: 'my_text_control_name', label: __( 'My label', 'my-text-domain' ), value: this.state.value, onChange: ( value ) =&gt; { this.setState( { value }) } } ) ); } } registerPlugin( 'my-plugin', { render: MyPlugin } ); const myFunction = () =&gt; { // this function is hooked into an action elsewhere, // and needs to access the state of MyPlugin } </code></pre> <p>What I'd ultimately like to do is access the textbox's value from a separate function. I don't mind how this is achieved, e.g. with <code>state</code> or <code>props</code> or some other means. I guess another approach would be to have the component write its value into a global variable when it changes, but that seems a bit clunky.</p>
[ { "answer_id": 324980, "author": "Sean", "author_id": 138112, "author_profile": "https://wordpress.stackexchange.com/users/138112", "pm_score": 1, "selected": false, "text": "<p>I found a solution, but I'm not sure it's really the intended way to do this. I use the core editor datastore ...
2019/01/08
[ "https://wordpress.stackexchange.com/questions/324979", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/138112/" ]
I've registered a sidebar component in the block editor. I'd like to access the `state` of the component (`MyPlugin`) from outside of that component, in some arbitrary JavaScript in the same file. Is it possible to access the state via e.g. the `wp` object? Or, is it possible, and would it be better to do this using `props`? ``` class MyPlugin extends Component { constructor() { super( ...arguments ); // initial state this.state = { key: 'my_key', value: '' } } render() { return el( PluginPostStatusInfo, { className: 'my-panel-class' }, el( TextControl, { name: 'my_text_control_name', label: __( 'My label', 'my-text-domain' ), value: this.state.value, onChange: ( value ) => { this.setState( { value }) } } ) ); } } registerPlugin( 'my-plugin', { render: MyPlugin } ); const myFunction = () => { // this function is hooked into an action elsewhere, // and needs to access the state of MyPlugin } ``` What I'd ultimately like to do is access the textbox's value from a separate function. I don't mind how this is achieved, e.g. with `state` or `props` or some other means. I guess another approach would be to have the component write its value into a global variable when it changes, but that seems a bit clunky.
To do so you need to use a redux store. To register your own you can follow the steps in the [documentation](https://github.com/WordPress/gutenberg/tree/master/packages/data). Here is the minimum that should achieve what you are looking for. First, lets give the "shape" of the store in the initial state object: ``` const initial_state = { my_control: { value: "" }, }; ``` Lets create a reducer that manipulates the state: ``` const reducer = (state = initial_state, action) => { switch (action.type) { case "UPDATE_MY_CONTROL_VALUE": { return { ...state, my_control: { ...state.my_control, value: action.value } }; } } return state; }; ``` As you can see, we set the `initial_state` object we just created as the default value of the state. Now lets add an action which updates the store, sending data to the reducer: ``` const actions = { updateMyControlValue(value) { return { type: "UPDATE_MY_CONTROL_VALUE", value }; }, } ``` Lets add a selector that gets the data from the store: ``` const selectors = { getMyControlValue(state) { return state.my_control.value; }, }; ``` And now we will register the store with the previous constants: ``` const { registerStore } = wp.data; registerStore("my_plugin/my_store", { reducer, actions, selectors }); ``` Now the store is registered. We will connect the component to the store to get the latest value of my\_control and to update it: ``` const { Component } = wp.element; const { TextControl } = wp.components; const { compose } = wp.compose; const { withDispatch, withSelect } = wp.data; class Text extends Component { render() { const { value, updateMyControlValue } = this.props; return ( <TextControl value={value} onChange={updateMyControlValue} /> ); } } export default compose([ withDispatch((dispatch, props) => { // This function here is the action we created before. const { updateMyControlValue } = dispatch("my_plugin/my_store"); return { updateMyControlValue }; }), withSelect((select, props) => { // This function here is the selector we created before. const { getMyControlValue } = select("my_plugin/my_store"); return { value: getMyControlValue() }; }), ])(Text); ``` --- This is a simple example, but you can take a look at the link on the documentation to see how you can use other functionality to enhance the store (for example, with controls and resolvers). Also you can make use the [core stores](https://github.com/WordPress/gutenberg/tree/master/docs/designers-developers/developers/data) and their selectors and actions inside your component's `withSelect` and `withDispatch`.
325,001
<p>I would really like to keep my template files as clean as possible, without including too much argument data. Is it possible with the following example...</p> <pre><code> $args = array( 'theme_location' =&gt; 'main-menu', 'menu_class' =&gt; 'list-inline', 'add_li_class' =&gt; 'list-inline-item' ); wp_nav_menu($args); </code></pre> <p>...that I can store my array of arguments in a function within my functions.php file, and then simply call the argument data onto my header.php where my wp_nav_menu() lives? Please feel free to correct me if I am wrong, but is this a good time for me to use a add_action/do_action for this specific case?</p> <p>I want to use my functions.php file as a one-stop-shop to (i.e. register the nav, add basic or advanced argument data to the same nav, etc..). </p> <p>This is the first time I'm thinking about this, so I'm all for any best practices.</p> <p>Many thanks!</p>
[ { "answer_id": 325020, "author": "mrben522", "author_id": 84703, "author_profile": "https://wordpress.stackexchange.com/users/84703", "pm_score": 2, "selected": true, "text": "<p>a function like this:</p>\n\n<pre><code>function get_nav_args($overrides = array()) {\n $defaults = array(...
2019/01/08
[ "https://wordpress.stackexchange.com/questions/325001", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/98671/" ]
I would really like to keep my template files as clean as possible, without including too much argument data. Is it possible with the following example... ``` $args = array( 'theme_location' => 'main-menu', 'menu_class' => 'list-inline', 'add_li_class' => 'list-inline-item' ); wp_nav_menu($args); ``` ...that I can store my array of arguments in a function within my functions.php file, and then simply call the argument data onto my header.php where my wp\_nav\_menu() lives? Please feel free to correct me if I am wrong, but is this a good time for me to use a add\_action/do\_action for this specific case? I want to use my functions.php file as a one-stop-shop to (i.e. register the nav, add basic or advanced argument data to the same nav, etc..). This is the first time I'm thinking about this, so I'm all for any best practices. Many thanks!
a function like this: ``` function get_nav_args($overrides = array()) { $defaults = array( 'theme_location' => 'main-menu', 'menu_class' => 'list-inline', 'add_li_class' => 'list-inline-item', ); return shortcode_atts($defaults, apply_filters('some_custom_identifier_nav_menu_args', $overrides, $defaults) ); } ``` would be callable like `wp_nav_menu(get_nav_args())` using shortcode atts and allowing an overrides array to be passed in would allow you to change the values if necessary without duplicating the whole thing. As for your put everything in functions.php I would avoid that if possible. Use `include` or `require` to include files that contain your functions. this way you can sort them out by type, use, location, or whatever else you'd like and won't end up digging through a single massive file looking for something down the road.
325,003
<p>First please excuse my English. So I built my own WordPress theme and want to use ajax in it, I'm using ajax for change post category in my post loop inside functions.php, so when a person clicked the button in index.php ajax will send the data and functions.php will change the category, the problem is i can't reach admin-ajax.php <br/></p> <p><strong>SO IN HERE MY CODE IS JUST FOR TESTING IF THE AJAX WORK OR NOT, IT WONT ECHO THE POST THAT HAD BEEN SENT</strong><br/></p> <p><strong>This is my .js file that contains ajax</strong></p> <pre><code> function kategori(kategori2){ //alert(kategori2); jQuery.ajax({ url: MyAjax.ajax_url, type: "POST", data: { action: "berubah", kategori: "berita"}, success : function(data) { } }); } </code></pre> <p><strong>This is my function.php</strong> </p> <pre><code>&lt;?php // Support Featured Images add_theme_support( 'post-thumbnails' ); add_action( 'wp_enqueue_scripts', 'my_script_enqueuer' ); function my_script_enqueuer() { wp_register_script( 'add-order-front', get_template_directory_uri() . '/js/programku.js' ); wp_localize_script( 'add-order-front', 'MyAjax', array( 'ajaxurl' =&gt; admin_url( 'admin-ajax.php' ) ) ); wp_enqueue_script( 'add-order-front' ); } add_action( 'wp_ajax_berubah', 'berubah' ); add_action( 'wp_ajax_nopriv_berubah', 'berubah' ); function berubah() { $kategori = isset( $_POST['kategori'] ) ? $_POST['kategori'] : ''; echo $kategori; wp_die(); } </code></pre> <p><hr/><br/></p> <p>I new to javascript too, I use Mozilla console and got this </p> <blockquote> <p>'ReferenceError: ajax_object is not defined'</p> </blockquote> <p><hr /> <br /></p> <p><strong>EDIT #1 -</strong></p> <p>i can reach admin-ajax.php now, my fault was i didn't have header.php on my theme, sorry i new in wordpress</p> <p>now my problem is, <strong>function.php can't get the data sent by AJAX from programku.js and response in console is an HTML code</strong></p> <p><hr/> <strong>in my theme i just have 5 files</strong> </p> <ol> <li>index.php</li> <li>programku.js inside the js folder</li> <li>header.php</li> <li>footer.php</li> <li>and last functions.php</li> </ol> <p><strong>Is there is a files that important in wordpress theme developing that i left?</strong><hr /> <br/><hr/></p> <p><a href="https://i.stack.imgur.com/Gsy3g.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Gsy3g.png" alt="enter image description here"></a></p> <p><a href="https://i.stack.imgur.com/SzG9t.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/SzG9t.png" alt="enter image description here"></a></p>
[ { "answer_id": 325020, "author": "mrben522", "author_id": 84703, "author_profile": "https://wordpress.stackexchange.com/users/84703", "pm_score": 2, "selected": true, "text": "<p>a function like this:</p>\n\n<pre><code>function get_nav_args($overrides = array()) {\n $defaults = array(...
2019/01/08
[ "https://wordpress.stackexchange.com/questions/325003", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/158580/" ]
First please excuse my English. So I built my own WordPress theme and want to use ajax in it, I'm using ajax for change post category in my post loop inside functions.php, so when a person clicked the button in index.php ajax will send the data and functions.php will change the category, the problem is i can't reach admin-ajax.php **SO IN HERE MY CODE IS JUST FOR TESTING IF THE AJAX WORK OR NOT, IT WONT ECHO THE POST THAT HAD BEEN SENT** **This is my .js file that contains ajax** ``` function kategori(kategori2){ //alert(kategori2); jQuery.ajax({ url: MyAjax.ajax_url, type: "POST", data: { action: "berubah", kategori: "berita"}, success : function(data) { } }); } ``` **This is my function.php** ``` <?php // Support Featured Images add_theme_support( 'post-thumbnails' ); add_action( 'wp_enqueue_scripts', 'my_script_enqueuer' ); function my_script_enqueuer() { wp_register_script( 'add-order-front', get_template_directory_uri() . '/js/programku.js' ); wp_localize_script( 'add-order-front', 'MyAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) ); wp_enqueue_script( 'add-order-front' ); } add_action( 'wp_ajax_berubah', 'berubah' ); add_action( 'wp_ajax_nopriv_berubah', 'berubah' ); function berubah() { $kategori = isset( $_POST['kategori'] ) ? $_POST['kategori'] : ''; echo $kategori; wp_die(); } ``` --- I new to javascript too, I use Mozilla console and got this > > 'ReferenceError: ajax\_object is not defined' > > > --- **EDIT #1 -** i can reach admin-ajax.php now, my fault was i didn't have header.php on my theme, sorry i new in wordpress now my problem is, **function.php can't get the data sent by AJAX from programku.js and response in console is an HTML code** --- **in my theme i just have 5 files** 1. index.php 2. programku.js inside the js folder 3. header.php 4. footer.php 5. and last functions.php **Is there is a files that important in wordpress theme developing that i left?** --- --- [![enter image description here](https://i.stack.imgur.com/Gsy3g.png)](https://i.stack.imgur.com/Gsy3g.png) [![enter image description here](https://i.stack.imgur.com/SzG9t.png)](https://i.stack.imgur.com/SzG9t.png)
a function like this: ``` function get_nav_args($overrides = array()) { $defaults = array( 'theme_location' => 'main-menu', 'menu_class' => 'list-inline', 'add_li_class' => 'list-inline-item', ); return shortcode_atts($defaults, apply_filters('some_custom_identifier_nav_menu_args', $overrides, $defaults) ); } ``` would be callable like `wp_nav_menu(get_nav_args())` using shortcode atts and allowing an overrides array to be passed in would allow you to change the values if necessary without duplicating the whole thing. As for your put everything in functions.php I would avoid that if possible. Use `include` or `require` to include files that contain your functions. this way you can sort them out by type, use, location, or whatever else you'd like and won't end up digging through a single massive file looking for something down the road.
325,013
<p>I am trying to query a custom taxonomy terms in a way that keeps the hierarchical structure. </p> <p>Here is the code that I am using.. </p> <pre><code>function ev_test_data() { $title = 'Mens Levi\'s Jeans'; $titles = str_replace( array("'", '"', '-', '\\' ), '', explode( ' ', trim($title)) ); $cats = array(); foreach ( $titles as $kw ) { $terms = get_terms( array( 'taxonomy' =&gt; 'product_cat', 'orderby' =&gt; 'parent', // I guess this is where I am lost. 'hide_empty' =&gt; false, 'name__like' =&gt; $kw, ) ); foreach ( $terms as $term ) { $cats[] = $term-&gt;term_id; } } $finals = array(); foreach ( $cats as $cat ) { $catobj = get_term_by( 'id', $cat, 'product_cat' ); $tree = ''; $ancentors = array_reverse(get_ancestors( $cat, 'product_cat', 'taxonomy' ), true); $i=1; foreach ( $ancentors as $ancentor ) { $sterm = get_term_by( 'id', $ancentor, 'product_cat' ); $tree .= $i == 1 ? '&lt;b&gt;' . $sterm-&gt;name . '&lt;/b&gt;' : ' &gt; ' . $sterm-&gt;name; $i++; } $tree .= ' &gt; ' . $catobj-&gt;name; $finals[$cat] = $tree; } echo '&lt;pre&gt;' . print_r( $finals, true ) . '&lt;/pre&gt;'; } </code></pre> <p>This produces this list.</p> <pre><code>Array ( [4638] =&gt; Fashion &gt; Womens Clothing [4699] =&gt; Fashion &gt; Womens Handbags &amp; Bags [4709] =&gt; Fashion &gt; Womens Shoes [4461] =&gt; Fashion &gt; Mens Accessories [4493] =&gt; Fashion &gt; Mens Clothing [4512] =&gt; Fashion &gt; Mens Shoes [4603] =&gt; Fashion &gt; Womens Accessories [4779] =&gt; Fashion &gt; Vintage &gt; Mens Vintage Clothing [4821] =&gt; Fashion &gt; Vintage &gt; Womens Vintage Clothing [4290] =&gt; Fashion &gt; Kids Clothing, Shoes &amp; Accs &gt; Boys Clothing (Sizes 4 &amp; Up) &gt; Jeans [4319] =&gt; Fashion &gt; Kids Clothing, Shoes &amp; Accs &gt; Girls Clothing (Sizes 4 &amp; Up) &gt; Jeans [4354] =&gt; Fashion &gt; Kids Clothing, Shoes &amp; Accs &gt; Unisex Clothing &gt; Jeans [4500] =&gt; Fashion &gt; Mens Clothing &gt; Jeans [4660] =&gt; Fashion &gt; Womens Clothing &gt; Jeans [4666] =&gt; Fashion &gt; Womens Clothing &gt; Maternity &gt; Jeans ) </code></pre> <p>However, this list is not ordered as I want. I need it to be ordered by the hierarchical order. Something like this.</p> <pre><code>Array ( [4493] =&gt; Fashion &gt; Mens Clothing [4500] =&gt; Fashion &gt; Mens Clothing &gt; Jeans [4638] =&gt; Fashion &gt; Womens Clothing [4660] =&gt; Fashion &gt; Womens Clothing &gt; Jeans [4666] =&gt; Fashion &gt; Womens Clothing &gt; Maternity &gt; Jeans [4699] =&gt; Fashion &gt; Womens Handbags &amp; Bags [4709] =&gt; Fashion &gt; Womens Shoes [4603] =&gt; Fashion &gt; Womens Accessories [4512] =&gt; Fashion &gt; Mens Shoes [4461] =&gt; Fashion &gt; Mens Accessories [4779] =&gt; Fashion &gt; Vintage &gt; Mens Vintage Clothing [4821] =&gt; Fashion &gt; Vintage &gt; Womens Vintage Clothing [4290] =&gt; Fashion &gt; Kids Clothing, Shoes &amp; Accs &gt; Boys Clothing (Sizes 4 &amp; Up) &gt; Jeans [4319] =&gt; Fashion &gt; Kids Clothing, Shoes &amp; Accs &gt; Girls Clothing (Sizes 4 &amp; Up) &gt; Jeans [4354] =&gt; Fashion &gt; Kids Clothing, Shoes &amp; Accs &gt; Unisex Clothing &gt; Jeans ) </code></pre> <p>Can this be done using WordPress built in functions? If not, what would be the logic for the custom query? I am not asking to do it for me, but any help or guide or headstart would be great. </p> <p>Thanks</p>
[ { "answer_id": 325016, "author": "RiddleMeThis", "author_id": 86845, "author_profile": "https://wordpress.stackexchange.com/users/86845", "pm_score": 0, "selected": false, "text": "<p>You can use <a href=\"https://developer.wordpress.org/reference/functions/wp_list_categories/#Display_Te...
2019/01/08
[ "https://wordpress.stackexchange.com/questions/325013", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/26991/" ]
I am trying to query a custom taxonomy terms in a way that keeps the hierarchical structure. Here is the code that I am using.. ``` function ev_test_data() { $title = 'Mens Levi\'s Jeans'; $titles = str_replace( array("'", '"', '-', '\\' ), '', explode( ' ', trim($title)) ); $cats = array(); foreach ( $titles as $kw ) { $terms = get_terms( array( 'taxonomy' => 'product_cat', 'orderby' => 'parent', // I guess this is where I am lost. 'hide_empty' => false, 'name__like' => $kw, ) ); foreach ( $terms as $term ) { $cats[] = $term->term_id; } } $finals = array(); foreach ( $cats as $cat ) { $catobj = get_term_by( 'id', $cat, 'product_cat' ); $tree = ''; $ancentors = array_reverse(get_ancestors( $cat, 'product_cat', 'taxonomy' ), true); $i=1; foreach ( $ancentors as $ancentor ) { $sterm = get_term_by( 'id', $ancentor, 'product_cat' ); $tree .= $i == 1 ? '<b>' . $sterm->name . '</b>' : ' > ' . $sterm->name; $i++; } $tree .= ' > ' . $catobj->name; $finals[$cat] = $tree; } echo '<pre>' . print_r( $finals, true ) . '</pre>'; } ``` This produces this list. ``` Array ( [4638] => Fashion > Womens Clothing [4699] => Fashion > Womens Handbags & Bags [4709] => Fashion > Womens Shoes [4461] => Fashion > Mens Accessories [4493] => Fashion > Mens Clothing [4512] => Fashion > Mens Shoes [4603] => Fashion > Womens Accessories [4779] => Fashion > Vintage > Mens Vintage Clothing [4821] => Fashion > Vintage > Womens Vintage Clothing [4290] => Fashion > Kids Clothing, Shoes & Accs > Boys Clothing (Sizes 4 & Up) > Jeans [4319] => Fashion > Kids Clothing, Shoes & Accs > Girls Clothing (Sizes 4 & Up) > Jeans [4354] => Fashion > Kids Clothing, Shoes & Accs > Unisex Clothing > Jeans [4500] => Fashion > Mens Clothing > Jeans [4660] => Fashion > Womens Clothing > Jeans [4666] => Fashion > Womens Clothing > Maternity > Jeans ) ``` However, this list is not ordered as I want. I need it to be ordered by the hierarchical order. Something like this. ``` Array ( [4493] => Fashion > Mens Clothing [4500] => Fashion > Mens Clothing > Jeans [4638] => Fashion > Womens Clothing [4660] => Fashion > Womens Clothing > Jeans [4666] => Fashion > Womens Clothing > Maternity > Jeans [4699] => Fashion > Womens Handbags & Bags [4709] => Fashion > Womens Shoes [4603] => Fashion > Womens Accessories [4512] => Fashion > Mens Shoes [4461] => Fashion > Mens Accessories [4779] => Fashion > Vintage > Mens Vintage Clothing [4821] => Fashion > Vintage > Womens Vintage Clothing [4290] => Fashion > Kids Clothing, Shoes & Accs > Boys Clothing (Sizes 4 & Up) > Jeans [4319] => Fashion > Kids Clothing, Shoes & Accs > Girls Clothing (Sizes 4 & Up) > Jeans [4354] => Fashion > Kids Clothing, Shoes & Accs > Unisex Clothing > Jeans ) ``` Can this be done using WordPress built in functions? If not, what would be the logic for the custom query? I am not asking to do it for me, but any help or guide or headstart would be great. Thanks
I was looking for the same thing and think this should work for you : [Custom taxonomy, get\_the\_terms, listing in order of parent > child](https://wordpress.stackexchange.com/questions/37285/custom-taxonomy-get-the-terms-listing-in-order-of-parent-child)
325,015
<p>It works in the category.php loop</p> <pre><code>&lt;article&gt; &lt;p&gt;post-&lt;?php echo $wp_query-&gt;current_post +1; ?&gt;&lt;/p&gt; &lt;/article&gt; &lt;article&gt; &lt;p&gt;post-&lt;?php echo $wp_query-&gt;current_post +1; ?&gt;&lt;/p&gt; &lt;/article&gt; </code></pre> <p>Result. Shows number 1, 2, 3 ...</p> <pre><code>&lt;article&gt; &lt;p&gt;post-1&lt;/p&gt; &lt;/article&gt; &lt;article&gt; &lt;p&gt;post-2&lt;/p&gt; &lt;/article&gt; </code></pre> <p>Where to add this to widget recent posts?</p> <p>If you add to the file /wp-includes/widgets/class-wp-widget-recent-posts.php</p> <p>Result. Shows only number 1.</p> <pre><code>&lt;ul&gt; &lt;li&gt;post-1&lt;/li&gt; &lt;/ul&gt; &lt;ul&gt; &lt;li&gt;post-1&lt;/li&gt; &lt;/ul&gt; </code></pre> <p>This is not a loop? How does this work in a widget?</p> <blockquote> <p>$wp_query->current_post +1</p> <p>class-wp-widget-recent-posts.php or functions.php?</p> </blockquote> <p>Thanks.</p>
[ { "answer_id": 325040, "author": "EGWorldNP", "author_id": 138428, "author_profile": "https://wordpress.stackexchange.com/users/138428", "pm_score": -1, "selected": false, "text": "<p>I didn't get what actually you are asking for ? Post count or Post ID <br><br>\nAs i understand, i assum...
2019/01/08
[ "https://wordpress.stackexchange.com/questions/325015", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/-1/" ]
It works in the category.php loop ``` <article> <p>post-<?php echo $wp_query->current_post +1; ?></p> </article> <article> <p>post-<?php echo $wp_query->current_post +1; ?></p> </article> ``` Result. Shows number 1, 2, 3 ... ``` <article> <p>post-1</p> </article> <article> <p>post-2</p> </article> ``` Where to add this to widget recent posts? If you add to the file /wp-includes/widgets/class-wp-widget-recent-posts.php Result. Shows only number 1. ``` <ul> <li>post-1</li> </ul> <ul> <li>post-1</li> </ul> ``` This is not a loop? How does this work in a widget? > > $wp\_query->current\_post +1 > > > class-wp-widget-recent-posts.php or functions.php? > > > Thanks.
It's not clearly stated in your question, but I guess, you added exactly this code to the widget file: ``` <?php echo $wp_query->current_post +1; ?> ``` Am I right? If so, then it couldn't work, because this code takes the counter from global `$wp_query` object, but... This widget doesn't use global `$wp_query` and uses custom `WP_Query` instance. You can see it clearly here: <https://github.com/WordPress/WordPress/blob/master/wp-includes/widgets/class-wp-widget-recent-posts.php#L70>. And even worse (in this case), because this widget doesn't use `the_post` method and standard way of looping through posts, but native PHP `foreach` loop (<https://github.com/WordPress/WordPress/blob/master/wp-includes/widgets/class-wp-widget-recent-posts.php#L94>), to be more efficient. But this also means that this loop doesn't change the counter value... But... There is one more, major, but. You should never ever modify core WP files. If you do this, you won't be able to update your WP or you will loose these modifications. You can easily cause any plugin or theme to work incorrectly. So...? Is that it? It can't be done? ------------------------------------ Well, it can. If all you want to do is to add numbers in the `li` element, you can do it with CSS. One way would be to change the `list-style-type` to `decimal` for list in that widget: ``` .widget_recent_entries ul {list-style-type: decimal;} ``` Another way is to use `:before` pseudo-class with counter: ``` .widget_recent_entries ul { counter-reset: my-recent-posts-widget-counter; } .widget_recent_entries ul li { counter-increment: my-recent-posts-widget-counter; } .widget_recent_entries ul li { content: counter(my-recent-posts-widget-counter); } ```
325,022
<p>I want to have what would appear if I chose "homepage display to: Your latest posts" but on a page of my choosing and Not as the front page of my site. </p>
[ { "answer_id": 325040, "author": "EGWorldNP", "author_id": 138428, "author_profile": "https://wordpress.stackexchange.com/users/138428", "pm_score": -1, "selected": false, "text": "<p>I didn't get what actually you are asking for ? Post count or Post ID <br><br>\nAs i understand, i assum...
2019/01/08
[ "https://wordpress.stackexchange.com/questions/325022", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/158618/" ]
I want to have what would appear if I chose "homepage display to: Your latest posts" but on a page of my choosing and Not as the front page of my site.
It's not clearly stated in your question, but I guess, you added exactly this code to the widget file: ``` <?php echo $wp_query->current_post +1; ?> ``` Am I right? If so, then it couldn't work, because this code takes the counter from global `$wp_query` object, but... This widget doesn't use global `$wp_query` and uses custom `WP_Query` instance. You can see it clearly here: <https://github.com/WordPress/WordPress/blob/master/wp-includes/widgets/class-wp-widget-recent-posts.php#L70>. And even worse (in this case), because this widget doesn't use `the_post` method and standard way of looping through posts, but native PHP `foreach` loop (<https://github.com/WordPress/WordPress/blob/master/wp-includes/widgets/class-wp-widget-recent-posts.php#L94>), to be more efficient. But this also means that this loop doesn't change the counter value... But... There is one more, major, but. You should never ever modify core WP files. If you do this, you won't be able to update your WP or you will loose these modifications. You can easily cause any plugin or theme to work incorrectly. So...? Is that it? It can't be done? ------------------------------------ Well, it can. If all you want to do is to add numbers in the `li` element, you can do it with CSS. One way would be to change the `list-style-type` to `decimal` for list in that widget: ``` .widget_recent_entries ul {list-style-type: decimal;} ``` Another way is to use `:before` pseudo-class with counter: ``` .widget_recent_entries ul { counter-reset: my-recent-posts-widget-counter; } .widget_recent_entries ul li { counter-increment: my-recent-posts-widget-counter; } .widget_recent_entries ul li { content: counter(my-recent-posts-widget-counter); } ```
325,113
<p>when I tried to edit a post of a custom post type, I experienced this error.</p> <p><a href="https://i.stack.imgur.com/mWpXa.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mWpXa.jpg" alt="enter image description here"></a></p> <p>When I press "Copy Error" I am getting this:</p> <pre class="lang-php prettyprint-override"><code>TypeError: Cannot read property 'prefix' of null at https://example.com/wp-includes/js/dist/edit-post.min.js?ver=3.1.6:12:56693 at ph (https://example.com/wp-includes/js/dist/vendor/react-dom.min.js?ver=16.6.3:97:88) at eg (https://example.com/wp-includes/js/dist/vendor/react-dom.min.js?ver=16.6.3:125:307) at fg (https://example.com/wp-includes/js/dist/vendor/react-dom.min.js?ver=16.6.3:126:168) at wc (https://example.com/wp-includes/js/dist/vendor/react-dom.min.js?ver=16.6.3:138:237) at fa (https://example.com/wp-includes/js/dist/vendor/react-dom.min.js?ver=16.6.3:137:115) at gg (https://example.com/wp-includes/js/dist/vendor/react-dom.min.js?ver=16.6.3:135:196) at Ca (https://example.com/wp-includes/js/dist/vendor/react-dom.min.js?ver=16.6.3:133:365) at Object.enqueueSetState (https://example.com/wp-includes/js/dist/vendor/react-dom.min.js?ver=16.6.3:191:324) at r.q.setState (https://example.com/wp-includes/js/dist/vendor/react.min.js?ver=16.6.3:20:304) </code></pre>
[ { "answer_id": 325114, "author": "marvinpoo", "author_id": 94786, "author_profile": "https://wordpress.stackexchange.com/users/94786", "pm_score": 2, "selected": true, "text": "<p>So,\nI was researching this topic a bit deeper. All answers found on this SE suggested disabling Gutenberg w...
2019/01/09
[ "https://wordpress.stackexchange.com/questions/325113", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/94786/" ]
when I tried to edit a post of a custom post type, I experienced this error. [![enter image description here](https://i.stack.imgur.com/mWpXa.jpg)](https://i.stack.imgur.com/mWpXa.jpg) When I press "Copy Error" I am getting this: ```php TypeError: Cannot read property 'prefix' of null at https://example.com/wp-includes/js/dist/edit-post.min.js?ver=3.1.6:12:56693 at ph (https://example.com/wp-includes/js/dist/vendor/react-dom.min.js?ver=16.6.3:97:88) at eg (https://example.com/wp-includes/js/dist/vendor/react-dom.min.js?ver=16.6.3:125:307) at fg (https://example.com/wp-includes/js/dist/vendor/react-dom.min.js?ver=16.6.3:126:168) at wc (https://example.com/wp-includes/js/dist/vendor/react-dom.min.js?ver=16.6.3:138:237) at fa (https://example.com/wp-includes/js/dist/vendor/react-dom.min.js?ver=16.6.3:137:115) at gg (https://example.com/wp-includes/js/dist/vendor/react-dom.min.js?ver=16.6.3:135:196) at Ca (https://example.com/wp-includes/js/dist/vendor/react-dom.min.js?ver=16.6.3:133:365) at Object.enqueueSetState (https://example.com/wp-includes/js/dist/vendor/react-dom.min.js?ver=16.6.3:191:324) at r.q.setState (https://example.com/wp-includes/js/dist/vendor/react.min.js?ver=16.6.3:20:304) ```
So, I was researching this topic a bit deeper. All answers found on this SE suggested disabling Gutenberg with a plugin. This couldn't be a valid "fix" in my oppinion. After researching and browsing through the git issues of `WordPress/gutenberg` I've found a pretty easy solution for this problem. The user `joshuafredrickson` on the git suggested changing the args of the custom post type array from `'public' => false,` to **true**. I have checked that fix on multiple of my clients projects and it has worked every single time. **Credits:** * <https://github.com/WordPress/gutenberg/issues/12482#issuecomment-445022253>
325,127
<p>I recently switched to ssl in order to provide a better and more secure website experience for my users.</p> <p>I nearly solved all of my mixed content issues, but the mixed content warnings of the Wordpress plugin kk star ratings are still unsolved.</p> <p>When I open a blog post, I always get the following notifications:</p> <p><strong>The following content is displayed in an insecure manner.</strong></p> <p>/wp-content/plugins/kk-star-ratings/yellow.png.</p> <p>/wp-content/plugins/kk-star-ratings/gray.png.</p> <p>I've already looked into the plugin folder, but I don't have any php knowledge to fix it.</p> <p>Could these lines be responsible for the mixed content warning?</p> <pre><code>echo $star_gray ? '.kk-star-ratings .kksr-star.gray { background-image: url('.$star_gray.'); }' : ''; echo $star_yellow ? '.kk-star-ratings .kksr-star.yellow { background-image: url('.$star_yellow.'); }' : ''; echo $star_orange ? '.kk-star-ratings .kksr-star.orange { background-image: url('.$star_orange.'); }' : ''; </code></pre> <p>I would be grateful if someone could help me to load these files via ssl.</p>
[ { "answer_id": 325226, "author": "Arvind Singh", "author_id": 113501, "author_profile": "https://wordpress.stackexchange.com/users/113501", "pm_score": 0, "selected": false, "text": "<p>Can try replacing all URL from database to https, you can use the plugin \"Search and replace\" or if ...
2019/01/09
[ "https://wordpress.stackexchange.com/questions/325127", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/158448/" ]
I recently switched to ssl in order to provide a better and more secure website experience for my users. I nearly solved all of my mixed content issues, but the mixed content warnings of the Wordpress plugin kk star ratings are still unsolved. When I open a blog post, I always get the following notifications: **The following content is displayed in an insecure manner.** /wp-content/plugins/kk-star-ratings/yellow.png. /wp-content/plugins/kk-star-ratings/gray.png. I've already looked into the plugin folder, but I don't have any php knowledge to fix it. Could these lines be responsible for the mixed content warning? ``` echo $star_gray ? '.kk-star-ratings .kksr-star.gray { background-image: url('.$star_gray.'); }' : ''; echo $star_yellow ? '.kk-star-ratings .kksr-star.yellow { background-image: url('.$star_yellow.'); }' : ''; echo $star_orange ? '.kk-star-ratings .kksr-star.orange { background-image: url('.$star_orange.'); }' : ''; ``` I would be grateful if someone could help me to load these files via ssl.
I solved it myself. You have to remove the stars in settings / stars. Afterwards the tool recognizes ssl and will load it from a secure version of the website.
325,136
<p>I have this custom query:</p> <pre><code>if (isset($_COOKIE['myCookie']) &amp;&amp; $_COOKIE['myCookie'] == $f_r) { $args = array( 'posts_per_page' =&gt; 4, 'nopaging' =&gt; false, 'order' =&gt; 'ASC', 'orderby' =&gt; 'rand', 'tax_query' =&gt; array( array( 'taxonomy' =&gt; 'Count', 'field' =&gt; 'slug', 'terms' =&gt; $f_r, ) ) ); $query = new WP_Query( $args ); if ( $query-&gt;have_posts() ) { while ( $query-&gt;have_posts() ) { $query-&gt;the_post(); &lt;a href="&lt;?php the_field('the_link'); ?&gt; "&gt; &lt;img src="&lt;?php echo the_field('the_img'); ?&gt;" /&gt; &lt;/a&gt; } else { echo 'Oops! Something went wrong!'; } wp_reset_postdata(); </code></pre> <p>The query works, but it does not reset the data. Every time a visitor lands on the page where the query runs, it shows the exact same 4 posts as it always does. </p> <p>This code run just fine in my local environment (fetching different posts each time it runs), but on the live server it seems to be "fixed" to 4 specific posts. </p> <p>I don't understand why this is happening, so I could really use some advice here. Thanks!</p> <p>Ps. It's not the plugins or theme, because it works fine in a local environment.</p>
[ { "answer_id": 325145, "author": "ClodClod91", "author_id": 110442, "author_profile": "https://wordpress.stackexchange.com/users/110442", "pm_score": 0, "selected": false, "text": "<p>try to use</p>\n\n<p><code>wp_reset_query();\n wp_reset_postdata();</code></p>\n\n<p>As you can see here...
2019/01/09
[ "https://wordpress.stackexchange.com/questions/325136", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/157978/" ]
I have this custom query: ``` if (isset($_COOKIE['myCookie']) && $_COOKIE['myCookie'] == $f_r) { $args = array( 'posts_per_page' => 4, 'nopaging' => false, 'order' => 'ASC', 'orderby' => 'rand', 'tax_query' => array( array( 'taxonomy' => 'Count', 'field' => 'slug', 'terms' => $f_r, ) ) ); $query = new WP_Query( $args ); if ( $query->have_posts() ) { while ( $query->have_posts() ) { $query->the_post(); <a href="<?php the_field('the_link'); ?> "> <img src="<?php echo the_field('the_img'); ?>" /> </a> } else { echo 'Oops! Something went wrong!'; } wp_reset_postdata(); ``` The query works, but it does not reset the data. Every time a visitor lands on the page where the query runs, it shows the exact same 4 posts as it always does. This code run just fine in my local environment (fetching different posts each time it runs), but on the live server it seems to be "fixed" to 4 specific posts. I don't understand why this is happening, so I could really use some advice here. Thanks! Ps. It's not the plugins or theme, because it works fine in a local environment.
If order by RAND is disabled at server level, you can try doing the rand by hand by running the query and get the ids first, then running a new query from the result including x random post ids: ``` $get_all_args = array( 'fields' => 'ids', 'posts_per_page' => 99, 'order' => 'DESC', 'orderby' => 'modified', 'tax_query' => array( array( 'taxonomy' => 'Count', 'field' => 'slug', 'terms' => $f_r, ) ) ); $query_all = new WP_Query( $get_all_args ); // additional code and checks // ... // ... wp_reset_postdata(); $args = array( 'post__in ' => array_rand(array_flip( $query_all ), 4) ); $query = new WP_Query( $get_all_args ); // additional code and checks // ... // ... wp_reset_postdata(); ``` You will get 4 random posts from the latest modified posts, notice I'm not using `'posts_per_page'=> -1` since this is not a good practice and can harm your site speed
325,151
<p>From my research there are only two questions I've found around this topic on this site:</p> <ul> <li><a href="https://wordpress.stackexchange.com/questions/206907/how-to-change-in-customizer-the-site-identity-tab-required-capabilities">How to change in customizer the “site identity” tab required capabilities</a></li> <li><a href="https://wordpress.stackexchange.com/questions/84200/how-to-change-default-icon-of-custom-plugin">how to change default icon of custom plugin?</a></li> </ul> <p>outside of the site I did find:</p> <ul> <li><a href="https://premium.wpmudev.org/forums/topic/how-to-add-a-default-site-icon-in-themes-customizer" rel="nofollow noreferrer">How to Add a Default Site Icon in Theme's Customizer</a></li> </ul> <p>but when I try:</p> <pre><code>function default_icon() { global $wp_customize; $wp_customize-&gt;get_setting('site_icon',array ( 'default' =&gt; home_url() . 'img/test.png' )); } add_action('customize_register','default_icon'); </code></pre> <p>I've also tried <code>add_setting</code> with:</p> <pre><code>function default_icon() { global $wp_customize; $wp_customize-&gt;add_setting('site_icon', array( 'default' =&gt; home_url() . 'img/test.png' )); } add_action('customize_register','default_icon'); </code></pre> <p>but that doesn't work either. It will not show the default icon in the drag and drop area and renders "No Image selected":</p> <p><a href="https://i.stack.imgur.com/JOyBz.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/JOyBz.png" alt="enter image description here"></a></p> <p>In my functions.php how can I code my theme to render the default icon presently being used in the drag and drop area?</p> <p>After further testing I can set the <code>default when I code</code>:</p> <pre><code>add_action('customize_register','default_icon',10,2); </code></pre> <p>and I can see it in a dump of <code>$wp_customize</code> but as far as rendering it will not.</p>
[ { "answer_id": 325145, "author": "ClodClod91", "author_id": 110442, "author_profile": "https://wordpress.stackexchange.com/users/110442", "pm_score": 0, "selected": false, "text": "<p>try to use</p>\n\n<p><code>wp_reset_query();\n wp_reset_postdata();</code></p>\n\n<p>As you can see here...
2019/01/09
[ "https://wordpress.stackexchange.com/questions/325151", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/25271/" ]
From my research there are only two questions I've found around this topic on this site: * [How to change in customizer the “site identity” tab required capabilities](https://wordpress.stackexchange.com/questions/206907/how-to-change-in-customizer-the-site-identity-tab-required-capabilities) * [how to change default icon of custom plugin?](https://wordpress.stackexchange.com/questions/84200/how-to-change-default-icon-of-custom-plugin) outside of the site I did find: * [How to Add a Default Site Icon in Theme's Customizer](https://premium.wpmudev.org/forums/topic/how-to-add-a-default-site-icon-in-themes-customizer) but when I try: ``` function default_icon() { global $wp_customize; $wp_customize->get_setting('site_icon',array ( 'default' => home_url() . 'img/test.png' )); } add_action('customize_register','default_icon'); ``` I've also tried `add_setting` with: ``` function default_icon() { global $wp_customize; $wp_customize->add_setting('site_icon', array( 'default' => home_url() . 'img/test.png' )); } add_action('customize_register','default_icon'); ``` but that doesn't work either. It will not show the default icon in the drag and drop area and renders "No Image selected": [![enter image description here](https://i.stack.imgur.com/JOyBz.png)](https://i.stack.imgur.com/JOyBz.png) In my functions.php how can I code my theme to render the default icon presently being used in the drag and drop area? After further testing I can set the `default when I code`: ``` add_action('customize_register','default_icon',10,2); ``` and I can see it in a dump of `$wp_customize` but as far as rendering it will not.
If order by RAND is disabled at server level, you can try doing the rand by hand by running the query and get the ids first, then running a new query from the result including x random post ids: ``` $get_all_args = array( 'fields' => 'ids', 'posts_per_page' => 99, 'order' => 'DESC', 'orderby' => 'modified', 'tax_query' => array( array( 'taxonomy' => 'Count', 'field' => 'slug', 'terms' => $f_r, ) ) ); $query_all = new WP_Query( $get_all_args ); // additional code and checks // ... // ... wp_reset_postdata(); $args = array( 'post__in ' => array_rand(array_flip( $query_all ), 4) ); $query = new WP_Query( $get_all_args ); // additional code and checks // ... // ... wp_reset_postdata(); ``` You will get 4 random posts from the latest modified posts, notice I'm not using `'posts_per_page'=> -1` since this is not a good practice and can harm your site speed
325,160
<p>I have the Twenty Seventeen theme and I would like to turn off generate SVG (social icons menu) in DOM.</p> <p><a href="https://i.imgur.com/HZCqOgV.png" rel="nofollow noreferrer">https://i.imgur.com/HZCqOgV.png</a></p> <p>How can I turn off it? I do not use the social icons, but it is g</p> <p>In function.php my parent theme i see it:</p> <pre><code>require get_parent_theme_file_path( '/inc/icon-functions.php' ); </code></pre> <p>How can I override it in my child-theme to avoid generate it?</p> <p>Thank you in advance.</p>
[ { "answer_id": 325163, "author": "mahdi azarm", "author_id": 94280, "author_profile": "https://wordpress.stackexchange.com/users/94280", "pm_score": 1, "selected": false, "text": "<p>Create <code>/inc/icon-functions.php</code> file in your child-theme and modify it as you want!</p>\n\n<p...
2019/01/09
[ "https://wordpress.stackexchange.com/questions/325160", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/140882/" ]
I have the Twenty Seventeen theme and I would like to turn off generate SVG (social icons menu) in DOM. <https://i.imgur.com/HZCqOgV.png> How can I turn off it? I do not use the social icons, but it is g In function.php my parent theme i see it: ``` require get_parent_theme_file_path( '/inc/icon-functions.php' ); ``` How can I override it in my child-theme to avoid generate it? Thank you in advance.
If you look at `get_parent_theme_file_path()` it returns `apply_filters( 'parent_theme_file_path', $path, $file );` You need to add a filter here to override the location to something in your child theme, like so. ``` add_filter('parent_theme_file_path', function($path, $file) { if ($file !== '/inc/icon-functions.php') { return $path; } $path = get_stylesheet_directory() . '/' . $file; return $path; }, 10, 2); ``` You will still need to have a file for it to find at that location in your child theme, but you can put whatever you want in there.
325,183
<p>Having the exact same problem as <a href="https://wordpress.stackexchange.com/questions/248057/oembed-fails-half-of-the-times-could-i-reload-the-request-on-fail">@Hjalmar</a> on Advanced Custom Fields, but still no fix. Only the URL text displays.</p> <p><a href="https://i.stack.imgur.com/wzWos.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wzWos.png" alt="Front End oembed output"></a></p> <p>Tried the original ACF oembed option:</p> <pre><code>&lt;div class="embed-container"&gt; &lt;?php echo get_field('video_embedd'); ?&gt; &lt;/div&gt; </code></pre> <p>No luck.</p> <p>Placed the YouTube embed URL in the ACF text field and outputting it into an HTML iframe:</p> <pre><code>&lt;?php $videoEmbeddPlease = get_field('video_embedd'); if (!empty($videoEmbeddPlease)): ?&gt; &lt;iframe width="560" height="315" src="&lt;?php echo $videoEmbeddPlease?&gt;" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen&gt;&lt;/iframe&gt; &lt;?php endif ?&gt; </code></pre> <p>No luck.</p> <p>Even tried the Advanced ACF example:</p> <pre><code>&lt;?php // get iframe HTML $iframe = get_field('video_embedd'); // use preg_match to find iframe src preg_match('/src="(.+?)"/', $iframe, $matches); $src = $matches[1]; // add extra params to iframe src $params = array( 'controls' =&gt; 0, 'hd' =&gt; 1, 'autohide' =&gt; 1 ); $new_src = add_query_arg($params, $src); $iframe = str_replace($src, $new_src, $iframe); // add extra attributes to iframe html $attributes = 'frameborder="0"'; $iframe = str_replace('&gt;&lt;/iframe&gt;', ' ' . $attributes . '&gt;&lt;/iframe&gt;', $iframe); // echo $iframe echo $iframe; ?&gt; </code></pre> <p>Even tried the WYSIWYG option. </p> <pre><code>&lt;?php the_field('video_embedd'); ?&gt; </code></pre> <p>Still! No embedded video display, just the YouTube URL text on the screen.</p> <p>Any help would be incredible.</p> <p>Thank you!</p>
[ { "answer_id": 329708, "author": "Roman Nazarkin", "author_id": 92253, "author_profile": "https://wordpress.stackexchange.com/users/92253", "pm_score": 1, "selected": false, "text": "<p>Such happens when video is <strong>not publicly accessible</strong>. In my case the video was simply r...
2019/01/10
[ "https://wordpress.stackexchange.com/questions/325183", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/150803/" ]
Having the exact same problem as [@Hjalmar](https://wordpress.stackexchange.com/questions/248057/oembed-fails-half-of-the-times-could-i-reload-the-request-on-fail) on Advanced Custom Fields, but still no fix. Only the URL text displays. [![Front End oembed output](https://i.stack.imgur.com/wzWos.png)](https://i.stack.imgur.com/wzWos.png) Tried the original ACF oembed option: ``` <div class="embed-container"> <?php echo get_field('video_embedd'); ?> </div> ``` No luck. Placed the YouTube embed URL in the ACF text field and outputting it into an HTML iframe: ``` <?php $videoEmbeddPlease = get_field('video_embedd'); if (!empty($videoEmbeddPlease)): ?> <iframe width="560" height="315" src="<?php echo $videoEmbeddPlease?>" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe> <?php endif ?> ``` No luck. Even tried the Advanced ACF example: ``` <?php // get iframe HTML $iframe = get_field('video_embedd'); // use preg_match to find iframe src preg_match('/src="(.+?)"/', $iframe, $matches); $src = $matches[1]; // add extra params to iframe src $params = array( 'controls' => 0, 'hd' => 1, 'autohide' => 1 ); $new_src = add_query_arg($params, $src); $iframe = str_replace($src, $new_src, $iframe); // add extra attributes to iframe html $attributes = 'frameborder="0"'; $iframe = str_replace('></iframe>', ' ' . $attributes . '></iframe>', $iframe); // echo $iframe echo $iframe; ?> ``` Even tried the WYSIWYG option. ``` <?php the_field('video_embedd'); ?> ``` Still! No embedded video display, just the YouTube URL text on the screen. Any help would be incredible. Thank you!
Such happens when video is **not publicly accessible**. In my case the video was simply removed from YouTube by their author and ACF's oEmbed module was unable to get metadata to properly display video.
325,252
<p><strong>Code</strong></p> <p>Currently, I'm working project to automatically generate all my theme customizer options with simple array.</p> <pre><code>'nav_font_style' =&gt; array( 'default_options' =&gt; array( 1 =&gt; 'default',), 'css' =&gt; " nav#for-mobile h1 { font-family: $", 'stylesheet_handle' =&gt; 'semperfi-navigation', 'label' =&gt; __('Font', 'semper-fi-lite'), 'description' =&gt; array( 1 =&gt; '', ), 'panel_title' =&gt; __('Navigation', 'semper-fi-lite'), 'panel_priority' =&gt; 1, 'priority' =&gt; 10, 'section_title' =&gt; __('Menu Title', 'semper-fi-lite'), 'section_priority' =&gt; 10, 'selector' =&gt; 'nav#for-mobile h1', 'type' =&gt; 'font'), </code></pre> <p>This array has everything needed to generate a theme option. Bellow is the loop that it will run through.</p> <pre><code> // Add a font selector to Customizer if ($values['type'] == 'font') { $wp_customize-&gt;add_setting( $option . '_' . $i, array( 'default' =&gt; 'Default', 'sanitize_callback' =&gt; 'semperfi_sanitize_css', ) ); $wp_customize-&gt;add_control( $option . '_' . $i . '_control', array( 'section' =&gt; str_replace( "~", $semperfi_customizer_multi_dimensional_array[$i], $section_title_transformed ), 'label' =&gt; $values['label'], 'description' =&gt; $values['description'][$i], 'priority' =&gt; $values['priority'], 'type' =&gt; 'select', 'settings' =&gt; $option . '_' . $i, 'stylesheet_handle' =&gt; $values['stylesheet_handle'], 'choices' =&gt; $finalized_google_font_array)); } </code></pre> <p>When I go the sanitize_callback I'm having issues using this to access all the choices like it's explained on <a href="https://wordpress.stackexchange.com/questions/308248/how-to-get-input-attrs-in-the-sanitize-function">How to get input_attrs in the sanitize function?</a> </p> <pre><code>function semperfi_sanitize_css( $input , $setting ) { set_theme_mod( 'semperfi_testing' , $setting-&gt;manager-&gt;get_control( 'nav_font_style_1' )-&gt;input_attrs ); return $input; </code></pre> <p>}</p> <p>The above sanitize function is just for testing but I really need to access the handle so that I can apply CSS to the correct sheet style.</p> <p>Thanks for your help!</p>
[ { "answer_id": 329708, "author": "Roman Nazarkin", "author_id": 92253, "author_profile": "https://wordpress.stackexchange.com/users/92253", "pm_score": 1, "selected": false, "text": "<p>Such happens when video is <strong>not publicly accessible</strong>. In my case the video was simply r...
2019/01/10
[ "https://wordpress.stackexchange.com/questions/325252", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/76309/" ]
**Code** Currently, I'm working project to automatically generate all my theme customizer options with simple array. ``` 'nav_font_style' => array( 'default_options' => array( 1 => 'default',), 'css' => " nav#for-mobile h1 { font-family: $", 'stylesheet_handle' => 'semperfi-navigation', 'label' => __('Font', 'semper-fi-lite'), 'description' => array( 1 => '', ), 'panel_title' => __('Navigation', 'semper-fi-lite'), 'panel_priority' => 1, 'priority' => 10, 'section_title' => __('Menu Title', 'semper-fi-lite'), 'section_priority' => 10, 'selector' => 'nav#for-mobile h1', 'type' => 'font'), ``` This array has everything needed to generate a theme option. Bellow is the loop that it will run through. ``` // Add a font selector to Customizer if ($values['type'] == 'font') { $wp_customize->add_setting( $option . '_' . $i, array( 'default' => 'Default', 'sanitize_callback' => 'semperfi_sanitize_css', ) ); $wp_customize->add_control( $option . '_' . $i . '_control', array( 'section' => str_replace( "~", $semperfi_customizer_multi_dimensional_array[$i], $section_title_transformed ), 'label' => $values['label'], 'description' => $values['description'][$i], 'priority' => $values['priority'], 'type' => 'select', 'settings' => $option . '_' . $i, 'stylesheet_handle' => $values['stylesheet_handle'], 'choices' => $finalized_google_font_array)); } ``` When I go the sanitize\_callback I'm having issues using this to access all the choices like it's explained on [How to get input\_attrs in the sanitize function?](https://wordpress.stackexchange.com/questions/308248/how-to-get-input-attrs-in-the-sanitize-function) ``` function semperfi_sanitize_css( $input , $setting ) { set_theme_mod( 'semperfi_testing' , $setting->manager->get_control( 'nav_font_style_1' )->input_attrs ); return $input; ``` } The above sanitize function is just for testing but I really need to access the handle so that I can apply CSS to the correct sheet style. Thanks for your help!
Such happens when video is **not publicly accessible**. In my case the video was simply removed from YouTube by their author and ACF's oEmbed module was unable to get metadata to properly display video.
325,260
<p>I want to add an author image for each thumbnail-preview on my homepage.</p> <p>I tried <code>&lt;?php echo get_avatar( get_the_author_meta( 'ID' ), 32 ); ?&gt;</code> but it gives me the same image in every thumbnail.</p> <p>Here's the full code for the thumbnails:</p> <pre><code> &lt;?php $recentp_args = array( 'numberposts' =&gt; '4' ); $recent_posts = wp_get_recent_posts($recentp_args); foreach( $recent_posts as $recent ){ ?&gt; &lt;article&gt; &lt;a href="&lt;?php echo get_permalink($recent["ID"]); ?&gt;"&gt; &lt;?php $thumb = get_the_post_thumbnail( $recent["ID"], 'featuredmedium', array( 'class' =&gt; 'lazyload' ) ); if ( !empty($thumb) ) { // check if the post has a Post Thumbnail assigned to it. echo $thumb; } else { echo '&lt;img src="'.get_bloginfo('template_url').'/images/photo_default.png" width="320" height="167" alt="" /&gt;'; } ?&gt; &lt;h2 class="title"&gt;&lt;?php echo $recent["post_title"]; ?&gt;&lt;/h2&gt; &lt;?php echo apply_filters( 'the_content', limit_words(strip_tags($recent["post_content"]),38) ); ?&gt; &lt;?php echo get_avatar( get_the_author_meta( 'ID' ), 32 ); ?&gt; &lt;/a&gt; &lt;/article&gt; &lt;?php } ?&gt; </code></pre>
[ { "answer_id": 329708, "author": "Roman Nazarkin", "author_id": 92253, "author_profile": "https://wordpress.stackexchange.com/users/92253", "pm_score": 1, "selected": false, "text": "<p>Such happens when video is <strong>not publicly accessible</strong>. In my case the video was simply r...
2019/01/10
[ "https://wordpress.stackexchange.com/questions/325260", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/107225/" ]
I want to add an author image for each thumbnail-preview on my homepage. I tried `<?php echo get_avatar( get_the_author_meta( 'ID' ), 32 ); ?>` but it gives me the same image in every thumbnail. Here's the full code for the thumbnails: ``` <?php $recentp_args = array( 'numberposts' => '4' ); $recent_posts = wp_get_recent_posts($recentp_args); foreach( $recent_posts as $recent ){ ?> <article> <a href="<?php echo get_permalink($recent["ID"]); ?>"> <?php $thumb = get_the_post_thumbnail( $recent["ID"], 'featuredmedium', array( 'class' => 'lazyload' ) ); if ( !empty($thumb) ) { // check if the post has a Post Thumbnail assigned to it. echo $thumb; } else { echo '<img src="'.get_bloginfo('template_url').'/images/photo_default.png" width="320" height="167" alt="" />'; } ?> <h2 class="title"><?php echo $recent["post_title"]; ?></h2> <?php echo apply_filters( 'the_content', limit_words(strip_tags($recent["post_content"]),38) ); ?> <?php echo get_avatar( get_the_author_meta( 'ID' ), 32 ); ?> </a> </article> <?php } ?> ```
Such happens when video is **not publicly accessible**. In my case the video was simply removed from YouTube by their author and ACF's oEmbed module was unable to get metadata to properly display video.
325,269
<p>I am working for a public service website and we really need a text-only version of the website, or a black and white version, for people with special needs.</p> <p>Is there any plug-in or script that can do this? Thank you so much!</p>
[ { "answer_id": 325270, "author": "mrben522", "author_id": 84703, "author_profile": "https://wordpress.stackexchange.com/users/84703", "pm_score": 2, "selected": false, "text": "<p>Sounds like your actual goal is accessibility. You should check out <a href=\"https://www.w3.org/WAI/standar...
2019/01/10
[ "https://wordpress.stackexchange.com/questions/325269", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/147952/" ]
I am working for a public service website and we really need a text-only version of the website, or a black and white version, for people with special needs. Is there any plug-in or script that can do this? Thank you so much!
If you wanted to remove all colorful text from your site, you could use a global CSS rule, as in ``` * {color:black !important; background-color:white !important} ``` which should turn all text to black on white background. (The '\*" should apply to all CSS elements.) That wouldn't get rid of images or other things, so you might add this for images ``` img {display:none !important;} ``` And then add additional elements as needed. The problem with this is that it would affect the entire site, so you would need to have a way to change the theme on the fly just for the text-only users. That's not easy to do, I think. Maybe create another WP installation that uses the same database, but set up a theme for that new site that adds the above CSS and others as needed. The new site would be at <https://www.example.com/textonly> , for example. You'd also need to copy the plugins folder to the new site. Probably some additional tweaks needed, but that might get you started. **Added** As I think about the duplicate site/same database idea, with the duplicate site using a different theme, there might be an issue. The active theme is stored in wp-options table (I think), so a shared database couldn't have a different theme. So you would need to use a hook to change the theme name (and location) during the very first part of the page load process. You would still need a separate install with the shared database, but the hook would load a different theme. Perhaps function that uses a hook that would change the theme name (and location) is all that is needed. The hook would look at the page's query parameter (say <https://www.example.com/some-page?theme=textonly> )and inspect the 'theme' query parameter to decide which theme to load. I don't think that a query parameter that specifies a theme name is available in WP core - although that would be a great idea; very useful for testing new themes on an active site, which some people would like to do. But perhaps my random thoughts might get you going into a direction that will meet your needs. I'd be interested in other thoughts about this. **Added More** So, digging around possible hooks, I came up with the '`setup_theme`' hook, in the wp-settings.php around line 407. A bit later in that file (around line 438) (line numbers are there from my copy/paste from the code): ``` // Load the functions for the active theme, for both parent and child theme if applicable. 439 if ( ! wp_installing() || 'wp-activate.php' === $pagenow ) { 440 if ( TEMPLATEPATH !== STYLESHEETPATH && file_exists( STYLESHEETPATH . '/functions.php' ) ) 441 include( STYLESHEETPATH . '/functions.php' ); 442 if ( file_exists( TEMPLATEPATH . '/functions.php' ) ) 443 include( TEMPLATEPATH . '/functions.php' ); 444 } ``` So, it would seem that by changing the `TEMPLATEPATH` and `STYLESHEETPATH` constants, we could change the theme being used. So, psuedocode: ``` add_action('setup_theme', 'my_use_different_theme'); function my_use_different_theme() { TEMPLATEPATH = "path/to/the/other/theme/templates'; STYLESHEETPATH = "path/to/the/other/theme/styles"; return; } ``` Might allow you to create a function that would add the action if the query parameter contained a value like '`theme=newtheme`', where '`newtheme`' is name of the theme you want to use. Psuedocode: ``` $themename = "get/the/query/value"; if ($themename =='newtheme') { add_action('setup_theme', 'my_use_different_theme'); } ``` which would call our '`my_use_different_theme`' function if the query parameter for the page was `theme=newtheme` .
325,271
<p>I have an ACF-field, that gives an output like this:</p> <pre><code>&lt;p&gt;Lorem ipsum dolor sit amet, consectetur adipiscing elit.&lt;/p&gt; &lt;p&gt;&lt;img class="alignnone size-large wp-image-48" src="http://example.org/wp-content/uploads/2019/01/foo-bar.jpg" alt="" width="1024" height="640" /&gt;&lt;/p&gt; &lt;p&gt;Sed lacinia enim a &lt;strong&gt;est aliquet&lt;/strong&gt;, et accumsan ex pellentesque. &lt;/p&gt; &lt;p&gt;Adipiscing elit, lorem ipsum dolor sit amet, consectetur.&lt;/p&gt; </code></pre> <p>... Both images and text. </p> <p>With <a href="https://codex.wordpress.org/Function_Reference/wp_html_excerpt" rel="nofollow noreferrer">wp_html_excerpt</a> I can remove all tags, so I get one long text-blurp. </p> <p>But with WordPress' native excerpts, then it doesn't remove line-breaks or bold text, which I find nice. </p> <p>How would I go about achieving, getting an excerpt like that, from my ACF-wysiwyg-field? </p> <p>So ideally, I would call my function like this: <code>create_neat_excerpt( $html, 15 );</code> and get an output like this (from above-given input):</p> <pre><code>&lt;p&gt;Lorem ipsum dolor sit amet, consectetur adipiscing elit.&lt;/p&gt; &lt;p&gt;Sed lacinia enim a &lt;strong&gt;est aliquet&lt;/strong&gt;, et accumsan...&lt;/p&gt; </code></pre> <h2>Addition: My current attempt</h2> <pre><code>$project_desc = get_field( 'project_description' ); if( !empty( $project_desc ) ): $trimmed_text = wp_html_excerpt( $project_desc, 800 ); $last_space = strrpos( $trimmed_text, ' ' ); $modified_trimmed_text = substr( $trimmed_text, 0, $last_space ); echo $modified_trimmed_text . '...'; endif; </code></pre>
[ { "answer_id": 325351, "author": "Peter HvD", "author_id": 134918, "author_profile": "https://wordpress.stackexchange.com/users/134918", "pm_score": 0, "selected": false, "text": "<p>Use <code>the_excerpt</code> filter (see <a href=\"https://developer.wordpress.org/reference/hooks/the_ex...
2019/01/10
[ "https://wordpress.stackexchange.com/questions/325271", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/128304/" ]
I have an ACF-field, that gives an output like this: ``` <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p> <p><img class="alignnone size-large wp-image-48" src="http://example.org/wp-content/uploads/2019/01/foo-bar.jpg" alt="" width="1024" height="640" /></p> <p>Sed lacinia enim a <strong>est aliquet</strong>, et accumsan ex pellentesque. </p> <p>Adipiscing elit, lorem ipsum dolor sit amet, consectetur.</p> ``` ... Both images and text. With [wp\_html\_excerpt](https://codex.wordpress.org/Function_Reference/wp_html_excerpt) I can remove all tags, so I get one long text-blurp. But with WordPress' native excerpts, then it doesn't remove line-breaks or bold text, which I find nice. How would I go about achieving, getting an excerpt like that, from my ACF-wysiwyg-field? So ideally, I would call my function like this: `create_neat_excerpt( $html, 15 );` and get an output like this (from above-given input): ``` <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p> <p>Sed lacinia enim a <strong>est aliquet</strong>, et accumsan...</p> ``` Addition: My current attempt ---------------------------- ``` $project_desc = get_field( 'project_description' ); if( !empty( $project_desc ) ): $trimmed_text = wp_html_excerpt( $project_desc, 800 ); $last_space = strrpos( $trimmed_text, ' ' ); $modified_trimmed_text = substr( $trimmed_text, 0, $last_space ); echo $modified_trimmed_text . '...'; endif; ```
You can provide your own implementation of `wp_trim_excerpt` which is responsible for trimming and stripping HTML tags (it uses `wp_strip_all_tags`), By copying the function source code and applying the change that you want (which is keeping the `<p>` and `<strong>` tags (or any additional tags as you wish) and it will work nicely. I copied the function for you and applied the change of allowing `<p>` and `<strong>` to be on your final excerpt. **(You should put this code in your `functions.php` file)** ``` function wp_trim_excerpt_modified($text, $content_length = 55, $remove_breaks = false) { if ( '' != $text ) { $text = strip_shortcodes( $text ); $text = excerpt_remove_blocks( $text ); $text = apply_filters( 'the_content', $text ); $text = str_replace(']]>', ']]&gt;', $text); $num_words = $content_length; $more = $excerpt_more ? $excerpt_more : null; if ( null === $more ) { $more = __( '&hellip;' ); } $original_text = $text; $text = preg_replace( '@<(script|style)[^>]*?>.*?</\\1>@si', '', $text ); // Here is our modification // Allow <p> and <strong> $text = strip_tags($text, '<p>,<strong>'); if ( $remove_breaks ) $text = preg_replace('/[\r\n\t ]+/', ' ', $text); $text = trim( $text ); if ( strpos( _x( 'words', 'Word count type. Do not translate!' ), 'characters' ) === 0 && preg_match( '/^utf\-?8$/i', get_option( 'blog_charset' ) ) ) { $text = trim( preg_replace( "/[\n\r\t ]+/", ' ', $text ), ' ' ); preg_match_all( '/./u', $text, $words_array ); $words_array = array_slice( $words_array[0], 0, $num_words + 1 ); $sep = ''; } else { $words_array = preg_split( "/[\n\r\t ]+/", $text, $num_words + 1, PREG_SPLIT_NO_EMPTY ); $sep = ' '; } if ( count( $words_array ) > $num_words ) { array_pop( $words_array ); $text = implode( $sep, $words_array ); $text = $text . $more; } else { $text = implode( $sep, $words_array ); } } return $text; } ``` Notice the line that is doing the stripping: **Line:22** `$text = strip_tags($text, '<p>,<strong>');` And your code should be like this: ``` $project_desc = get_field( 'project_description' ); if( !empty( $project_desc ) ): $trimmed_text = wp_trim_excerpt_modified( $project_desc, 15 ); $last_space = strrpos( $trimmed_text, ' ' ); $modified_trimmed_text = substr( $trimmed_text, 0, $last_space ); echo $modified_trimmed_text . '...'; endif; ``` For more information, you can checkout [this answer](https://stackoverflow.com/a/24160854/4365678) on stackoverflow it is more detailed.
325,303
<p>My lost password option in the wp login page redirect to woocommerce lost password page.How to set it back to the standard wp lost password option.?I want it to redirect to "wp-login.php?action=lostpassword". I am using,woocommerce,paid membership pro,buddypress plugins. I found this <a href="https://wordpress.stackexchange.com/q/290858/158576">Lost password link is redirecting to /shop/my-account/lost-password/</a>, but I couldn't understand it.</p> <p>Thanks.</p>
[ { "answer_id": 325304, "author": "Pratik Patel", "author_id": 143123, "author_profile": "https://wordpress.stackexchange.com/users/143123", "pm_score": 2, "selected": true, "text": "<p>Try to put below code into your theme <strong>functions.php</strong> file</p>\n\n<pre><code>remove_filt...
2019/01/11
[ "https://wordpress.stackexchange.com/questions/325303", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/158576/" ]
My lost password option in the wp login page redirect to woocommerce lost password page.How to set it back to the standard wp lost password option.?I want it to redirect to "wp-login.php?action=lostpassword". I am using,woocommerce,paid membership pro,buddypress plugins. I found this [Lost password link is redirecting to /shop/my-account/lost-password/](https://wordpress.stackexchange.com/q/290858/158576), but I couldn't understand it. Thanks.
Try to put below code into your theme **functions.php** file ``` remove_filter( 'lostpassword_url', 'wc_lostpassword_url', 10 ); ``` OR ``` function reset_pass_url() { $siteURL = get_option('siteurl'); return "{$siteURL}/wp-login.php?action=lostpassword"; } add_filter( 'lostpassword_url', 'reset_pass_url', 10, 2 ); ``` Please let me know if any query. Hope it will help you.
325,361
<p>My old permalink structure is <code>/index.php/%year%/%monthnum%/%day%/%postname%/</code>. For example:</p> <p><code>https://example.com/index.php/2019/01/08/technological-innovation-for-agriculture-sector-in-india/</code></p> <p>but I want to change to "Post name". For example:</p> <pre><code>https://example.com/sample-post/ </code></pre> <p>also, want to remove <code>index.php</code>.</p> <p>When I change the permalink my old post or pages are not working </p>
[ { "answer_id": 325319, "author": "Stefano Tombolini", "author_id": 96268, "author_profile": "https://wordpress.stackexchange.com/users/96268", "pm_score": 0, "selected": false, "text": "<p>I suggest using BuddyPress user profiles feature, you don't need to enable all BuddyPress features....
2019/01/11
[ "https://wordpress.stackexchange.com/questions/325361", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/142924/" ]
My old permalink structure is `/index.php/%year%/%monthnum%/%day%/%postname%/`. For example: `https://example.com/index.php/2019/01/08/technological-innovation-for-agriculture-sector-in-india/` but I want to change to "Post name". For example: ``` https://example.com/sample-post/ ``` also, want to remove `index.php`. When I change the permalink my old post or pages are not working
I suggest using BuddyPress user profiles feature, you don't need to enable all BuddyPress features. Gravity Forms can be used to create profile-like fields, but it is not really tied to real WordPress user profiles: <https://www.gravityforms.com/creating-team-member-profiles/>
325,391
<p>I am creating a custom field <code>Tracking_ID</code> on Woocommerce, where the admin will enter the tracking ID as value.</p> <p>How can i get the value of the created custom field and display it inside the <code>customer-completed-order.php</code> </p> <p>Also (Optional) i want to show the tracking ID field in the user's <code>track-order</code> order page in his/her my-account.</p> <p><strong>Woocommerce>order field:</strong></p> <p><a href="https://i.stack.imgur.com/0Q78e.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/0Q78e.png" alt="enter image description here"></a></p> <p><strong>oceanwp-child/woocommerce/emails/customer-completed-order.php</strong></p> <pre><code>&lt;?php /* translators: %s: Customer first name */ ?&gt; &lt;p&gt;&lt;?php printf( esc_html__( 'Hi %s,', 'woocommerce' ), esc_html( $order-&gt;get_billing_first_name() ) ); ?&gt;&lt;/p&gt; &lt;?php /* translators: %s: Site title */ ?&gt; &lt;p&gt;&lt;?php printf( esc_html__( 'Your %s order is completed. Your tracking number is: {$fld}', 'woocommerce' ), esc_html( wp_specialchars_decode( get_option( 'blogname' ), ENT_QUOTES ) ) ); ?&gt;&lt;/p&gt; </code></pre>
[ { "answer_id": 325437, "author": "Melissa Freeman", "author_id": 84867, "author_profile": "https://wordpress.stackexchange.com/users/84867", "pm_score": 1, "selected": false, "text": "<p>The syntax to get your custom field is:</p>\n\n<pre><code>get_post_meta($post_id, $key, $single);\n</...
2019/01/12
[ "https://wordpress.stackexchange.com/questions/325391", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/87667/" ]
I am creating a custom field `Tracking_ID` on Woocommerce, where the admin will enter the tracking ID as value. How can i get the value of the created custom field and display it inside the `customer-completed-order.php` Also (Optional) i want to show the tracking ID field in the user's `track-order` order page in his/her my-account. **Woocommerce>order field:** [![enter image description here](https://i.stack.imgur.com/0Q78e.png)](https://i.stack.imgur.com/0Q78e.png) **oceanwp-child/woocommerce/emails/customer-completed-order.php** ``` <?php /* translators: %s: Customer first name */ ?> <p><?php printf( esc_html__( 'Hi %s,', 'woocommerce' ), esc_html( $order->get_billing_first_name() ) ); ?></p> <?php /* translators: %s: Site title */ ?> <p><?php printf( esc_html__( 'Your %s order is completed. Your tracking number is: {$fld}', 'woocommerce' ), esc_html( wp_specialchars_decode( get_option( 'blogname' ), ENT_QUOTES ) ) ); ?></p> ```
Based on Melissa's answer, here is what i did and it worked for me. ``` <?php #Tracking ID $tracking_id = get_post_meta($order->get_order_number(), 'Tracking_ID', true); if( ! empty($tracking_id) ) { ?> <p> <?php printf( esc_html__( 'Your tracking number is: %s', 'woocommerce' ), esc_html($tracking_id) );?> </p> <?php } ?> ```
325,428
<p>I have a site where I created a page that takes the gallery images from a post and puts them into a slider. </p> <p>I used the following code:</p> <pre><code>// gets the gallery info $gallery = get_post_gallery( $post-&gt;ID, false ); // makes an array of image ids $ids = explode ( ",", $gallery['ids'] ); </code></pre> <p>Then I inserted the images using wp_get_attachment_image(). </p> <p>Unfortunately, with WP 5.0 and Gutenberg, get_post_gallery no longer works with newly added content. It seems that get_post_gallery used a shortcode that no longer works with Gutenberg. </p> <p>I am still getting up to speed on Gutenberg and the block system. Until I understand that all better, I was wondering if anyone has any advice on how to get the image ids from a gallery in Gutenberg?</p>
[ { "answer_id": 325431, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 2, "selected": false, "text": "<p>The <code>get_post_gallery()</code> is a wrapper for <code>get_post_galleries()</code> that has an open ticke...
2019/01/12
[ "https://wordpress.stackexchange.com/questions/325428", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/120936/" ]
I have a site where I created a page that takes the gallery images from a post and puts them into a slider. I used the following code: ``` // gets the gallery info $gallery = get_post_gallery( $post->ID, false ); // makes an array of image ids $ids = explode ( ",", $gallery['ids'] ); ``` Then I inserted the images using wp\_get\_attachment\_image(). Unfortunately, with WP 5.0 and Gutenberg, get\_post\_gallery no longer works with newly added content. It seems that get\_post\_gallery used a shortcode that no longer works with Gutenberg. I am still getting up to speed on Gutenberg and the block system. Until I understand that all better, I was wondering if anyone has any advice on how to get the image ids from a gallery in Gutenberg?
Using birgire's suggestions, I came up with the following solution that is working well with both the old pre-WP 4.x data and the newer posts that have been added under 5.0. ``` // if there is a gallery block do this if (has_block('gallery', $post->post_content)) { $post_blocks = parse_blocks($post->post_content); $ids = $post_blocks[0][attrs][ids]; } // if there is not a gallery block do this else { // gets the gallery info $gallery = get_post_gallery( $post->ID, false ); // makes an array of image ids $ids = explode ( ",", $gallery['ids'] ); } ```
325,429
<p>I have a website running WP connected to a MySql db, where the latter uses PHP. I did not make the site and have only small experience with WP. This may be a simple question. The WP also uses Elementor. I interact with the db via phpMyAdmin.</p> <p>I have this page = <a href="http://linket.info/signup/" rel="nofollow noreferrer">http://linket.info/signup/</a> It accepts input data that does into the db.</p> <p>See the labels ('First Name' etc). I can't seem to find them defined in WP. So they are in the db? I looked in the various db tables. But still can't seem to find these labels. Can you suggest what tables I might focus on?</p>
[ { "answer_id": 325431, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 2, "selected": false, "text": "<p>The <code>get_post_gallery()</code> is a wrapper for <code>get_post_galleries()</code> that has an open ticke...
2019/01/12
[ "https://wordpress.stackexchange.com/questions/325429", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/158888/" ]
I have a website running WP connected to a MySql db, where the latter uses PHP. I did not make the site and have only small experience with WP. This may be a simple question. The WP also uses Elementor. I interact with the db via phpMyAdmin. I have this page = <http://linket.info/signup/> It accepts input data that does into the db. See the labels ('First Name' etc). I can't seem to find them defined in WP. So they are in the db? I looked in the various db tables. But still can't seem to find these labels. Can you suggest what tables I might focus on?
Using birgire's suggestions, I came up with the following solution that is working well with both the old pre-WP 4.x data and the newer posts that have been added under 5.0. ``` // if there is a gallery block do this if (has_block('gallery', $post->post_content)) { $post_blocks = parse_blocks($post->post_content); $ids = $post_blocks[0][attrs][ids]; } // if there is not a gallery block do this else { // gets the gallery info $gallery = get_post_gallery( $post->ID, false ); // makes an array of image ids $ids = explode ( ",", $gallery['ids'] ); } ```
325,469
<p>In my index page there are two slider one is working fine but the second one is giving some problems.</p> <h2>FIRST ONE</h2> <pre><code>&lt;?php global $post; $i=0; $args = array('post_per_page' =&gt; -1, 'post_type' =&gt; 'slider-items', 'page' =&gt; $paged, 'order' =&gt; 'ASC'); $myposts = get_posts($args); foreach( $myposts as $post ) : setup_postdata($post); $large_image_url = wp_get_attachment_image_src( get_post_thumbnail_id($post-&gt;ID), 'slider-items'); $i++; ?&gt; &lt;!-- Slider Item --&gt; &lt;div class="owl-item main_slider_item"&gt; &lt;div class="main_slider_item_bg" style="background-image:url(&lt;?php echo $large_image_url[0]; ?&gt;)"&gt;&lt;/div&gt; &lt;div class="main_slider_shapes"&gt;&lt;img src="&lt;?php echo get_template_directory_uri() ?&gt;/images/main_slider_shapes.png" alt="" style="width: 100% !important;"&gt;&lt;/div&gt; &lt;div class="container"&gt; &lt;div class="row"&gt; &lt;div class="col slider_content_col"&gt; &lt;div class="main_slider_content"&gt; &lt;h2&gt;&lt;/h2&gt; &lt;h2&gt;&lt;?php the_content(); ?&gt;&lt;/h2&gt; &lt;div class="button discover_button"&gt; &lt;a href="#" class="d-flex flex-row align-items-center justify-content-center"&gt;discover&lt;img src="&lt;?php echo get_template_directory_uri() ?&gt;/images/arrow_right.svg" alt=""&gt;&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;?php endforeach; ?&gt; </code></pre> <h2>SECOND ONE</h2> <pre><code>&lt;?php global $small_post; $x=0; $small_args = array('post_per_page' =&gt; -1, 'post_type' =&gt; 'bottom-slider-items', 'page' =&gt; $small_paged); $small_myposts = get_posts($small_args); foreach( $small_myposts as $small_post ) : setup_postdata($small_post); $small_image_url = wp_get_attachment_image_src( get_post_thumbnail_id($small_post-&gt;ID), 'bottom-slider-items'); $x++; ?&gt; &lt;div class="owl-item testimonials_item d-flex flex-column align-items-center justify-content-center text-center"&gt; &lt;div class="testimonials_content"&gt; &lt;div class="test_user_pic" style="background-image:url(&lt;?php echo $small_image_url[0]; ?&gt;)"&gt;&lt;/div&gt; &lt;div class="test_name"&gt;&lt;?php echo get_the_title(); ?&gt;&lt;/div&gt; &lt;div class="test_title"&gt;Company CEO&lt;/div&gt; &lt;div class="test_quote"&gt;"&lt;/div&gt; &lt;p&gt;&lt;?php the_content(); ?&gt;&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;?php endforeach; ?&gt; </code></pre> <hr> <p>When I call <code>get_the_title()</code> it shows me the title of first loop. I have added three sliders post in the first one and the second loop showing title of the last one. Please help.</p>
[ { "answer_id": 325431, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 2, "selected": false, "text": "<p>The <code>get_post_gallery()</code> is a wrapper for <code>get_post_galleries()</code> that has an open ticke...
2019/01/13
[ "https://wordpress.stackexchange.com/questions/325469", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/158922/" ]
In my index page there are two slider one is working fine but the second one is giving some problems. FIRST ONE --------- ``` <?php global $post; $i=0; $args = array('post_per_page' => -1, 'post_type' => 'slider-items', 'page' => $paged, 'order' => 'ASC'); $myposts = get_posts($args); foreach( $myposts as $post ) : setup_postdata($post); $large_image_url = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'slider-items'); $i++; ?> <!-- Slider Item --> <div class="owl-item main_slider_item"> <div class="main_slider_item_bg" style="background-image:url(<?php echo $large_image_url[0]; ?>)"></div> <div class="main_slider_shapes"><img src="<?php echo get_template_directory_uri() ?>/images/main_slider_shapes.png" alt="" style="width: 100% !important;"></div> <div class="container"> <div class="row"> <div class="col slider_content_col"> <div class="main_slider_content"> <h2></h2> <h2><?php the_content(); ?></h2> <div class="button discover_button"> <a href="#" class="d-flex flex-row align-items-center justify-content-center">discover<img src="<?php echo get_template_directory_uri() ?>/images/arrow_right.svg" alt=""></a> </div> </div> </div> </div> </div> </div> <?php endforeach; ?> ``` SECOND ONE ---------- ``` <?php global $small_post; $x=0; $small_args = array('post_per_page' => -1, 'post_type' => 'bottom-slider-items', 'page' => $small_paged); $small_myposts = get_posts($small_args); foreach( $small_myposts as $small_post ) : setup_postdata($small_post); $small_image_url = wp_get_attachment_image_src( get_post_thumbnail_id($small_post->ID), 'bottom-slider-items'); $x++; ?> <div class="owl-item testimonials_item d-flex flex-column align-items-center justify-content-center text-center"> <div class="testimonials_content"> <div class="test_user_pic" style="background-image:url(<?php echo $small_image_url[0]; ?>)"></div> <div class="test_name"><?php echo get_the_title(); ?></div> <div class="test_title">Company CEO</div> <div class="test_quote">"</div> <p><?php the_content(); ?></p> </div> </div> <?php endforeach; ?> ``` --- When I call `get_the_title()` it shows me the title of first loop. I have added three sliders post in the first one and the second loop showing title of the last one. Please help.
Using birgire's suggestions, I came up with the following solution that is working well with both the old pre-WP 4.x data and the newer posts that have been added under 5.0. ``` // if there is a gallery block do this if (has_block('gallery', $post->post_content)) { $post_blocks = parse_blocks($post->post_content); $ids = $post_blocks[0][attrs][ids]; } // if there is not a gallery block do this else { // gets the gallery info $gallery = get_post_gallery( $post->ID, false ); // makes an array of image ids $ids = explode ( ",", $gallery['ids'] ); } ```
325,489
<p>In a template, I have a need to <code>include_once</code> an external PHP (an <code>include.php</code>) that contains functions that I need to use inside the template.</p> <p>Included in those functions are CSS styles and an external JS script.</p> <p>The CSS is inside a function in the include.php. And the JS script also needs to be in the area.</p> <p>So I need to <code>include_once("includes.php")</code> (which is in the theme's root folder). I figured I would use code similar to this:</p> <pre><code>add_action('wp_head', 'fst_include',20); function fst_include() { include_once get_stylesheet_directory(). "/includes.php"; // load required functions return; } </code></pre> <p>Since the action is 'wp_head', that should get the <code>include_once("includes.php")</code> in the head area. I use <code>get_stylesheet_directory</code> because the includes.php file will be in a Child Theme.</p> <p>Once that is loaded, then I can add some CSS with this:</p> <pre><code>add_action('wp_head', 'more_css',30) // 'more_css' is a function inside the includes.php file that contains some CSS </code></pre> <p>And add some JS with</p> <pre><code>add_action('wp_head', 'some_script',30) // 'some_script' is a function inside the includes.php file that adds some JS </code></pre> <p>I give the last two add_actions a priority of '30' so they will be loaded after the includes.php file is loaded. (Because the includes.php has a priority of 20.)</p> <p>But the includes.php file doesn't appear to be loading, as the 'some_script' function (contained in includes.php) is not available, and causes an error.</p> <p>So I need a way to add a <code>include_once('includes.php')</code> so that the functions inside there are available 'later' in the template. I don't think that <code>get_template_part</code> is appropriate because the <code>include_once</code> needs to be in the section.</p> <p><strong>Added - But Why?</strong></p> <p>Why do I need to do this? My template displays a form. The form's code and functions are in the include.php file. Even the form is displayed by a function in the include.php.</p> <p>The include.php file is a 'package' of functions and scripts and actions and changing of DOM elements to perform specific functions when the form is displayed - and the user fills out the form and submits it. (The 'package' is the process that is used to protect forms - like contact forms - against spam-bots. It's an effective process, but a bit complex. If you are really interested, you can go <a href="https://www.formspammertrap.com" rel="nofollow noreferrer">here</a> to learn about it.)</p> <p>The include.php file is also built as a standalone/non-WP code that can be used on non-WP pages. I don't want to maintain two versions of the code.</p> <p>The form has to 'live' in the visual look of whatever theme is being used, if used on a WP site. I figured a template would be the best way to do that. So I need to get my include.php 'inside' the template so that it's functions can be called.</p> <p>As for the priorty used in the add_action, that was an attempt to make sure that the include.php file is included in the area so that I can call the function that includes the CSS used for the form. If include.php is not loaded first, then the CSS-calling function will fail.</p>
[ { "answer_id": 325490, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 1, "selected": false, "text": "<p>Including PHP files inside actions isn't recommended, and is considered <strong>highly unusual</strong>. If ...
2019/01/13
[ "https://wordpress.stackexchange.com/questions/325489", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/29416/" ]
In a template, I have a need to `include_once` an external PHP (an `include.php`) that contains functions that I need to use inside the template. Included in those functions are CSS styles and an external JS script. The CSS is inside a function in the include.php. And the JS script also needs to be in the area. So I need to `include_once("includes.php")` (which is in the theme's root folder). I figured I would use code similar to this: ``` add_action('wp_head', 'fst_include',20); function fst_include() { include_once get_stylesheet_directory(). "/includes.php"; // load required functions return; } ``` Since the action is 'wp\_head', that should get the `include_once("includes.php")` in the head area. I use `get_stylesheet_directory` because the includes.php file will be in a Child Theme. Once that is loaded, then I can add some CSS with this: ``` add_action('wp_head', 'more_css',30) // 'more_css' is a function inside the includes.php file that contains some CSS ``` And add some JS with ``` add_action('wp_head', 'some_script',30) // 'some_script' is a function inside the includes.php file that adds some JS ``` I give the last two add\_actions a priority of '30' so they will be loaded after the includes.php file is loaded. (Because the includes.php has a priority of 20.) But the includes.php file doesn't appear to be loading, as the 'some\_script' function (contained in includes.php) is not available, and causes an error. So I need a way to add a `include_once('includes.php')` so that the functions inside there are available 'later' in the template. I don't think that `get_template_part` is appropriate because the `include_once` needs to be in the section. **Added - But Why?** Why do I need to do this? My template displays a form. The form's code and functions are in the include.php file. Even the form is displayed by a function in the include.php. The include.php file is a 'package' of functions and scripts and actions and changing of DOM elements to perform specific functions when the form is displayed - and the user fills out the form and submits it. (The 'package' is the process that is used to protect forms - like contact forms - against spam-bots. It's an effective process, but a bit complex. If you are really interested, you can go [here](https://www.formspammertrap.com) to learn about it.) The include.php file is also built as a standalone/non-WP code that can be used on non-WP pages. I don't want to maintain two versions of the code. The form has to 'live' in the visual look of whatever theme is being used, if used on a WP site. I figured a template would be the best way to do that. So I need to get my include.php 'inside' the template so that it's functions can be called. As for the priorty used in the add\_action, that was an attempt to make sure that the include.php file is included in the area so that I can call the function that includes the CSS used for the form. If include.php is not loaded first, then the CSS-calling function will fail.
After much experimentation, and limited help from the googles, I figured how to do an '`include`' of an external functions file inside a Template. The key is to use the `get_template_part` in your Template at the beginning (after the template header). The file specified in that function must be in your Theme's root folder, although I think it could also be in the theme's template folder. ``` get_template_part('my_custom_functions'); ``` This will do the equivalent of a '`include`' in a non-WP PHP code. It will '`include`' the file called `my_custom_functions.php` . Once you do that, then you can use filters to include things in the generated page's `<head>` area, or any other filters you need, as in: ``` add_filter('wp_head','some_function'); ``` Which will call the `some_function()` function in your `my_custom_functions.php` file. (Make sure that your function names are unique, of course.) This process, which is not easily found via the googles, will let you 'include' a file and then use functions in your include file in your WP Template.
325,536
<p>I have 2 categories in my cutom post type: Cat 1 Cat 2</p> <p>I wish display a random category from this post type. I made this and it works:</p> <pre><code>function categorie(){ $global; $args = array('type' =&gt; 'carte', 'taxonomy' =&gt; 'carte-category', 'parent' =&gt; 0); $categories = get_categories($args); shuffle( $categories); $i = 0; foreach($categories as $category) { $i++; $categoryname= $category-&gt;name; $html.= '&lt;h3&gt; '. $category-&gt;name. '&lt;/h3&gt;'; $html.= '&lt;p class="txtContent"&gt; '. $category-&gt;description. '&lt;/p&gt;'; if (++$i == 2) break; } return $html; } add_shortcode( 'categorie', 'categorie' ); </code></pre> <p>But now in this random category, I wish display a thumbnail from random post</p> <p>To be clear:</p> <p>Cat1 = Menus Posts: Menu 1, menu 2...</p> <p>Cat 2 = Dishes Posts: Dish 1, Dish 2...</p> <p>If my random cat is displaying Cat1, I need the thumbnail of Menu 1 or Menu 2</p> <p>How can I do that ?</p>
[ { "answer_id": 325538, "author": "wpdev", "author_id": 133897, "author_profile": "https://wordpress.stackexchange.com/users/133897", "pm_score": -1, "selected": false, "text": "<p>Inser this inside foreach loop:</p>\n\n<pre><code>$args_query = array(\n 'order' =&gt; 'DESC',\n...
2019/01/14
[ "https://wordpress.stackexchange.com/questions/325536", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/158978/" ]
I have 2 categories in my cutom post type: Cat 1 Cat 2 I wish display a random category from this post type. I made this and it works: ``` function categorie(){ $global; $args = array('type' => 'carte', 'taxonomy' => 'carte-category', 'parent' => 0); $categories = get_categories($args); shuffle( $categories); $i = 0; foreach($categories as $category) { $i++; $categoryname= $category->name; $html.= '<h3> '. $category->name. '</h3>'; $html.= '<p class="txtContent"> '. $category->description. '</p>'; if (++$i == 2) break; } return $html; } add_shortcode( 'categorie', 'categorie' ); ``` But now in this random category, I wish display a thumbnail from random post To be clear: Cat1 = Menus Posts: Menu 1, menu 2... Cat 2 = Dishes Posts: Dish 1, Dish 2... If my random cat is displaying Cat1, I need the thumbnail of Menu 1 or Menu 2 How can I do that ?
All you need to do is to add another query in your code: ``` function categorie_shortcode_callback() { $html = ''; $categories = get_categories( array( // 'type' => 'carte', <- THERE IS NO ATTRIBUTE CALLED type FOR get_categories, SO REMOVE THAT 'taxonomy' => 'carte-category', 'parent' => 0 )); shuffle( $categories); // you also don't need to loop through that array, since you only want to get first one if ( ! empty($categories) ) { $category = $categories[0]; $html.= '<h3> '. $category->name. '</h3>'; $html.= '<p class="txtContent"> '. $category->description. '</p>'; $random_posts = get_posts( array( 'post_type' => 'carte', 'posts_per_page' => 1, 'orderby' => 'rand', 'fields' => 'ids', 'tax_query' => array( array( 'taxonomy' => 'carte-category', 'terms' => $category->term_id, 'field' => 'term_id' ) ) ) ); if ( ! empty($random_posts) ) { $html .= get_the_post_thumbnail( $random_posts[0] ); } } return $html; } add_shortcode( 'categorie', 'categorie_shortcode_callback' ); ```
325,563
<p>I created a page (<a href="https://padigital.org/rights/" rel="nofollow noreferrer">https://padigital.org/rights/</a>) to test something, then deleted it. It still appears in Google searches. However, it no longer appears in the Admin Dashboard, so I'm unable to delete/make it private. How do I find it to delete it again?</p>
[ { "answer_id": 325566, "author": "RiddleMeThis", "author_id": 86845, "author_profile": "https://wordpress.stackexchange.com/users/86845", "pm_score": 1, "selected": false, "text": "<p>Since that page has already been indexed you can do a couple things.</p>\n\n<p><strong>1</strong> - Add ...
2019/01/14
[ "https://wordpress.stackexchange.com/questions/325563", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/159001/" ]
I created a page (<https://padigital.org/rights/>) to test something, then deleted it. It still appears in Google searches. However, it no longer appears in the Admin Dashboard, so I'm unable to delete/make it private. How do I find it to delete it again?
Since that page has already been indexed you can do a couple things. **1** - Add a rule in your .htaccess file that tells search engines not to index the page ``` User-agent: * Disallow: /rights ``` **2** - Use Google's Remove URLs Tool. The Remove URLs tool enables you to temporarily block pages from Google Search results. You can [start that process here](https://www.google.com/webmasters/tools/url-removal).
325,569
<p>I want to create on my blog a category loop with the featured image. But i don't know how i do that technical.</p> <p>You should only see a list of categories and click on them to get the category site. It's like a article loop only with categories.</p> <p>Thank you for any help :)</p> <p><a href="https://i.stack.imgur.com/mRLy9.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mRLy9.jpg" alt="enter image description here"></a></p>
[ { "answer_id": 325583, "author": "Krzysiek Dróżdż", "author_id": 34172, "author_profile": "https://wordpress.stackexchange.com/users/34172", "pm_score": 1, "selected": false, "text": "<p>Well, in WP the word \"loop\" is mainly related to posts. It's easier to say that you want to display...
2019/01/14
[ "https://wordpress.stackexchange.com/questions/325569", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/158400/" ]
I want to create on my blog a category loop with the featured image. But i don't know how i do that technical. You should only see a list of categories and click on them to get the category site. It's like a article loop only with categories. Thank you for any help :) [![enter image description here](https://i.stack.imgur.com/mRLy9.jpg)](https://i.stack.imgur.com/mRLy9.jpg)
Well, in WP the word "loop" is mainly related to posts. It's easier to say that you want to display categories. All you have to do is to get them using [`get_categories`](https://developer.wordpress.org/reference/functions/get_categories/) function and display them. ``` <?php $categories = get_categories( array( 'orderby' => 'name', 'order' => 'ASC' ) ); if ( ! empty( $categories ) ) : ?> <ul> <?php foreach ( $categories as $category ) : ?> <li><a href="<?php echo esc_attr(get_category_link( $category->term_id ) ); ?>"><?php echo esc_html( $category->name ); ?></a></li> <?php endforeach; ?> </ul> <?php endif; ?> ``` And if you want to change the category title to some ACF custom field, then change this part: ``` <?php echo esc_html( $category->name ); ?> ``` to: ``` <?php echo wp_get_attachment_image( get_field('<FIELD_NAME>', $category), 'full' ); ?> ``` PS. Remember to change to real name of the field. It should return the ID of an image (and not the array - you should set it in field setting). You can also change the 'full' size to some other size.
325,574
<p>The following code should redirect the user to a specific page if they have the manage_woocommerce capability or higher - but it doesn't and just goes to the main dashboard.</p> <pre><code> add_filter( 'login_redirect', array( $this, 'login_redirect' ), 10, 3 ); public function login_redirect( $redirect_to, $request, $user ) { if( is_user_logged_in() == 1 ) { if( $user-&gt;has_cap( 'manage_woocommerce' ) ) { $redirect_to = get_admin_url() . 'admin.php?page=my-page'; } } return $redirect_to; } </code></pre> <p>I have tried <code>$user-&gt;has_cap</code>, <a href="https://codex.wordpress.org/Function_Reference/current_user_can" rel="nofollow noreferrer">current_user_can</a> with the same result. </p>
[ { "answer_id": 325587, "author": "Krzysiek Dróżdż", "author_id": 34172, "author_profile": "https://wordpress.stackexchange.com/users/34172", "pm_score": 3, "selected": true, "text": "<p>OK, it wasn't easy to catch, but... There is one major problem in your code...</p>\n\n<p>First check y...
2019/01/14
[ "https://wordpress.stackexchange.com/questions/325574", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/75779/" ]
The following code should redirect the user to a specific page if they have the manage\_woocommerce capability or higher - but it doesn't and just goes to the main dashboard. ``` add_filter( 'login_redirect', array( $this, 'login_redirect' ), 10, 3 ); public function login_redirect( $redirect_to, $request, $user ) { if( is_user_logged_in() == 1 ) { if( $user->has_cap( 'manage_woocommerce' ) ) { $redirect_to = get_admin_url() . 'admin.php?page=my-page'; } } return $redirect_to; } ``` I have tried `$user->has_cap`, [current\_user\_can](https://codex.wordpress.org/Function_Reference/current_user_can) with the same result.
OK, it wasn't easy to catch, but... There is one major problem in your code... First check you make is: ``` if ( is_user_logged_in() == 1 ) { ``` And `is_user_logged_in()` is based on global `$current_user` variable. But... As you can read in [`login_redirect` hook docs](https://codex.wordpress.org/Plugin_API/Filter_Reference/login_redirect): > > The $current\_user global may not be available at the time this filter > is run. So you should use the $user global or the $user parameter > passed to this filter. > > > So this condition won't be satisfied - so your code won't change anything. You should use `$user` variable that is passed as param, so this should do the trick: ``` public function login_redirect( $redirect_to, $request, $user ) { if ( is_a ( $user , 'WP_User' ) && $user->exists() ) { if ( $user->has_cap( 'manage_woocommerce' ) ) { $redirect_to = get_admin_url() . 'admin.php?page=my-page'; } } return $redirect_to; } add_filter( 'login_redirect', array( $this, 'login_redirect' ), 10, 3 ); ```
325,622
<p>How can I put my own code in a wordpress page? </p> <p>This happens when I tried to <a href="https://i.stack.imgur.com/27KOk.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/27KOk.png" alt="pic1"></a></p> <p><a href="https://i.stack.imgur.com/yZOyA.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/yZOyA.png" alt="pic2"></a></p>
[ { "answer_id": 325587, "author": "Krzysiek Dróżdż", "author_id": 34172, "author_profile": "https://wordpress.stackexchange.com/users/34172", "pm_score": 3, "selected": true, "text": "<p>OK, it wasn't easy to catch, but... There is one major problem in your code...</p>\n\n<p>First check y...
2019/01/15
[ "https://wordpress.stackexchange.com/questions/325622", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/159037/" ]
How can I put my own code in a wordpress page? This happens when I tried to [![pic1](https://i.stack.imgur.com/27KOk.png)](https://i.stack.imgur.com/27KOk.png) [![pic2](https://i.stack.imgur.com/yZOyA.png)](https://i.stack.imgur.com/yZOyA.png)
OK, it wasn't easy to catch, but... There is one major problem in your code... First check you make is: ``` if ( is_user_logged_in() == 1 ) { ``` And `is_user_logged_in()` is based on global `$current_user` variable. But... As you can read in [`login_redirect` hook docs](https://codex.wordpress.org/Plugin_API/Filter_Reference/login_redirect): > > The $current\_user global may not be available at the time this filter > is run. So you should use the $user global or the $user parameter > passed to this filter. > > > So this condition won't be satisfied - so your code won't change anything. You should use `$user` variable that is passed as param, so this should do the trick: ``` public function login_redirect( $redirect_to, $request, $user ) { if ( is_a ( $user , 'WP_User' ) && $user->exists() ) { if ( $user->has_cap( 'manage_woocommerce' ) ) { $redirect_to = get_admin_url() . 'admin.php?page=my-page'; } } return $redirect_to; } add_filter( 'login_redirect', array( $this, 'login_redirect' ), 10, 3 ); ```
325,663
<p>I'm trying to make some pretty URLs that show content from a category page. An example would be this: <a href="https://example.com/resources/white-paper" rel="nofollow noreferrer">https://example.com/resources/white-paper</a> (not a real WP page) would show content from <a href="https://example.com/resources/?type=white-paper" rel="nofollow noreferrer">https://example.com/resources/?type=white-paper</a>. /resources is an archive page of a custom post type, and the archive page template pulls the query string and displays posts of the respective taxonomy. Any tips on how to approach this?</p>
[ { "answer_id": 325671, "author": "WebElaine", "author_id": 102815, "author_profile": "https://wordpress.stackexchange.com/users/102815", "pm_score": -1, "selected": false, "text": "<p>As long as you're only dealing with one CPT, when you register your post type, make sure to set <code>ha...
2019/01/15
[ "https://wordpress.stackexchange.com/questions/325663", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/28497/" ]
I'm trying to make some pretty URLs that show content from a category page. An example would be this: <https://example.com/resources/white-paper> (not a real WP page) would show content from <https://example.com/resources/?type=white-paper>. /resources is an archive page of a custom post type, and the archive page template pulls the query string and displays posts of the respective taxonomy. Any tips on how to approach this?
Use [`add_rewrite_rule()`](https://codex.wordpress.org/Rewrite_API/add_rewrite_rule). ``` function wpse325663_rewrite_resource_type() { add_rewrite_rule('^resources\/(.+)/?', 'resources/?type=$matches[1]', 'top'); } add_action('init', 'wpse325663_rewrite_resource_type'); ``` An important note from [the codex](https://codex.wordpress.org/Rewrite_API/add_rewrite_rule#Example): > > Do not forget to flush and regenerate the rewrite rules database after > modifying rules. From [WordPress Administration Screens](https://codex.wordpress.org/Administration_Screens), Select > Settings -> Permalinks and just click Save Changes without any > changes. > > >
325,670
<p>Any ideal way how to change Gutenberg's categories checkboxes to radio inputs? I have tried using this plugin: <a href="https://wordpress.org/plugins/categories-metabox-enhanced/" rel="nofollow noreferrer">Categories Metabox Enhanced</a>. </p> <p>But it doesn't work fully well with Gutenberg, meaning my conditions to show some field when a term is checked doesn't work. Also this plugin adds an extra meta box without replacing Gutenberg's default categories box.</p> <p><a href="https://i.stack.imgur.com/mbNZY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mbNZY.png" alt="enter image description here"></a></p>
[ { "answer_id": 328707, "author": "leymannx", "author_id": 30597, "author_profile": "https://wordpress.stackexchange.com/users/30597", "pm_score": -1, "selected": false, "text": "<p>Yes, <a href=\"https://wordpress.org/plugins/categories-metabox-enhanced/\" rel=\"nofollow noreferrer\">Cat...
2019/01/15
[ "https://wordpress.stackexchange.com/questions/325670", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/129306/" ]
Any ideal way how to change Gutenberg's categories checkboxes to radio inputs? I have tried using this plugin: [Categories Metabox Enhanced](https://wordpress.org/plugins/categories-metabox-enhanced/). But it doesn't work fully well with Gutenberg, meaning my conditions to show some field when a term is checked doesn't work. Also this plugin adds an extra meta box without replacing Gutenberg's default categories box. [![enter image description here](https://i.stack.imgur.com/mbNZY.png)](https://i.stack.imgur.com/mbNZY.png)
Fortunately there is a hook that we can use to customize what component is used to render the taxonomy panels called `editor.PostTaxonomyType`. Gutenberg renders taxonomy panels with a component called `PostTaxonomies`, which really just checks whether the taxonomy is heirarchical or not, and passes the props along to either the `HierarchicalTermSelector` or `FlatTermSelector` components accordingly. Normally, these two components don't appear to be exposed in the Gutenberg API, except for within the `editor.PostTaxonomyType` hook, which passes the relevant component as the 1st argument. From there, all we have to do is extend the component, override the `renderTerms` method to change the input type from `checkbox` to `radio`, and override the `onChange` method to only return one selected term. Unfortunately, extending the class within the hook seemed to cause a noticable performance hit, but storing the extended class in the `window` seemed to mitigate that. [PostTaxonomies](https://github.com/WordPress/gutenberg/tree/master/packages/editor/src/components/post-taxonomies#posttaxonomies) [HierarchicalTermSelector](https://github.com/WordPress/gutenberg/blob/master/packages/editor/src/components/post-taxonomies/hierarchical-term-selector.js) ```js /** * External dependencies */ import { unescape as unescapeString } from 'lodash'; function customizeTaxonomySelector( OriginalComponent ) { return function( props ) { if ( props.slug === 'my_taxonomy') { if ( ! window.HierarchicalTermRadioSelector ) { window.HierarchicalTermRadioSelector = class HierarchicalTermRadioSelector extends OriginalComponent { // Return only the selected term ID onChange( event ) { const { onUpdateTerms, taxonomy } = this.props; const termId = parseInt( event.target.value, 10 ); onUpdateTerms( [ termId ], taxonomy.rest_base ); } // Copied from HierarchicalTermSelector, changed input type to radio renderTerms( renderedTerms ) { const { terms = [] } = this.props; return renderedTerms.map( ( term ) => { const id = `editor-post-taxonomies-hierarchical-term-${ term.id }`; return ( <div key={ term.id } className="editor-post-taxonomies__hierarchical-terms-choice"> <input id={ id } className="editor-post-taxonomies__hierarchical-terms-input" type="radio" checked={ terms.indexOf( term.id ) !== -1 } value={ term.id } onChange={ this.onChange } /> <label htmlFor={ id }>{ unescapeString( term.name ) }</label> { !! term.children.length && <div className="editor-post-taxonomies__hierarchical-terms-subchoices">{ this.renderTerms( term.children ) }</div> } </div> ); } ); } }; } return <window.HierarchicalTermRadioSelector { ...props } />; } return <OriginalComponent { ...props } />; }; } wp.hooks.addFilter( 'editor.PostTaxonomyType', 'my-custom-plugin', customizeTaxonomySelector ); ```
325,672
<p>I have created a search using WP_Query, it seems like this query is looking for the queried term in title AND tags. </p> <p>Is there a way to have this search the title OR tags?</p> <pre><code>$s = $request['s']; $tags = str_replace(' ', '-', strtolower($request['s'])); $paged = $request['page']; $posts_per_page = $request['per_page']; $result = new WP_Query([ 'post_type' =&gt; 'post', 'category__in' =&gt; 3060, 'posts_per_page' =&gt; $posts_per_page, 'paged' =&gt; $page, 'orderby' =&gt; 'date', 'order' =&gt; 'desc', 's' =&gt; $s, 'tag' =&gt; array($tags) ]); </code></pre>
[ { "answer_id": 326512, "author": "Community", "author_id": -1, "author_profile": "https://wordpress.stackexchange.com/users/-1", "pm_score": -1, "selected": false, "text": "<p>You just need to add </p>\n\n<pre><code> 'relation' =&gt; 'OR'\n</code></pre>\n\n<p>in your Query arguments.\nad...
2019/01/15
[ "https://wordpress.stackexchange.com/questions/325672", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/13679/" ]
I have created a search using WP\_Query, it seems like this query is looking for the queried term in title AND tags. Is there a way to have this search the title OR tags? ``` $s = $request['s']; $tags = str_replace(' ', '-', strtolower($request['s'])); $paged = $request['page']; $posts_per_page = $request['per_page']; $result = new WP_Query([ 'post_type' => 'post', 'category__in' => 3060, 'posts_per_page' => $posts_per_page, 'paged' => $page, 'orderby' => 'date', 'order' => 'desc', 's' => $s, 'tag' => array($tags) ]); ```
Please use below code to show posts in texonomy and titles ``` $s = $request['s']; $tags = str_replace(' ', '-', strtolower($request['s'])); $q1 = get_posts(array( 'fields' => 'id', 'post_type' => 'post', 'post_status' => 'publish', 'posts_per_page' => -1, 's' => $s )); $q2 = get_posts(array( 'fields' => 'ids', 'post_type' => 'post', 'post_status' => 'publish', 'posts_per_page' => -1, 'tag' => array($tags) )); $unique = array_unique( array_merge( $q1, $q2 ) ); $posts = get_posts(array( 'post_type' => 'post', 'post__in' => $unique, 'posts_per_page' => -1 )); if ($posts ) : foreach( $posts as $post ) : //show results endforeach; endif; ```
325,690
<p>When I try to save my site in the Gutenberg Editor it just says "Updating failed".</p> <p>How to fix that?</p>
[ { "answer_id": 325691, "author": "Noah Krasser", "author_id": 159080, "author_profile": "https://wordpress.stackexchange.com/users/159080", "pm_score": 1, "selected": false, "text": "<p>There are many reasons this error can occur. Those two were the most frequent for me:</p>\n\n<h2>Sessi...
2019/01/15
[ "https://wordpress.stackexchange.com/questions/325690", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/159080/" ]
When I try to save my site in the Gutenberg Editor it just says "Updating failed". How to fix that?
There are many reasons this error can occur. Those two were the most frequent for me: Session-Cookie -------------- Open the Javascript Console by pressing F12 and click on the tab "Console". If you see some error message that goes something like `cookie_nonce` it's a session cookie problem. The problem solves by just completely logging out and possibly also deleting all cookies of your website. File-Permissions ---------------- If you have a webserver you manage on your own it may be that file permissions are wrong. The [instructions here](https://askubuntu.com/questions/46331/how-to-avoid-using-sudo-when-working-in-var-www) have never failed to resolve my issues so far, so it's worth checking out. It's those commands: Add yourself to www-data group: ``` sudo gpasswd -a "$USER" www-data ``` Change file permissions: ``` sudo chown -R "$USER":www-data /var/www find /var/www -type f -exec chmod 0660 {} \; sudo find /var/www -type d -exec chmod 2770 {} \; ```
325,717
<p>I am new to wordpress and I just install version 5.0.3and I installed Consult theme.</p> <p>At the button of page,I am getting this message:</p> <pre><code>The-Consult By Themeruler. </code></pre> <p>How can I remove it from the pages?</p>
[ { "answer_id": 325794, "author": "Loren Rosen", "author_id": 158993, "author_profile": "https://wordpress.stackexchange.com/users/158993", "pm_score": 1, "selected": false, "text": "<p>There probably isn't a simple button you can push (unless there's a special one the theme developer cre...
2019/01/15
[ "https://wordpress.stackexchange.com/questions/325717", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/159103/" ]
I am new to wordpress and I just install version 5.0.3and I installed Consult theme. At the button of page,I am getting this message: ``` The-Consult By Themeruler. ``` How can I remove it from the pages?
There probably isn't a simple button you can push (unless there's a special one the theme developer created), but it can most likely be done via some basic theme tweaking. First, make a child theme. There are lots of tutorials about how to do that. Second, modify the child theme. Two options for this: * hide the message via CSS: Find the CSS class for some enclosing HTML tag (there are several ways to determine that), and hide it via a CSS `display:none`. One drawback is that there's a risk Google might be unhappy with the page hiding things. * customize the footer: Copy `footer.php` from the parent theme to the child theme. Edit the copy and remove the text you don't want, plus perhaps any enclosing now-empty HTML tags. One drawback is that if you later install an updated version of the parent theme, the child theme will still be using a modified version of the old footer. Also, the generic WordPress themes have a similar footer message, which many people want to remove. So a web search for 'remove proudly powered by WordPress' should find lots of tutorials. Your situation is probably almost the same.
325,720
<p>I tried everything I found online. The backend appears, including dynamic segments (withSelect, etc). But the simplest 'render-callback' doesn't appear on the frontend.</p> <p>plugin.php <pre><code>/** * Plugin Name: My Dynamic Block */ function my_plugin_render_dynamic_block( ) { return '&lt;h1&gt;Sample Block&lt;/h1&gt;'; } function register_dynamic_block() { wp_register_script( 'dynamic-block', plugins_url( '/dist/block.js ', __FILE__), array( 'wp-blocks', 'wp-element', 'wp-editor' ), filemtime( plugin_dir_path( __FILE__ ) . 'dist/block.js' ) ); register_block_type( 'my-plugin/dynamic-block', [ 'editor_script' =&gt; 'dynamic-block', 'render_callback' =&gt; 'my_plugin_render_dynamic_block', ] ); } add_action('init', 'register_dynamic_block'); </code></pre> <p>block.js</p> <pre><code>const { __ } = wp.i18n; const { registerBlockType } = wp.blocks; registerBlockType( 'my-plugin/dynamic-block', { title: 'My Dynamic Block', icon: 'megaphone', category: 'widgets', edit({attributes}) { return ( &lt;div&gt;Content&lt;/div&gt; ); }, save() { return null; }, } ); </code></pre>
[ { "answer_id": 326236, "author": "Ashiquzzaman Kiron", "author_id": 78505, "author_profile": "https://wordpress.stackexchange.com/users/78505", "pm_score": -1, "selected": false, "text": "<p>Even if you do manage to render frontend with null return, On the next page reload you'll get blo...
2019/01/15
[ "https://wordpress.stackexchange.com/questions/325720", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/158827/" ]
I tried everything I found online. The backend appears, including dynamic segments (withSelect, etc). But the simplest 'render-callback' doesn't appear on the frontend. plugin.php ``` /** * Plugin Name: My Dynamic Block */ function my_plugin_render_dynamic_block( ) { return '<h1>Sample Block</h1>'; } function register_dynamic_block() { wp_register_script( 'dynamic-block', plugins_url( '/dist/block.js ', __FILE__), array( 'wp-blocks', 'wp-element', 'wp-editor' ), filemtime( plugin_dir_path( __FILE__ ) . 'dist/block.js' ) ); register_block_type( 'my-plugin/dynamic-block', [ 'editor_script' => 'dynamic-block', 'render_callback' => 'my_plugin_render_dynamic_block', ] ); } add_action('init', 'register_dynamic_block'); ``` block.js ``` const { __ } = wp.i18n; const { registerBlockType } = wp.blocks; registerBlockType( 'my-plugin/dynamic-block', { title: 'My Dynamic Block', icon: 'megaphone', category: 'widgets', edit({attributes}) { return ( <div>Content</div> ); }, save() { return null; }, } ); ```
Even if you do manage to render frontend with null return, On the next page reload you'll get block validation error. Because your html structure on edit function will not be matching up with save function. So Instead of ``` save() { return null; }, ``` Try ``` save() { return ( <div>Content</div> ); }, ``` I hope this helps.
325,724
<p>With WP 5.0 you can now enable full width blocks in the editor by adding this to your theme: <code>add_theme_support( 'align-wide' );</code></p> <p>However, if you are using a custom theme you have to add <em>your own</em> CSS to make that work, as discussed in this <a href="https://github.com/WordPress/gutenberg/issues/8289" rel="nofollow noreferrer">Gutenberg issue</a>. There are lots of examples out there that do work, but there are scrollbar issues with all of them for anyone not on a Mac.</p> <p>The problem is if you use <code>width: 100vw</code>, which is the best way I've found to do this, on Windows devices you get a horizontal scroll bar as soon as you have a vertical scroll bar on the page. I understand this is actually per the viewport width spec, so I'm really hoping to find another way to actually make this work on <strong>all</strong> devices.</p> <p>What I have right now to enable full width is this CSS:</p> <pre><code>.entry-content .alignfull { position: relative; width: 100vw; left: 50%; right: 50%; margin-left: -50vw; margin-right: -50vw; } body .entry-content .alignfull &gt; * { width: 100vw; max-width: none; } </code></pre> <p>I then add an <code>overflow: hidden;</code> on my outside container <code>&lt;div&gt;</code> of whatever wraps <code>the_content()</code> so as to hide the scrollbar. But what I'm looking for is a solution that doesn't rely on overflow hidden which can cause all kinds of unintended consequences. Any ideas out there?</p>
[ { "answer_id": 327701, "author": "NickFMC", "author_id": 56566, "author_profile": "https://wordpress.stackexchange.com/users/56566", "pm_score": 3, "selected": true, "text": "<p>After banging my head over that horizontal scroll bar issue, I think going the other way and adding a max widt...
2019/01/16
[ "https://wordpress.stackexchange.com/questions/325724", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/17461/" ]
With WP 5.0 you can now enable full width blocks in the editor by adding this to your theme: `add_theme_support( 'align-wide' );` However, if you are using a custom theme you have to add *your own* CSS to make that work, as discussed in this [Gutenberg issue](https://github.com/WordPress/gutenberg/issues/8289). There are lots of examples out there that do work, but there are scrollbar issues with all of them for anyone not on a Mac. The problem is if you use `width: 100vw`, which is the best way I've found to do this, on Windows devices you get a horizontal scroll bar as soon as you have a vertical scroll bar on the page. I understand this is actually per the viewport width spec, so I'm really hoping to find another way to actually make this work on **all** devices. What I have right now to enable full width is this CSS: ``` .entry-content .alignfull { position: relative; width: 100vw; left: 50%; right: 50%; margin-left: -50vw; margin-right: -50vw; } body .entry-content .alignfull > * { width: 100vw; max-width: none; } ``` I then add an `overflow: hidden;` on my outside container `<div>` of whatever wraps `the_content()` so as to hide the scrollbar. But what I'm looking for is a solution that doesn't rely on overflow hidden which can cause all kinds of unintended consequences. Any ideas out there?
After banging my head over that horizontal scroll bar issue, I think going the other way and adding a max width to blocks without the alignfull classes. If you just remove your page templates wrapper and assume it as 100%. Here is a pen with the WP markup as closely emulated as I could <https://codepen.io/nickfmc/pen/vvbWQa> ``` .editor-content > *:not(.alignfull) { width: 100%; max-width: 1200px; margin-left: auto; margin-right: auto; } .editor-content > *:not(.alignfull).alignwide { max-width: 1400px; } ```
325,803
<p>I've been working on a wordpress site (geniedrinks.co.uk) using the Jevelin theme. Last night, I deactivated a plugin called WP Bakery Page Builder (js_composer) which immediately resulted in HTTP error 500 across all pages - I can't even access my wp-admin page. </p> <p>I have a feeling reactivating the plugin might correct the issue, but can't find a way to do so from within the control panel (server host is names.co.uk). I've looked for an options tab within PHPMyAdmin to try and find a list of active plugins (to add the plugin manually to the list), but can't locate said tab. Any help or alternative solutions gratefully received. </p> <p>Many thanks in advance,</p> <p>Nic</p>
[ { "answer_id": 325808, "author": "RiddleMeThis", "author_id": 86845, "author_profile": "https://wordpress.stackexchange.com/users/86845", "pm_score": 3, "selected": true, "text": "<p>You can do this by editing the database via PhpMyAdmin.</p>\n\n<p>Go to your database's <strong>Options t...
2019/01/16
[ "https://wordpress.stackexchange.com/questions/325803", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/159173/" ]
I've been working on a wordpress site (geniedrinks.co.uk) using the Jevelin theme. Last night, I deactivated a plugin called WP Bakery Page Builder (js\_composer) which immediately resulted in HTTP error 500 across all pages - I can't even access my wp-admin page. I have a feeling reactivating the plugin might correct the issue, but can't find a way to do so from within the control panel (server host is names.co.uk). I've looked for an options tab within PHPMyAdmin to try and find a list of active plugins (to add the plugin manually to the list), but can't locate said tab. Any help or alternative solutions gratefully received. Many thanks in advance, Nic
You can do this by editing the database via PhpMyAdmin. Go to your database's **Options table** and find a row called **active\_plugins**. You should see something like this... ``` a:10:{ i:0;s:49:"1and1-wordpress-wizard/1and1-wordpress-wizard.php"; i:1;s:29:"acf-repeater/acf-repeater.php"; i:2;s:30:"advanced-custom-fields/acf.php"; i:3;s:45:"limit-login-attempts/limit-login-attempts.php"; i:4;s:27:"redirection/redirection.php"; i:6;s:33:"w3-total-cache/w3-total-cache.php"; i:7;s:41:"wordpress-importer/wordpress-importer.php"; i:8;s:24:"wordpress-seo/wp-seo.php"; i:9;s:34:"wpml-string-translation/plugin.php"; } ``` You can add a new row for your plugin. You will need to know the following. * a:10 : 10 = the count of row (how many plugins are in the list) * i:0;s:49 : i = the item position in the list * i:0;s:49 : s = the character count So you you can activate a new plugin by adding a new row and change the values like this... ``` a:11:{ i:0;s:49:"1and1-wordpress-wizard/1and1-wordpress-wizard.php"; i:1;s:29:"acf-repeater/acf-repeater.php"; i:2;s:30:"advanced-custom-fields/acf.php"; i:3;s:45:"limit-login-attempts/limit-login-attempts.php"; i:4;s:27:"redirection/redirection.php"; i:6;s:33:"w3-total-cache/w3-total-cache.php"; i:7;s:41:"wordpress-importer/wordpress-importer.php"; i:8;s:24:"wordpress-seo/wp-seo.php"; i:9;s:34:"wpml-string-translation/plugin.php"; i:10;s:20:"my-plugin/plugin.php"; } ```
325,849
<p>On a site that has many different image sizes each time an image is uploaded all the different thumbnail sizes are created causing a fair bit of bloat. What would be the best way of optimising this process?</p> <p>With a custom post type of <strong>‘product’</strong>, where the different product type images have slightly different aspect orientations, should (the plugin) register all the possible image sizes? e.g.</p> <pre><code>add_image_size('small-A', 45, 67, array('center', 'center')); add_image_size('small-B', 35, 49, array('center', 'center')); add_image_size('small-C', 42, 65, array('center', 'center')); add_image_size('small-D', 50, 50, array('center', 'center'));... </code></pre> <p>But assuming when the plugin creates a product A, and the front end will never use the other formats for that size; should one only register the necessary sizes for ‘A’ format before running <code>media_handle_upload()</code>, would that affect the front end?</p> <p>Or, run <code>remove_image_size()</code> on all the unnecessary image sizes just before <code>media_handle_upload()</code>?</p> <p>Or, is there a different / best-practice approach?</p> <p>Obviously, impact on performance, scalability and especially impact on storage are of some concern.</p> <p>Thanks in advance.</p> <p>(PS. one could conceivably just generate a standard image size and place the appropriately sized image inside that with PHP, but that seems a bit like cheating and possibly creating scaling problems down the road)</p>
[ { "answer_id": 325808, "author": "RiddleMeThis", "author_id": 86845, "author_profile": "https://wordpress.stackexchange.com/users/86845", "pm_score": 3, "selected": true, "text": "<p>You can do this by editing the database via PhpMyAdmin.</p>\n\n<p>Go to your database's <strong>Options t...
2019/01/17
[ "https://wordpress.stackexchange.com/questions/325849", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/137417/" ]
On a site that has many different image sizes each time an image is uploaded all the different thumbnail sizes are created causing a fair bit of bloat. What would be the best way of optimising this process? With a custom post type of **‘product’**, where the different product type images have slightly different aspect orientations, should (the plugin) register all the possible image sizes? e.g. ``` add_image_size('small-A', 45, 67, array('center', 'center')); add_image_size('small-B', 35, 49, array('center', 'center')); add_image_size('small-C', 42, 65, array('center', 'center')); add_image_size('small-D', 50, 50, array('center', 'center'));... ``` But assuming when the plugin creates a product A, and the front end will never use the other formats for that size; should one only register the necessary sizes for ‘A’ format before running `media_handle_upload()`, would that affect the front end? Or, run `remove_image_size()` on all the unnecessary image sizes just before `media_handle_upload()`? Or, is there a different / best-practice approach? Obviously, impact on performance, scalability and especially impact on storage are of some concern. Thanks in advance. (PS. one could conceivably just generate a standard image size and place the appropriately sized image inside that with PHP, but that seems a bit like cheating and possibly creating scaling problems down the road)
You can do this by editing the database via PhpMyAdmin. Go to your database's **Options table** and find a row called **active\_plugins**. You should see something like this... ``` a:10:{ i:0;s:49:"1and1-wordpress-wizard/1and1-wordpress-wizard.php"; i:1;s:29:"acf-repeater/acf-repeater.php"; i:2;s:30:"advanced-custom-fields/acf.php"; i:3;s:45:"limit-login-attempts/limit-login-attempts.php"; i:4;s:27:"redirection/redirection.php"; i:6;s:33:"w3-total-cache/w3-total-cache.php"; i:7;s:41:"wordpress-importer/wordpress-importer.php"; i:8;s:24:"wordpress-seo/wp-seo.php"; i:9;s:34:"wpml-string-translation/plugin.php"; } ``` You can add a new row for your plugin. You will need to know the following. * a:10 : 10 = the count of row (how many plugins are in the list) * i:0;s:49 : i = the item position in the list * i:0;s:49 : s = the character count So you you can activate a new plugin by adding a new row and change the values like this... ``` a:11:{ i:0;s:49:"1and1-wordpress-wizard/1and1-wordpress-wizard.php"; i:1;s:29:"acf-repeater/acf-repeater.php"; i:2;s:30:"advanced-custom-fields/acf.php"; i:3;s:45:"limit-login-attempts/limit-login-attempts.php"; i:4;s:27:"redirection/redirection.php"; i:6;s:33:"w3-total-cache/w3-total-cache.php"; i:7;s:41:"wordpress-importer/wordpress-importer.php"; i:8;s:24:"wordpress-seo/wp-seo.php"; i:9;s:34:"wpml-string-translation/plugin.php"; i:10;s:20:"my-plugin/plugin.php"; } ```
325,855
<p><strong>EDIT</strong> <em>the title of this question was "Does anyone know if Jetpack is caching pages/content" but has been changed following the thread.</em></p> <p>I just updated a plugin I made. Among others, it does filter the content of a page using <code>the_content</code> hook.</p> <p>But I noticed that it does not behaves like it should once I pushed the changes online (some parts of my content are missing).</p> <p>Once I do disable Jetpack, it works as expected.</p> <p>Does anyone know if Jetpack is caching pages/content and how to clear that cache ?</p> <p>I didn't find anything about it online.</p> <p>Thanks ! </p>
[ { "answer_id": 325808, "author": "RiddleMeThis", "author_id": 86845, "author_profile": "https://wordpress.stackexchange.com/users/86845", "pm_score": 3, "selected": true, "text": "<p>You can do this by editing the database via PhpMyAdmin.</p>\n\n<p>Go to your database's <strong>Options t...
2019/01/17
[ "https://wordpress.stackexchange.com/questions/325855", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/70449/" ]
**EDIT** *the title of this question was "Does anyone know if Jetpack is caching pages/content" but has been changed following the thread.* I just updated a plugin I made. Among others, it does filter the content of a page using `the_content` hook. But I noticed that it does not behaves like it should once I pushed the changes online (some parts of my content are missing). Once I do disable Jetpack, it works as expected. Does anyone know if Jetpack is caching pages/content and how to clear that cache ? I didn't find anything about it online. Thanks !
You can do this by editing the database via PhpMyAdmin. Go to your database's **Options table** and find a row called **active\_plugins**. You should see something like this... ``` a:10:{ i:0;s:49:"1and1-wordpress-wizard/1and1-wordpress-wizard.php"; i:1;s:29:"acf-repeater/acf-repeater.php"; i:2;s:30:"advanced-custom-fields/acf.php"; i:3;s:45:"limit-login-attempts/limit-login-attempts.php"; i:4;s:27:"redirection/redirection.php"; i:6;s:33:"w3-total-cache/w3-total-cache.php"; i:7;s:41:"wordpress-importer/wordpress-importer.php"; i:8;s:24:"wordpress-seo/wp-seo.php"; i:9;s:34:"wpml-string-translation/plugin.php"; } ``` You can add a new row for your plugin. You will need to know the following. * a:10 : 10 = the count of row (how many plugins are in the list) * i:0;s:49 : i = the item position in the list * i:0;s:49 : s = the character count So you you can activate a new plugin by adding a new row and change the values like this... ``` a:11:{ i:0;s:49:"1and1-wordpress-wizard/1and1-wordpress-wizard.php"; i:1;s:29:"acf-repeater/acf-repeater.php"; i:2;s:30:"advanced-custom-fields/acf.php"; i:3;s:45:"limit-login-attempts/limit-login-attempts.php"; i:4;s:27:"redirection/redirection.php"; i:6;s:33:"w3-total-cache/w3-total-cache.php"; i:7;s:41:"wordpress-importer/wordpress-importer.php"; i:8;s:24:"wordpress-seo/wp-seo.php"; i:9;s:34:"wpml-string-translation/plugin.php"; i:10;s:20:"my-plugin/plugin.php"; } ```
325,871
<p>Hi I used the Edin theme to build a wordpress website. I modified a big part of the CSS at the CSS editor, without having a clue what a child theme is. What should I do now? Create a child theme and delete the additional CSS of the parent theme? Any ideas?</p> <p>Thank you very much!! </p>
[ { "answer_id": 325872, "author": "Nour Edin Al-Habal", "author_id": 97257, "author_profile": "https://wordpress.stackexchange.com/users/97257", "pm_score": -1, "selected": false, "text": "<p>If you've changed the original theme files, create a child theme and move your changes to the new...
2019/01/17
[ "https://wordpress.stackexchange.com/questions/325871", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/159229/" ]
Hi I used the Edin theme to build a wordpress website. I modified a big part of the CSS at the CSS editor, without having a clue what a child theme is. What should I do now? Create a child theme and delete the additional CSS of the parent theme? Any ideas? Thank you very much!!
As [Jacob Peattie](https://wordpress.stackexchange.com/users/39152/jacob-peattie) mentioned, you've made custom CSS changes in a way that does not impact your theme. To expand a bit more, this is the *only* place you can make changes that will persist through a theme update or change. All other customizations get wiped. So if you find you want to make further changes, you can create a child theme. You'll need access to the server/file system for this. First create a new folder/directory in `wp-content/themes/` You need to add two files to this directory: `style.css` and `functions.php` In the `style.css` file add the following information: ``` /* Theme Name: Edin Child Template: edin */ ``` Those are the only two required things in this file. Note that I have assumed that the "Template" is "edin"; make sure this is actually the parent theme directory name. [More info.](https://developer.wordpress.org/themes/advanced-topics/child-themes/#2-create-a-stylesheet-style-css) Next is the `functions.php` file, which is a little more involved. Here is where tell your child theme to import information from its parent as well as importing its own style info. ``` <?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' ); // get_template_directory_uri() returns the URI of the current parent theme, set in "Template" in your style.css wp_enqueue_style( 'child-style', get_stylesheet_directory_uri() . '/style.css', array( $parent_style ), wp_get_theme()->get('Version') ); // get_stylesheet_directory_uri() returns the child theme URI } ?> ``` Then you'll have to zip your child theme directory up and upload it via the WP admin (or upload via ftp to `/wp-content/`, no zipping required), and finally activate the child theme. [More info.](https://developer.wordpress.org/themes/advanced-topics/child-themes/#3-enqueue-stylesheet) You can find more about creating child themes directly from the [WordPress theme development docs.](https://developer.wordpress.org/themes/advanced-topics/child-themes/)
325,873
<p>I created a field to enter whatsapp number in the front of a site in wordpress, since the back is simple, but I need to change it from the front section for the users <a href="https://i.stack.imgur.com/7sGZZ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/7sGZZ.png" alt="enter image description here"></a></p> <p>I have already placed an input where I show the user's information, the other fields already come by default in the subject.</p> <pre><code>&lt;div class="form-group"&gt; &lt;div class="stm-label h4"&gt;&lt;?php esc_html_e('Whatsapp', 'motors'); ?&gt;&lt;/div&gt; &lt;?php $author_id = get_the_author_meta('ID'); $author_badge = get_field('n_whatsapp', 'user_'. $author_id ); ?&gt; &lt;input class="form-control" type="text" name="stm_phone" value="&lt;?php echo esc_attr($author_badge); ?&gt;" placeholder="&lt;?php esc_html_e('Incluir whatsapp', 'motors'); ?&gt;"/&gt; &lt;/div&gt; &lt;input type="text" id="id_whatsapp" name="acf[n_whatsapp]" value="acf[n_whatsapp]"&gt; &lt;?php acf_form(); ?&gt; &lt;/div&gt; &lt;/div&gt; </code></pre>
[ { "answer_id": 325872, "author": "Nour Edin Al-Habal", "author_id": 97257, "author_profile": "https://wordpress.stackexchange.com/users/97257", "pm_score": -1, "selected": false, "text": "<p>If you've changed the original theme files, create a child theme and move your changes to the new...
2019/01/17
[ "https://wordpress.stackexchange.com/questions/325873", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/129154/" ]
I created a field to enter whatsapp number in the front of a site in wordpress, since the back is simple, but I need to change it from the front section for the users [![enter image description here](https://i.stack.imgur.com/7sGZZ.png)](https://i.stack.imgur.com/7sGZZ.png) I have already placed an input where I show the user's information, the other fields already come by default in the subject. ``` <div class="form-group"> <div class="stm-label h4"><?php esc_html_e('Whatsapp', 'motors'); ?></div> <?php $author_id = get_the_author_meta('ID'); $author_badge = get_field('n_whatsapp', 'user_'. $author_id ); ?> <input class="form-control" type="text" name="stm_phone" value="<?php echo esc_attr($author_badge); ?>" placeholder="<?php esc_html_e('Incluir whatsapp', 'motors'); ?>"/> </div> <input type="text" id="id_whatsapp" name="acf[n_whatsapp]" value="acf[n_whatsapp]"> <?php acf_form(); ?> </div> </div> ```
As [Jacob Peattie](https://wordpress.stackexchange.com/users/39152/jacob-peattie) mentioned, you've made custom CSS changes in a way that does not impact your theme. To expand a bit more, this is the *only* place you can make changes that will persist through a theme update or change. All other customizations get wiped. So if you find you want to make further changes, you can create a child theme. You'll need access to the server/file system for this. First create a new folder/directory in `wp-content/themes/` You need to add two files to this directory: `style.css` and `functions.php` In the `style.css` file add the following information: ``` /* Theme Name: Edin Child Template: edin */ ``` Those are the only two required things in this file. Note that I have assumed that the "Template" is "edin"; make sure this is actually the parent theme directory name. [More info.](https://developer.wordpress.org/themes/advanced-topics/child-themes/#2-create-a-stylesheet-style-css) Next is the `functions.php` file, which is a little more involved. Here is where tell your child theme to import information from its parent as well as importing its own style info. ``` <?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' ); // get_template_directory_uri() returns the URI of the current parent theme, set in "Template" in your style.css wp_enqueue_style( 'child-style', get_stylesheet_directory_uri() . '/style.css', array( $parent_style ), wp_get_theme()->get('Version') ); // get_stylesheet_directory_uri() returns the child theme URI } ?> ``` Then you'll have to zip your child theme directory up and upload it via the WP admin (or upload via ftp to `/wp-content/`, no zipping required), and finally activate the child theme. [More info.](https://developer.wordpress.org/themes/advanced-topics/child-themes/#3-enqueue-stylesheet) You can find more about creating child themes directly from the [WordPress theme development docs.](https://developer.wordpress.org/themes/advanced-topics/child-themes/)
325,875
<p>I've inherited a wordpress website I need to maintain. Despite having upgraded it to the latest version (5.03), and having changed the theme, there seems to be some customisations which survived. These seem to be CSS related, affecting the general page template, as well as a specific plug-in. I would like to remove these customisations. </p> <p>I am not a wordrpess dev, any pointers as to where to look would be appreciated.</p>
[ { "answer_id": 325879, "author": "WebElaine", "author_id": 102815, "author_profile": "https://wordpress.stackexchange.com/users/102815", "pm_score": 3, "selected": true, "text": "<p>When you inspect elements on the affected pages, it should tell you which CSS file is enforcing the rule. ...
2019/01/17
[ "https://wordpress.stackexchange.com/questions/325875", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/68023/" ]
I've inherited a wordpress website I need to maintain. Despite having upgraded it to the latest version (5.03), and having changed the theme, there seems to be some customisations which survived. These seem to be CSS related, affecting the general page template, as well as a specific plug-in. I would like to remove these customisations. I am not a wordrpess dev, any pointers as to where to look would be appreciated.
When you inspect elements on the affected pages, it should tell you which CSS file is enforcing the rule. If the file is somewhere inside `/wp-content/plugins/` then a plugin is adding them and you can either disable that plugin or see whether they have properly enqueued the CSS. If inside the plugin the style is added like this: `wp_enqueue_style(...);` and you need the plugin's functionality, just not the styles, you can create a child theme and inside its `functions.php` file add ``` add_action('wp_enqueue_scripts', 'wpse_325875_dequeue_plugin_css'); function wpse_325875_dequeue_plugin_css() { wp_deregister_style(...); } ``` (replacing the ... with the same name the original plugin uses, so that it dequeues that particular file.) Another possibility is that the dev before you may have modified Core files, which would be somewhere inside `/wp-content/admin/` or `/wp-content/includes/`. Usually updating Core fixes this type of problem, but you can also manually download the .zip file from wordpress.org and overwrite your `wp-admin` and `wp-includes` folder. (Be careful not to overwrite `wp-content` as that contains all of your plugins as well as media uploads, like jpgs and pdfs.) That will ensure you're using non-modified Core files. As with any changes, make sure you have a complete backup of both files and database before making changes. :)
325,886
<p>I import image to wordpress via <code>wp_insert_attachment</code>. </p> <p>On frontend wordpress media library still don't know that image is imported. I need a way to update attachments in media library without refreshing page.</p> <p>I found partial solution:</p> <pre><code>wp.media.frame.on('open', function() { if (wp.media.frame.content.get() !== null) { wp.media.frame.content.get().collection.props.set({ignore: (+ new Date())}); wp.media.frame.content.get().options.selection.reset(); } else { wp.media.frame.library.props.set({ignore: (+ new Date())}); } }, this); </code></pre> <p>Problem with this part of code is that now when I try to upload photo using Media Library uploader, image is uploaded correctly but it's not displayed. </p>
[ { "answer_id": 325890, "author": "Nour Edin Al-Habal", "author_id": 97257, "author_profile": "https://wordpress.stackexchange.com/users/97257", "pm_score": 0, "selected": false, "text": "<p>This depends on how you use <code>wp_insert_attachment()</code>. Here is a full example copied fro...
2019/01/17
[ "https://wordpress.stackexchange.com/questions/325886", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/107666/" ]
I import image to wordpress via `wp_insert_attachment`. On frontend wordpress media library still don't know that image is imported. I need a way to update attachments in media library without refreshing page. I found partial solution: ``` wp.media.frame.on('open', function() { if (wp.media.frame.content.get() !== null) { wp.media.frame.content.get().collection.props.set({ignore: (+ new Date())}); wp.media.frame.content.get().options.selection.reset(); } else { wp.media.frame.library.props.set({ignore: (+ new Date())}); } }, this); ``` Problem with this part of code is that now when I try to upload photo using Media Library uploader, image is uploaded correctly but it's not displayed.
edit: ok after working on this for the last hour ive finally found a solution that works without affecting uploading and without messing with ignore or reset ``` wp.media.frame.on('open', function() { if (wp.media.frame.content.get() !== null) { // this forces a refresh of the content wp.media.frame.content.get().collection._requery(true); // optional: reset selection wp.media.frame.content.get().options.selection.reset(); } }, this); ```
325,937
<p>I am in the process of rescuing the content from a WordPress site with a bloated/damaged database. Everything has gone according to plan except for the comments. I can see that the 4000+ comments are indeed in the database's <code>wp_comments</code> table, and I verified that the IDs of the associated posts are correct, but none of them show up in the WordPress admin area or the front-end. I haven't been able to find where the issue lies.</p> <p>Maybe someone in the community has an idea for a possible fix? Thanks.</p> <p>Edit: to clarify, I already moved the content to a new database, the issue happens on the new WordPress installation. The comments were imported to the database when importing the posts through the export/import tool.</p>
[ { "answer_id": 325890, "author": "Nour Edin Al-Habal", "author_id": 97257, "author_profile": "https://wordpress.stackexchange.com/users/97257", "pm_score": 0, "selected": false, "text": "<p>This depends on how you use <code>wp_insert_attachment()</code>. Here is a full example copied fro...
2019/01/18
[ "https://wordpress.stackexchange.com/questions/325937", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/159268/" ]
I am in the process of rescuing the content from a WordPress site with a bloated/damaged database. Everything has gone according to plan except for the comments. I can see that the 4000+ comments are indeed in the database's `wp_comments` table, and I verified that the IDs of the associated posts are correct, but none of them show up in the WordPress admin area or the front-end. I haven't been able to find where the issue lies. Maybe someone in the community has an idea for a possible fix? Thanks. Edit: to clarify, I already moved the content to a new database, the issue happens on the new WordPress installation. The comments were imported to the database when importing the posts through the export/import tool.
edit: ok after working on this for the last hour ive finally found a solution that works without affecting uploading and without messing with ignore or reset ``` wp.media.frame.on('open', function() { if (wp.media.frame.content.get() !== null) { // this forces a refresh of the content wp.media.frame.content.get().collection._requery(true); // optional: reset selection wp.media.frame.content.get().options.selection.reset(); } }, this); ```
325,938
<p>.htaccess:</p> <pre><code>&lt;IfModule mod_rewrite.c&gt; RewriteEngine On RewriteBase /wp_test/ RewriteRule ^index\.php$ - [L] RewriteRule ^the_image$ wp-content/uploads/2019/01/banner\.jpg [L] RewriteRule ^the_page$ sample-page [L] &lt;/IfModule&gt; </code></pre> <p>When I go to <code>example.com/the_image</code> it shows the correct image. However, if I go to <code>example.com/the_page</code> it shows the page not found page.</p> <p>Any work around on this?</p>
[ { "answer_id": 325890, "author": "Nour Edin Al-Habal", "author_id": 97257, "author_profile": "https://wordpress.stackexchange.com/users/97257", "pm_score": 0, "selected": false, "text": "<p>This depends on how you use <code>wp_insert_attachment()</code>. Here is a full example copied fro...
2019/01/18
[ "https://wordpress.stackexchange.com/questions/325938", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/154532/" ]
.htaccess: ``` <IfModule mod_rewrite.c> RewriteEngine On RewriteBase /wp_test/ RewriteRule ^index\.php$ - [L] RewriteRule ^the_image$ wp-content/uploads/2019/01/banner\.jpg [L] RewriteRule ^the_page$ sample-page [L] </IfModule> ``` When I go to `example.com/the_image` it shows the correct image. However, if I go to `example.com/the_page` it shows the page not found page. Any work around on this?
edit: ok after working on this for the last hour ive finally found a solution that works without affecting uploading and without messing with ignore or reset ``` wp.media.frame.on('open', function() { if (wp.media.frame.content.get() !== null) { // this forces a refresh of the content wp.media.frame.content.get().collection._requery(true); // optional: reset selection wp.media.frame.content.get().options.selection.reset(); } }, this); ```
325,943
<p>Adding images to a post with the block editor:</p> <p><a href="https://i.stack.imgur.com/HxXQ7.png" rel="noreferrer"><img src="https://i.stack.imgur.com/HxXQ7.png" alt="enter image description here"></a></p> <p>produces the code figure of:</p> <pre><code>&lt;figure class="wp-block-image"&gt; &lt;img src="http://localhost:8888/time.png" alt="alt text" class="wp-image-1391"/&gt; &lt;figcaption&gt;This is an image test.&lt;/figcaption&gt; &lt;/figure&gt; </code></pre> <p>but I'm using Bootstrap 4 and would like to add <a href="https://getbootstrap.com/docs/4.2/utilities/spacing/" rel="noreferrer">Spacing</a> (such as <code>mt-2</code>) and to remove the image class <code>wp-image-1391</code>, result:</p> <pre><code>&lt;figure class="mt-2"&gt; &lt;img src="http://localhost:8888/time.png" alt="alt text" class="img-fluid"/&gt; &lt;figcaption&gt;This is an image test.&lt;/figcaption&gt; &lt;/figure&gt; </code></pre> <p>or be able to modify it to a div:</p> <pre><code>&lt;div class="mt-2"&gt; &lt;img src="http://localhost:8888/time.png" alt="alt text" class="img-fluid"/&gt; &lt;figcaption&gt;This is an image test.&lt;/figcaption&gt; &lt;/div&gt; </code></pre> <p>Researching I've found <a href="https://developer.wordpress.org/reference/hooks/get_image_tag_class/" rel="noreferrer"><code>get_image_tag_class</code></a> but testing:</p> <pre><code>function example_add_img_class($class) { return $class . ' img-fluid'; } add_filter('get_image_tag_class','example_add_img_class'); </code></pre> <p>doesn't work. Reading "<a href="https://stackoverflow.com/questions/49779347/how-can-i-prevent-wordpress-from-adding-extra-classes-to-element-in-the-wysiwyg?rq=1">How can I prevent WordPress from adding extra classes to element in the WYSIWYG editor</a>" I tested:</p> <pre><code>add_filter('get_image_tag_class','__return_empty_string'); </code></pre> <p>but doesn't work. I can modify the <code>&lt;img&gt;</code> with a <code>preg_replace</code> using <code>the_content</code> add_filter:</p> <pre><code>function add_image_fluid_class($content) { global $post; $pattern = "/&lt;img(.*?)class=\"(.*?)\"(.*?)&gt;/i"; $replacement = '&lt;img$1class="$2 img-fluid"$3&gt;'; $content = preg_replace($pattern,$replacement,$content); return $content; } add_filter('the_content','add_image_fluid_class'); function img_responsive($content){ return str_replace('&lt;img class="','&lt;img class="img-responsive ',$content); } add_filter('the_content','img_responsive'); </code></pre> <p>but I've read that targeting <code>the_content</code> with regex can yield mixed results. I could solve the issue with a simple CSS:</p> <pre><code>figure img { width:100%; height:auto; } figure figcaption { text-align:center; font-size:80%; } </code></pre> <p>but I'd like to understand more of what filters I can use to modify WordPress. How can I add and remove classes and change figure to a div?</p>
[ { "answer_id": 326009, "author": "user9447", "author_id": 25271, "author_profile": "https://wordpress.stackexchange.com/users/25271", "pm_score": 2, "selected": false, "text": "<p>The following answer is a solution for Bootstrap 4 and centering images in a <code>&lt;figure&gt;</code> tag...
2019/01/18
[ "https://wordpress.stackexchange.com/questions/325943", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/25271/" ]
Adding images to a post with the block editor: [![enter image description here](https://i.stack.imgur.com/HxXQ7.png)](https://i.stack.imgur.com/HxXQ7.png) produces the code figure of: ``` <figure class="wp-block-image"> <img src="http://localhost:8888/time.png" alt="alt text" class="wp-image-1391"/> <figcaption>This is an image test.</figcaption> </figure> ``` but I'm using Bootstrap 4 and would like to add [Spacing](https://getbootstrap.com/docs/4.2/utilities/spacing/) (such as `mt-2`) and to remove the image class `wp-image-1391`, result: ``` <figure class="mt-2"> <img src="http://localhost:8888/time.png" alt="alt text" class="img-fluid"/> <figcaption>This is an image test.</figcaption> </figure> ``` or be able to modify it to a div: ``` <div class="mt-2"> <img src="http://localhost:8888/time.png" alt="alt text" class="img-fluid"/> <figcaption>This is an image test.</figcaption> </div> ``` Researching I've found [`get_image_tag_class`](https://developer.wordpress.org/reference/hooks/get_image_tag_class/) but testing: ``` function example_add_img_class($class) { return $class . ' img-fluid'; } add_filter('get_image_tag_class','example_add_img_class'); ``` doesn't work. Reading "[How can I prevent WordPress from adding extra classes to element in the WYSIWYG editor](https://stackoverflow.com/questions/49779347/how-can-i-prevent-wordpress-from-adding-extra-classes-to-element-in-the-wysiwyg?rq=1)" I tested: ``` add_filter('get_image_tag_class','__return_empty_string'); ``` but doesn't work. I can modify the `<img>` with a `preg_replace` using `the_content` add\_filter: ``` function add_image_fluid_class($content) { global $post; $pattern = "/<img(.*?)class=\"(.*?)\"(.*?)>/i"; $replacement = '<img$1class="$2 img-fluid"$3>'; $content = preg_replace($pattern,$replacement,$content); return $content; } add_filter('the_content','add_image_fluid_class'); function img_responsive($content){ return str_replace('<img class="','<img class="img-responsive ',$content); } add_filter('the_content','img_responsive'); ``` but I've read that targeting `the_content` with regex can yield mixed results. I could solve the issue with a simple CSS: ``` figure img { width:100%; height:auto; } figure figcaption { text-align:center; font-size:80%; } ``` but I'd like to understand more of what filters I can use to modify WordPress. How can I add and remove classes and change figure to a div?
After some digging and trial/error I have came up with a couple solutions. I was looking for a "Gutenberg" solution so I could avoid using `str_replace`. First, we need to enqueue our JS and include the wp.blocks package ``` // Add to functions.php function gutenberg_enqueue() { wp_enqueue_script( 'myguten-script', // get_template_directory_uri() . '/js/gutenberg.js', // For Parent Themes get_stylesheet_directory_uri() . '/js/gutenberg.js', // For Child Themes array('wp-blocks') // Include wp.blocks Package ); } add_action('enqueue_block_editor_assets', 'gutenberg_enqueue'); ``` --- Next, I found a couple solutions, the first is probably the best for your specific use-case. **Method #1** Use a filter function to override the default class. Well, in this case we are going to keep the "wp-block-image" class and just add the needed bootstrap class mt-2. But you could easily add whatever class you wanted. Add the code below and create a new image block, inspect it to see the figure tag now has the new class. ``` // Add to your JS file function setBlockCustomClassName(className, blockName) { return blockName === 'core/image' ? 'wp-block-image mt-2' : className; } wp.hooks.addFilter( 'blocks.getBlockDefaultClassName', 'my-plugin/set-block-custom-class-name', setBlockCustomClassName ); ``` --- **Method #2** Add a setting in the block styles settings in the sidebar to add a class to the image. ``` // Add to your JS file wp.blocks.registerBlockStyle('core/image', { name: 'test-image-class', label: 'Test Class' }); ``` [![enter image description here](https://i.stack.imgur.com/aIN1t.png)](https://i.stack.imgur.com/aIN1t.png) This will add your class but unfortunately Gutenberg appends is-style- before the class, so it results in is-style-test-image-class. You would have to adjust your CSS accordingly. --- **Method #3** Manually adding the class via the Block > Advanced > Additional CSS Class option. Obviously, the class would need to be added for each image block. [![enter image description here](https://i.stack.imgur.com/9DiVW.png)](https://i.stack.imgur.com/9DiVW.png) --- **Note:** When adding or editing any of the JS above I needed to delete the block, refresh the page and then re-add the block to avoid getting a [block validation error](https://wordpress.org/gutenberg/handbook/designers-developers/developers/block-api/block-edit-save/#validation). **References:** [Block Style Variations](https://wordpress.org/gutenberg/handbook/designers-developers/developers/filters/block-filters/#block-style-variations) [blocks.getBlockDefaultClassName](https://wordpress.org/gutenberg/handbook/designers-developers/developers/filters/block-filters/#blocks-getblockdefaultclassname)
325,956
<p>I have a code that displays results for search but, I need it to include the count not just keyword searched</p> <pre><code>&lt;h1 class="font-thin h2 m-b"&gt; &lt;?php printf( esc_html__( 'Search Results for: %s', 'musik' ), '&lt;span class="font-bold"&gt;' . get_search_query() . '&lt;/span&gt;' ); ?&gt; &lt;/h1&gt; </code></pre>
[ { "answer_id": 325957, "author": "Mohsin Ghouri", "author_id": 159253, "author_profile": "https://wordpress.stackexchange.com/users/159253", "pm_score": 1, "selected": false, "text": "<p>If you are in the search results template then you can find out the count by using the below code.</p...
2019/01/18
[ "https://wordpress.stackexchange.com/questions/325956", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/159276/" ]
I have a code that displays results for search but, I need it to include the count not just keyword searched ``` <h1 class="font-thin h2 m-b"> <?php printf( esc_html__( 'Search Results for: %s', 'musik' ), '<span class="font-bold">' . get_search_query() . '</span>' ); ?> </h1> ```
If you are in the search results template then you can find out the count by using the below code. ``` global $wp_query; $count = $wp_query->found_posts ``` variable `$count` contains the count of post against the search.
326,005
<p>the answer to this one will probably be obvious to many of you, but I recently decided to make a website for my girlfriend and expand my knowledge while doing that. So here is my dilemma:</p> <p>I am using the Blossom Mommy Blog theme, which is a child of the Blossom Feminine theme.</p> <p>Below a single post page, there is a previous post/ next post navigation menu, that has some text in English and I want to change that to be in Bulgarian (see attached file below). I was able to see this in the browser debugger, but I can't seem to find where this comes from in the theme files themself, so any help would be really appreciated!</p> <p><a href="https://i.stack.imgur.com/vbgFU.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vbgFU.png" alt="Here&#39;s what I want to change"></a></p> <p>With many thanks, Dobri</p>
[ { "answer_id": 325957, "author": "Mohsin Ghouri", "author_id": 159253, "author_profile": "https://wordpress.stackexchange.com/users/159253", "pm_score": 1, "selected": false, "text": "<p>If you are in the search results template then you can find out the count by using the below code.</p...
2019/01/18
[ "https://wordpress.stackexchange.com/questions/326005", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/159310/" ]
the answer to this one will probably be obvious to many of you, but I recently decided to make a website for my girlfriend and expand my knowledge while doing that. So here is my dilemma: I am using the Blossom Mommy Blog theme, which is a child of the Blossom Feminine theme. Below a single post page, there is a previous post/ next post navigation menu, that has some text in English and I want to change that to be in Bulgarian (see attached file below). I was able to see this in the browser debugger, but I can't seem to find where this comes from in the theme files themself, so any help would be really appreciated! [![Here's what I want to change](https://i.stack.imgur.com/vbgFU.png)](https://i.stack.imgur.com/vbgFU.png) With many thanks, Dobri
If you are in the search results template then you can find out the count by using the below code. ``` global $wp_query; $count = $wp_query->found_posts ``` variable `$count` contains the count of post against the search.
326,013
<p>I'm loading some third party CSS with the help of wp_enqueue_style. I would like this CSS to be loaded in the footer, so it does not block rendering of the page. This would be fine, since this CSS is related to some chat functionality which is loaded on the page right away anyway. For JS, there is an option for adding right before the end of the body tag, instead of at the top of the page, but no such thing seem to exist for CSS. So, I'm wondering if there is some smart solution for this?</p> <p>-- <strong>Edit</strong></p> <p>I know that strictly speaking, style and link tags are not allowed anywhere but in the head, but I think it's a debatable question. Browsers do not complain about this and why would Google recommend this practice if it was so bad?</p>
[ { "answer_id": 326019, "author": "admcfajn", "author_id": 123674, "author_profile": "https://wordpress.stackexchange.com/users/123674", "pm_score": 3, "selected": true, "text": "<p>Yes, technically you can. But you shouldn't load css in the footer, css links outside of the <code>&lt;head...
2019/01/18
[ "https://wordpress.stackexchange.com/questions/326013", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/5079/" ]
I'm loading some third party CSS with the help of wp\_enqueue\_style. I would like this CSS to be loaded in the footer, so it does not block rendering of the page. This would be fine, since this CSS is related to some chat functionality which is loaded on the page right away anyway. For JS, there is an option for adding right before the end of the body tag, instead of at the top of the page, but no such thing seem to exist for CSS. So, I'm wondering if there is some smart solution for this? -- **Edit** I know that strictly speaking, style and link tags are not allowed anywhere but in the head, but I think it's a debatable question. Browsers do not complain about this and why would Google recommend this practice if it was so bad?
Yes, technically you can. But you shouldn't load css in the footer, css links outside of the `<head>` are considered invalid. A better technique would be to add the css-links to the dom with javaScript. You may even want to split out the css so that critical portions are loaded inline (so you avoid a [FOUC](https://en.wikipedia.org/wiki/Flash_of_unstyled_content)) Here's a technique as suggested by [GiftOfSpeed](https://www.giftofspeed.com/defer-loading-css/) ### This JS will create your css-link elements dynamically. ``` <script type="text/javascript"> /* First CSS File */ var wpse326013 = document.createElement('link'); wpse326013.rel = 'stylesheet'; wpse326013.href = '../css/yourcssfile.css'; wpse326013.type = 'text/css'; var godefer = document.getElementsByTagName('link')[0]; godefer.parentNode.insertBefore(wpse326013, godefer); /* Second CSS File */ var wpse326013_2 = document.createElement('link'); wpse326013_2.rel = 'stylesheet'; wpse326013_2.href = '../css/yourcssfile2.css'; wpse326013_2.type = 'text/css'; var godefer2 = document.getElementsByTagName('link')[0]; godefer2.parentNode.insertBefore(wpse326013_2, godefer2); </script> ``` ### & for graceful degradation, we also include the following inside of the head element ``` <noscript> <link rel="stylesheet" type="text/css" href="../css/yourcssfile.css" /> <link rel="stylesheet" type="text/css" href="../css/yourcssfile2.css" /> </noscript> ``` > > You could also wrap the execution of the javaScript in a timeout, the following example would delay execution by 2 seconds. > > > ``` setTimeout(function(){ var wpse326013 = document.createElement('link'); wpse326013.rel = 'stylesheet'; wpse326013.href = '../css/yourcssfile.css'; wpse326013.type = 'text/css'; var godefer = document.getElementsByTagName('link')[0]; godefer.parentNode.insertBefore(wpse326013, godefer); }, 2000); ```
326,055
<p>I'm interested in creating a filter for pages with password protection and that have a certain category. I've placed this code in my theme's child folder in functions.php since I didn't want to edit the wp-includes files.</p> <pre><code>/** * Retrieve v1-i1 protected post password form content. * * @since 1.0.0 * * @param int|WP_Post $post Optional. Post ID or WP_Post object. Default is global $post. * @return string HTML content for password form for password protected post. */ function get_the_v1i1_password_form( $post = 0 ) { $post = get_post( $post ); $label = 'pwbox-' . ( empty($post-&gt;ID) ? rand() : $post-&gt;ID ); $output = '&lt;form action="' . esc_url( site_url( 'wp-login.php?action=postpass', 'login_post' ) ) . '" class="post-password-form" method="post"&gt; &lt;p&gt;' . __( 'This is exclusive content from v1:i1. Please enter password below:' ) . '&lt;/p&gt; &lt;p&gt;&lt;label for="' . $label . '"&gt;' . __( 'Password:' ) . ' &lt;input name="post_password" id="' . $label . '" type="password" size="20" /&gt;&lt;/label&gt; &lt;input type="submit" name="Submit" value="' . esc_attr_x( 'Enter', 'post password form' ) . '" /&gt;&lt;/p&gt;&lt;/form&gt; '; /** * Filters the HTML output for the protected post password form. * * If modifying the password field, please note that the core database schema * limits the password field to 20 characters regardless of the value of the * size attribute in the form input. * * @since 2.7.0 * * @param string $output The password form HTML output. */ return apply_filters( 'the_password_form', $output ); } // If post password required and it doesn't match the cookie. if (post_password_required( $post ) &amp;&amp; in_category( 'v1-i1' )) { return get_the_v1i1_password_form( $post ); } else { return get_the_password_form( $post ); } ` </code></pre> <p>I can't seem to get this to work. Am I missing something?</p>
[ { "answer_id": 326019, "author": "admcfajn", "author_id": 123674, "author_profile": "https://wordpress.stackexchange.com/users/123674", "pm_score": 3, "selected": true, "text": "<p>Yes, technically you can. But you shouldn't load css in the footer, css links outside of the <code>&lt;head...
2019/01/19
[ "https://wordpress.stackexchange.com/questions/326055", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/159342/" ]
I'm interested in creating a filter for pages with password protection and that have a certain category. I've placed this code in my theme's child folder in functions.php since I didn't want to edit the wp-includes files. ``` /** * Retrieve v1-i1 protected post password form content. * * @since 1.0.0 * * @param int|WP_Post $post Optional. Post ID or WP_Post object. Default is global $post. * @return string HTML content for password form for password protected post. */ function get_the_v1i1_password_form( $post = 0 ) { $post = get_post( $post ); $label = 'pwbox-' . ( empty($post->ID) ? rand() : $post->ID ); $output = '<form action="' . esc_url( site_url( 'wp-login.php?action=postpass', 'login_post' ) ) . '" class="post-password-form" method="post"> <p>' . __( 'This is exclusive content from v1:i1. Please enter password below:' ) . '</p> <p><label for="' . $label . '">' . __( 'Password:' ) . ' <input name="post_password" id="' . $label . '" type="password" size="20" /></label> <input type="submit" name="Submit" value="' . esc_attr_x( 'Enter', 'post password form' ) . '" /></p></form> '; /** * Filters the HTML output for the protected post password form. * * If modifying the password field, please note that the core database schema * limits the password field to 20 characters regardless of the value of the * size attribute in the form input. * * @since 2.7.0 * * @param string $output The password form HTML output. */ return apply_filters( 'the_password_form', $output ); } // If post password required and it doesn't match the cookie. if (post_password_required( $post ) && in_category( 'v1-i1' )) { return get_the_v1i1_password_form( $post ); } else { return get_the_password_form( $post ); } ` ``` I can't seem to get this to work. Am I missing something?
Yes, technically you can. But you shouldn't load css in the footer, css links outside of the `<head>` are considered invalid. A better technique would be to add the css-links to the dom with javaScript. You may even want to split out the css so that critical portions are loaded inline (so you avoid a [FOUC](https://en.wikipedia.org/wiki/Flash_of_unstyled_content)) Here's a technique as suggested by [GiftOfSpeed](https://www.giftofspeed.com/defer-loading-css/) ### This JS will create your css-link elements dynamically. ``` <script type="text/javascript"> /* First CSS File */ var wpse326013 = document.createElement('link'); wpse326013.rel = 'stylesheet'; wpse326013.href = '../css/yourcssfile.css'; wpse326013.type = 'text/css'; var godefer = document.getElementsByTagName('link')[0]; godefer.parentNode.insertBefore(wpse326013, godefer); /* Second CSS File */ var wpse326013_2 = document.createElement('link'); wpse326013_2.rel = 'stylesheet'; wpse326013_2.href = '../css/yourcssfile2.css'; wpse326013_2.type = 'text/css'; var godefer2 = document.getElementsByTagName('link')[0]; godefer2.parentNode.insertBefore(wpse326013_2, godefer2); </script> ``` ### & for graceful degradation, we also include the following inside of the head element ``` <noscript> <link rel="stylesheet" type="text/css" href="../css/yourcssfile.css" /> <link rel="stylesheet" type="text/css" href="../css/yourcssfile2.css" /> </noscript> ``` > > You could also wrap the execution of the javaScript in a timeout, the following example would delay execution by 2 seconds. > > > ``` setTimeout(function(){ var wpse326013 = document.createElement('link'); wpse326013.rel = 'stylesheet'; wpse326013.href = '../css/yourcssfile.css'; wpse326013.type = 'text/css'; var godefer = document.getElementsByTagName('link')[0]; godefer.parentNode.insertBefore(wpse326013, godefer); }, 2000); ```
326,066
<p>I did a small adjustment in the 'custom css' in my theme settings, and now I broke my theme. Whenever I select a page as the home page, it says 'Nothing found'. Whenever I visit a page thats not a home page, it works perfectly fine. </p> <p>Been looking for hours now. Any help appreciated. </p> <p>Edit: The change in the CSS I made was temporary putting a piece of CSS within a comment (/* foo */) for testing purposes. </p>
[ { "answer_id": 326019, "author": "admcfajn", "author_id": 123674, "author_profile": "https://wordpress.stackexchange.com/users/123674", "pm_score": 3, "selected": true, "text": "<p>Yes, technically you can. But you shouldn't load css in the footer, css links outside of the <code>&lt;head...
2019/01/19
[ "https://wordpress.stackexchange.com/questions/326066", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/159369/" ]
I did a small adjustment in the 'custom css' in my theme settings, and now I broke my theme. Whenever I select a page as the home page, it says 'Nothing found'. Whenever I visit a page thats not a home page, it works perfectly fine. Been looking for hours now. Any help appreciated. Edit: The change in the CSS I made was temporary putting a piece of CSS within a comment (/\* foo \*/) for testing purposes.
Yes, technically you can. But you shouldn't load css in the footer, css links outside of the `<head>` are considered invalid. A better technique would be to add the css-links to the dom with javaScript. You may even want to split out the css so that critical portions are loaded inline (so you avoid a [FOUC](https://en.wikipedia.org/wiki/Flash_of_unstyled_content)) Here's a technique as suggested by [GiftOfSpeed](https://www.giftofspeed.com/defer-loading-css/) ### This JS will create your css-link elements dynamically. ``` <script type="text/javascript"> /* First CSS File */ var wpse326013 = document.createElement('link'); wpse326013.rel = 'stylesheet'; wpse326013.href = '../css/yourcssfile.css'; wpse326013.type = 'text/css'; var godefer = document.getElementsByTagName('link')[0]; godefer.parentNode.insertBefore(wpse326013, godefer); /* Second CSS File */ var wpse326013_2 = document.createElement('link'); wpse326013_2.rel = 'stylesheet'; wpse326013_2.href = '../css/yourcssfile2.css'; wpse326013_2.type = 'text/css'; var godefer2 = document.getElementsByTagName('link')[0]; godefer2.parentNode.insertBefore(wpse326013_2, godefer2); </script> ``` ### & for graceful degradation, we also include the following inside of the head element ``` <noscript> <link rel="stylesheet" type="text/css" href="../css/yourcssfile.css" /> <link rel="stylesheet" type="text/css" href="../css/yourcssfile2.css" /> </noscript> ``` > > You could also wrap the execution of the javaScript in a timeout, the following example would delay execution by 2 seconds. > > > ``` setTimeout(function(){ var wpse326013 = document.createElement('link'); wpse326013.rel = 'stylesheet'; wpse326013.href = '../css/yourcssfile.css'; wpse326013.type = 'text/css'; var godefer = document.getElementsByTagName('link')[0]; godefer.parentNode.insertBefore(wpse326013, godefer); }, 2000); ```
326,088
<p>Here is a test fiddle: my fiddle: <a href="https://jsfiddle.net/blogob/qtou84Lj/23/" rel="nofollow noreferrer">https://jsfiddle.net/blogob/qtou84Lj/23/</a></p> <p>I'm trying to build a full width map in a wordpress site with leaflet.</p> <p>My goal is to dsplay all post with markers on the map. When i click on the marker, a sidebar appear with the corresponding content in it. It's working.</p> <p>But i have a problem that i can't solve. we can see it in the fiddle, when i move the map, i can see "the content" behind the map. so i have it in the sidebar and also on the page, behind the map. In my wordpress site it's the same : my post contain a title, a video and a description. When i hover the map, in some place i can click on the video that is behind the map and it redirects me to youtube.. so it's a huge problem for me. Is it better to display content via data attributes, i tryed but without success. if i put the content in a data attribute, the map doen't appear in the page. i don't understand why the post are duplicated..</p>
[ { "answer_id": 326019, "author": "admcfajn", "author_id": 123674, "author_profile": "https://wordpress.stackexchange.com/users/123674", "pm_score": 3, "selected": true, "text": "<p>Yes, technically you can. But you shouldn't load css in the footer, css links outside of the <code>&lt;head...
2019/01/19
[ "https://wordpress.stackexchange.com/questions/326088", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/159378/" ]
Here is a test fiddle: my fiddle: <https://jsfiddle.net/blogob/qtou84Lj/23/> I'm trying to build a full width map in a wordpress site with leaflet. My goal is to dsplay all post with markers on the map. When i click on the marker, a sidebar appear with the corresponding content in it. It's working. But i have a problem that i can't solve. we can see it in the fiddle, when i move the map, i can see "the content" behind the map. so i have it in the sidebar and also on the page, behind the map. In my wordpress site it's the same : my post contain a title, a video and a description. When i hover the map, in some place i can click on the video that is behind the map and it redirects me to youtube.. so it's a huge problem for me. Is it better to display content via data attributes, i tryed but without success. if i put the content in a data attribute, the map doen't appear in the page. i don't understand why the post are duplicated..
Yes, technically you can. But you shouldn't load css in the footer, css links outside of the `<head>` are considered invalid. A better technique would be to add the css-links to the dom with javaScript. You may even want to split out the css so that critical portions are loaded inline (so you avoid a [FOUC](https://en.wikipedia.org/wiki/Flash_of_unstyled_content)) Here's a technique as suggested by [GiftOfSpeed](https://www.giftofspeed.com/defer-loading-css/) ### This JS will create your css-link elements dynamically. ``` <script type="text/javascript"> /* First CSS File */ var wpse326013 = document.createElement('link'); wpse326013.rel = 'stylesheet'; wpse326013.href = '../css/yourcssfile.css'; wpse326013.type = 'text/css'; var godefer = document.getElementsByTagName('link')[0]; godefer.parentNode.insertBefore(wpse326013, godefer); /* Second CSS File */ var wpse326013_2 = document.createElement('link'); wpse326013_2.rel = 'stylesheet'; wpse326013_2.href = '../css/yourcssfile2.css'; wpse326013_2.type = 'text/css'; var godefer2 = document.getElementsByTagName('link')[0]; godefer2.parentNode.insertBefore(wpse326013_2, godefer2); </script> ``` ### & for graceful degradation, we also include the following inside of the head element ``` <noscript> <link rel="stylesheet" type="text/css" href="../css/yourcssfile.css" /> <link rel="stylesheet" type="text/css" href="../css/yourcssfile2.css" /> </noscript> ``` > > You could also wrap the execution of the javaScript in a timeout, the following example would delay execution by 2 seconds. > > > ``` setTimeout(function(){ var wpse326013 = document.createElement('link'); wpse326013.rel = 'stylesheet'; wpse326013.href = '../css/yourcssfile.css'; wpse326013.type = 'text/css'; var godefer = document.getElementsByTagName('link')[0]; godefer.parentNode.insertBefore(wpse326013, godefer); }, 2000); ```
326,109
<p>I Need to build an interface with a filter set (a list of checkboxes) that the user can check and click 'filter' to search with in 1 custom post-type for posts with matching terms (there are 3 custom taxonomies with each an unlimited amount of terms).</p> <p><em>How to go about this? I am thinking to code the following:</em></p> <p>I displayed the GUI filterlist like this (x3 because there are 3 taxonomies):</p> <pre><code>&lt;form action="/filter-result" method="get"&gt; &lt;?php $terms = get_terms( array( 'taxonomy' =&gt; 'taxonomy-name', 'hide_empty' =&gt; false, ) ); foreach($terms as $term) { echo '&lt;label&gt;&lt;input type="checkbox" name="taxonomy-name" value="' . $term-&gt;name .'"&gt;' . $term-&gt;name . '&lt;/label&gt;'; } ?&gt; &lt;input type="submit" value="Filter"&gt; &lt;/form&gt; </code></pre> <p>I end up on the <code>/filter-result</code> page with an URL with more than one parameter that all have the same name: <code>filter-result/?taxonomya=term1&amp;taxonomya=term2&amp;taxonomyb=term9</code></p> <p>My plan is to GET all the parameters- I don't know how because there are parameters with the same name- and then build an SQL out of the filtered data.</p>
[ { "answer_id": 326111, "author": "Milo", "author_id": 4771, "author_profile": "https://wordpress.stackexchange.com/users/4771", "pm_score": 1, "selected": false, "text": "<p>Add brackets to the input names:</p>\n\n<pre><code>&lt;label&gt;&lt;input type=\"checkbox\" name=\"taxonomy-name[]...
2019/01/19
[ "https://wordpress.stackexchange.com/questions/326109", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/108754/" ]
I Need to build an interface with a filter set (a list of checkboxes) that the user can check and click 'filter' to search with in 1 custom post-type for posts with matching terms (there are 3 custom taxonomies with each an unlimited amount of terms). *How to go about this? I am thinking to code the following:* I displayed the GUI filterlist like this (x3 because there are 3 taxonomies): ``` <form action="/filter-result" method="get"> <?php $terms = get_terms( array( 'taxonomy' => 'taxonomy-name', 'hide_empty' => false, ) ); foreach($terms as $term) { echo '<label><input type="checkbox" name="taxonomy-name" value="' . $term->name .'">' . $term->name . '</label>'; } ?> <input type="submit" value="Filter"> </form> ``` I end up on the `/filter-result` page with an URL with more than one parameter that all have the same name: `filter-result/?taxonomya=term1&taxonomya=term2&taxonomyb=term9` My plan is to GET all the parameters- I don't know how because there are parameters with the same name- and then build an SQL out of the filtered data.
Add brackets to the input names: ``` <label><input type="checkbox" name="taxonomy-name[]" value="term">term</label> ``` It will be automatically converted to an array: ``` if( isset( $_GET['taxonomy-name'] ) ){ foreach( $_GET['taxonomy-name'] as $term ){ echo $term; } } ```
326,143
<p>I got this code:</p> <pre><code>function ntt_movie_shortcode($atts, $content = null) { return 'TEST'; } add_shortcode('ntt_movie', 'ntt_movie_shortcode'); </code></pre> <p>The shortcode works perfectly on a single page, but on the Home Page / in excerpts the shortcodes are rendered as an empty string. So, the shortcode gets recognized but it seems, that the function doesn't get processed.</p> <p>Any hints or approaches?</p> <p>Thanks in advance.</p>
[ { "answer_id": 326126, "author": "Mohsin Ghouri", "author_id": 159253, "author_profile": "https://wordpress.stackexchange.com/users/159253", "pm_score": 1, "selected": false, "text": "<p>You can test the site back up by creating a staging site or uploading the backup on your localhost to...
2019/01/20
[ "https://wordpress.stackexchange.com/questions/326143", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/33303/" ]
I got this code: ``` function ntt_movie_shortcode($atts, $content = null) { return 'TEST'; } add_shortcode('ntt_movie', 'ntt_movie_shortcode'); ``` The shortcode works perfectly on a single page, but on the Home Page / in excerpts the shortcodes are rendered as an empty string. So, the shortcode gets recognized but it seems, that the function doesn't get processed. Any hints or approaches? Thanks in advance.
You can test the site back up by creating a staging site or uploading the backup on your localhost to verify how much work you have done.
326,172
<p>I have a simple code where I am attaching existing in the library image to a post:</p> <pre><code>function attachToPost($attachmentId, $postId){ return wp_update_post(array( 'ID' =&gt; (int)$attachmentId, 'post_parent' =&gt; (int)$postId )); } </code></pre> <p>The problem is that I can't attach it to a second post. I read in the internet that this is the way that WordPress works, but is there some kind of solution ?</p> <p>I don't prefer plugins.</p>
[ { "answer_id": 326174, "author": "Mohsin Ghouri", "author_id": 159253, "author_profile": "https://wordpress.stackexchange.com/users/159253", "pm_score": 1, "selected": false, "text": "<p>It is not possible to assign multiple parents to the attachment. However, there is an alternative sol...
2019/01/20
[ "https://wordpress.stackexchange.com/questions/326172", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/152132/" ]
I have a simple code where I am attaching existing in the library image to a post: ``` function attachToPost($attachmentId, $postId){ return wp_update_post(array( 'ID' => (int)$attachmentId, 'post_parent' => (int)$postId )); } ``` The problem is that I can't attach it to a second post. I read in the internet that this is the way that WordPress works, but is there some kind of solution ? I don't prefer plugins.
It is not possible to assign multiple parents to the attachment. However, there is an alternative solution. You can use `update_post_meta`. to store the attachment id to the post and similarly, you can use function `get_post_meta`. for getting the attachment id.
326,211
<p>How can I show a post featured image by post id in gutenberg editor? I have a slider with latest posts and when I iterate through over posts I would like to show the post featured image as well. Here is my example snippet</p> <pre><code> const cards = displayPosts.map( ( post, i ) =&gt; { console.log(post.featured_media) return(&lt;div className="card" key={i}&gt; &lt;div className="card-image"&gt; &lt;div className="image is-4by3"&gt; &lt;PostFeaturedImage currentPostId = {post.id} featuredImageId = {post.featured_media} /&gt; &lt;div className="news__post-title"&gt; &lt;div className="title is-5"&gt; &lt;a href={ post.link } target="_blank"&gt;{ decodeEntities( post.title.rendered.trim() ) || __( '(Untitled)' ) }&lt;/a&gt; { displayPostDate &amp;&amp; post.date_gmt &amp;&amp; &lt;time dateTime={ format( 'c', post.date_gmt ) } className="wp-block-latest-posts__post-date"&gt; { dateI18n( dateFormat, post.date_gmt ) } &lt;/time&gt; } &lt;/div&gt; &lt;/div&gt; &lt;div className="card-content"&gt; &lt;div className="content"&gt; &lt;p dangerouslySetInnerHTML={ { __html: post.excerpt.rendered } }&gt;&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt;) }) </code></pre>
[ { "answer_id": 327360, "author": "moped", "author_id": 160324, "author_profile": "https://wordpress.stackexchange.com/users/160324", "pm_score": 0, "selected": false, "text": "<p>I have the same question and tried some ways to get the attachment ID and URL.\nIn fact I got it, but I can't...
2019/01/21
[ "https://wordpress.stackexchange.com/questions/326211", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/23759/" ]
How can I show a post featured image by post id in gutenberg editor? I have a slider with latest posts and when I iterate through over posts I would like to show the post featured image as well. Here is my example snippet ``` const cards = displayPosts.map( ( post, i ) => { console.log(post.featured_media) return(<div className="card" key={i}> <div className="card-image"> <div className="image is-4by3"> <PostFeaturedImage currentPostId = {post.id} featuredImageId = {post.featured_media} /> <div className="news__post-title"> <div className="title is-5"> <a href={ post.link } target="_blank">{ decodeEntities( post.title.rendered.trim() ) || __( '(Untitled)' ) }</a> { displayPostDate && post.date_gmt && <time dateTime={ format( 'c', post.date_gmt ) } className="wp-block-latest-posts__post-date"> { dateI18n( dateFormat, post.date_gmt ) } </time> } </div> </div> <div className="card-content"> <div className="content"> <p dangerouslySetInnerHTML={ { __html: post.excerpt.rendered } }></p> </div> </div> </div> </div> </div>) }) ```
A simple and effective approach ``` const editor = wp.data.select('core/editor'); const imageId = editor.getEditedPostAttribute('featured_media'); const imageObj = wp.data.select('core').getMedia(imageId); ``` ImageObj gives you a reasonable amount of image data to work with.
326,269
<pre><code>&lt;ul class="nav navbar-nav" id="hover_slip"&gt; &lt;li&gt;&lt;a href="index.html"&gt;Home&lt;/a&gt;&lt;/li&gt; &lt;li class="arrow_down"&gt;&lt;a href="about.html"&gt;About Us&lt;/a&gt; &lt;div class="sub-menu"&gt; &lt;ul&gt; &lt;li&gt;&lt;a href="advisor.html"&gt;Advisor&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="single-advisor.html"&gt;Single Advisor&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="career.html"&gt;Career&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="testimonial.html"&gt;Testimonaials&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="partners.html"&gt;partners&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;/li&gt; &lt;li class="arrow_down"&gt;&lt;a href="service.html"&gt;Services&lt;/a&gt; &lt;div class="sub-menu"&gt; &lt;ul&gt; &lt;li&gt;&lt;a href="service2.html"&gt;Service Two&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="pricing-page.html"&gt;Pricing Page&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;/li&gt; </code></pre> <p></p>
[ { "answer_id": 327360, "author": "moped", "author_id": 160324, "author_profile": "https://wordpress.stackexchange.com/users/160324", "pm_score": 0, "selected": false, "text": "<p>I have the same question and tried some ways to get the attachment ID and URL.\nIn fact I got it, but I can't...
2019/01/21
[ "https://wordpress.stackexchange.com/questions/326269", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/159534/" ]
``` <ul class="nav navbar-nav" id="hover_slip"> <li><a href="index.html">Home</a></li> <li class="arrow_down"><a href="about.html">About Us</a> <div class="sub-menu"> <ul> <li><a href="advisor.html">Advisor</a></li> <li><a href="single-advisor.html">Single Advisor</a></li> <li><a href="career.html">Career</a></li> <li><a href="testimonial.html">Testimonaials</a></li> <li><a href="partners.html">partners</a></li> </ul> </div> </li> <li class="arrow_down"><a href="service.html">Services</a> <div class="sub-menu"> <ul> <li><a href="service2.html">Service Two</a></li> <li><a href="pricing-page.html">Pricing Page</a></li> </ul> </div> </li> ```
A simple and effective approach ``` const editor = wp.data.select('core/editor'); const imageId = editor.getEditedPostAttribute('featured_media'); const imageObj = wp.data.select('core').getMedia(imageId); ``` ImageObj gives you a reasonable amount of image data to work with.
326,276
<p>Many times I have code and I want to make sure it only runs in a rest api context, or it never runs in a rest context.</p> <p>I know there are some hooks, but is there a function similar to <code>wp_is_doing_cron</code>?</p>
[ { "answer_id": 326277, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 0, "selected": false, "text": "<p>Yes, <code>wp_is_json_request()</code> can be used to determine if the current request is a REST API request...
2019/01/21
[ "https://wordpress.stackexchange.com/questions/326276", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/736/" ]
Many times I have code and I want to make sure it only runs in a rest api context, or it never runs in a rest context. I know there are some hooks, but is there a function similar to `wp_is_doing_cron`?
I would use : ``` if ( defined( 'REST_REQUEST' ) && REST_REQUEST ) {...} ``` Source: <https://github.com/WP-API/WP-API/issues/926#issuecomment-162920686> If you take a look to [this source code](https://github.com/WordPress/WordPress/blob/5f62cd1566d27be22d961c2a9af31f077efdecf7/wp-includes/rest-api.php#L329) on you will notice the constant is defined before processing anything, I would check for it instead of calling the mentioned function `wp_is_json_request()` Why? if headers were not set when you do the check, it will return false, here is a real example reported for a GET request: <https://github.com/WordPress/gutenberg/issues/11327>
326,335
<p>I'm trying to figure out a way, to create a Gutenberg sidebar that is only visible on a custom post type.</p> <p>For instance, I'd like my sidebar with settings, like a custom checkbox, only related to pages, to be inaccessible on my custom post types.</p> <p>Instead of creating a sidebar for a specific post type, it would also be great to remove a sidebar from a specific post type.</p> <p>I couldn't yet find any way to accomplish that, any ideas?</p>
[ { "answer_id": 336444, "author": "Ahrengot", "author_id": 23829, "author_profile": "https://wordpress.stackexchange.com/users/23829", "pm_score": 4, "selected": true, "text": "<p>I know this question is a few months old by now, but I got around this issue using the following code and tho...
2019/01/22
[ "https://wordpress.stackexchange.com/questions/326335", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/151781/" ]
I'm trying to figure out a way, to create a Gutenberg sidebar that is only visible on a custom post type. For instance, I'd like my sidebar with settings, like a custom checkbox, only related to pages, to be inaccessible on my custom post types. Instead of creating a sidebar for a specific post type, it would also be great to remove a sidebar from a specific post type. I couldn't yet find any way to accomplish that, any ideas?
I know this question is a few months old by now, but I got around this issue using the following code and thought it might be helpful for others. There might be a better way, but this works: ``` import ColorSchemeSelect from "./components/color-scheme-select"; import includes from "lodash/includes"; const { select } = wp.data; const { registerPlugin } = wp.plugins; const { PluginSidebar } = wp.editPost; registerPlugin('ahr-sidebar-post-options', { render() { const postType = select("core/editor").getCurrentPostType(); if ( !includes(["post", "page"], postType) ) { return null; } return ( <PluginSidebar name="ahr-sidebar-post-options" icon="admin-customizer" title="Color settings"> <div style={{ padding: 16 }}> <ColorSchemeSelect /> </div> </PluginSidebar> ); }, }); ``` In my example I only wanted to show a certain sidebar for posts and pages, so I'm using `!includes(["post", "page"], postType)` to test wheter or not the sidebar should be shown. If you only want it for one specific post type you'd just go `postType === "my-post-type"` instead.
326,345
<p>I just have installed xampp with php 7.3.1 on mac with OS El capitan. </p> <p>The problem that when i run a WordPress project will show:</p> <blockquote> <p>Warning: preg_replace(): JIT compilation failed: no more memory in /Applications/XAMPP/xamppfiles/htdocs/wordpress/wp-includes/formatting.php on line 2110 Warning: preg_match(): JIT compilation failed: no more memory in /Applications/XAMPP/xamppfiles/htdocs/wordpress/wp-includes/functions.php on line 4947 Warning: preg_replace(): JIT compilation failed: no more memory in /Applications/XAMPP/xamppfiles/htdocs/wordpress/wp-includes/functions.php on line 4843 Warning: preg_match(): JIT compilation failed: no more memory in /Applications/XAMPP/xamppfiles/htdocs/wordpress/wp-includes/functions.php on line 4947 Warning: preg_match(): JIT compilation failed: no more memory in /Applications/XAMPP/xamppfiles/htdocs/wordpress/wp-includes/functions.php on line 4947</p> </blockquote>
[ { "answer_id": 327568, "author": "Michael Parkinson", "author_id": 145000, "author_profile": "https://wordpress.stackexchange.com/users/145000", "pm_score": 3, "selected": false, "text": "<p>I added the following line to the <code>php.ini</code> and restarted Apache and it worked (Xampp ...
2019/01/22
[ "https://wordpress.stackexchange.com/questions/326345", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/158614/" ]
I just have installed xampp with php 7.3.1 on mac with OS El capitan. The problem that when i run a WordPress project will show: > > Warning: preg\_replace(): JIT compilation failed: no more memory in > /Applications/XAMPP/xamppfiles/htdocs/wordpress/wp-includes/formatting.php > on line 2110 Warning: preg\_match(): JIT compilation failed: no more > memory in > /Applications/XAMPP/xamppfiles/htdocs/wordpress/wp-includes/functions.php > on line 4947 Warning: preg\_replace(): JIT compilation failed: no more > memory in > /Applications/XAMPP/xamppfiles/htdocs/wordpress/wp-includes/functions.php > on line 4843 Warning: preg\_match(): JIT compilation failed: no more > memory in > /Applications/XAMPP/xamppfiles/htdocs/wordpress/wp-includes/functions.php > on line 4947 Warning: preg\_match(): JIT compilation failed: no more > memory in > /Applications/XAMPP/xamppfiles/htdocs/wordpress/wp-includes/functions.php > on line 4947 > > >
I added the following line to the `php.ini` and restarted Apache and it worked (Xampp on macOS): ``` pcre.jit=0 ``` This disables PCRE's just-in-time compilation. Further information: * <http://php.net/manual/en/pcre.configuration.php#ini.pcre.jit> If you can't find the location of `php.ini` and are using Xampp, go to localhost and select the PHP information link and it is displayed there.
326,375
<p>My website:<a href="http://up8.431.myftpupload.com/" rel="nofollow noreferrer">http://up8.431.myftpupload.com/</a></p> <p>I recently changed the words under We Serve under the main image to links. After I did that, when I hovered over them they changed to the background color that they are in. I would like them to change to blue when I hover over them.</p> <p>In the scrrenshot I have up the styling of the links but am hovered over the title, which happens to be an H2 tag. I used some custom css to get them to change to blue when I hover over them . Problem is, the whole page gets that same styling applied and it makes no sense to me. I put the custom css specifically just for that section of text. </p> <p>Feel free to go to the page as well and see how everything on the page gets the same :hover effect applied. I suspect it's because I used just :hover with nothing before it so therefore it get's applied to everything.</p> <p>Other things I've tried: 1. Using this:hover - did nothing 2. Using a:hover - made all links on the page have same hover effect 3. Giving that section of text a CSSID and class and applying styling thru the customizer Custom CSS/JS - did nothing... didn't even work</p> <p><a href="https://i.stack.imgur.com/rGsBx.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/rGsBx.png" alt="enter image description here"></a></p> <p>Any help would be appreciated. I think I understand what's going on. I just don't know how to fix it. Thx in advance </p>
[ { "answer_id": 326379, "author": "RiddleMeThis", "author_id": 86845, "author_profile": "https://wordpress.stackexchange.com/users/86845", "pm_score": -1, "selected": true, "text": "<p>Replace the style you added with the following.</p>\n\n<pre><code>.elementor-element-1fc9820 a:hover {\n...
2019/01/22
[ "https://wordpress.stackexchange.com/questions/326375", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/159272/" ]
My website:<http://up8.431.myftpupload.com/> I recently changed the words under We Serve under the main image to links. After I did that, when I hovered over them they changed to the background color that they are in. I would like them to change to blue when I hover over them. In the scrrenshot I have up the styling of the links but am hovered over the title, which happens to be an H2 tag. I used some custom css to get them to change to blue when I hover over them . Problem is, the whole page gets that same styling applied and it makes no sense to me. I put the custom css specifically just for that section of text. Feel free to go to the page as well and see how everything on the page gets the same :hover effect applied. I suspect it's because I used just :hover with nothing before it so therefore it get's applied to everything. Other things I've tried: 1. Using this:hover - did nothing 2. Using a:hover - made all links on the page have same hover effect 3. Giving that section of text a CSSID and class and applying styling thru the customizer Custom CSS/JS - did nothing... didn't even work [![enter image description here](https://i.stack.imgur.com/rGsBx.png)](https://i.stack.imgur.com/rGsBx.png) Any help would be appreciated. I think I understand what's going on. I just don't know how to fix it. Thx in advance
Replace the style you added with the following. ``` .elementor-element-1fc9820 a:hover { color:blue !important; } ``` You needed to be more specific with your rule. Since there is a elementor class around those links I just used that class. Note: Your #3 solution should have worked so apparently you made a mistake when you attempted it.
326,387
<p>Basically what I'm asking is, is <code>wp_ajax_nopriv</code> exclusive to non-logged-in users?</p> <p>Will a <code>wp_ajax_nopriv</code> action fire if a user is logged in?</p>
[ { "answer_id": 326389, "author": "Pat J", "author_id": 16121, "author_profile": "https://wordpress.stackexchange.com/users/16121", "pm_score": 4, "selected": true, "text": "<p>Looking at <a href=\"https://core.trac.wordpress.org/browser/tags/5.0.3/src/wp-admin/admin-ajax.php#L114\" rel=\...
2019/01/22
[ "https://wordpress.stackexchange.com/questions/326387", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/22588/" ]
Basically what I'm asking is, is `wp_ajax_nopriv` exclusive to non-logged-in users? Will a `wp_ajax_nopriv` action fire if a user is logged in?
Looking at [the WordPress source code](https://core.trac.wordpress.org/browser/tags/5.0.3/src/wp-admin/admin-ajax.php#L114), I'd say that `wp_ajax_nopriv_*` fires *only* if you're not logged in, and `wp_ajax_*` fires otherwise. Here's the relevant bit, in `admin-ajax.php`, lines 85-115 in version 5.0.3: ``` if ( is_user_logged_in() ) { // If no action is registered, return a Bad Request response. if ( ! has_action( 'wp_ajax_' . $_REQUEST['action'] ) ) { wp_die( '0', 400 ); } /** * Fires authenticated Ajax actions for logged-in users. * * The dynamic portion of the hook name, `$_REQUEST['action']`, * refers to the name of the Ajax action callback being fired. * * @since 2.1.0 */ do_action( 'wp_ajax_' . $_REQUEST['action'] ); } else { // If no action is registered, return a Bad Request response. if ( ! has_action( 'wp_ajax_nopriv_' . $_REQUEST['action'] ) ) { wp_die( '0', 400 ); } /** * Fires non-authenticated Ajax actions for logged-out users. * * The dynamic portion of the hook name, `$_REQUEST['action']`, * refers to the name of the Ajax action callback being fired. * * @since 2.8.0 */ do_action( 'wp_ajax_nopriv_' . $_REQUEST['action'] ); } ``` So, if you're logged in (ie, `is_user_logged_in()` is `true`), it runs the `wp_ajax_*` action(s), otherwise it runs the `wp_ajax_nopriv_*` actions. If you want the same action run regardless whether your user is logged in or not, I'd recommend you hook to **both** `wp_ajax_*` and `wp_ajax_nopriv_*`.
326,399
<p>I am working with the onClick action on a custom IconButton like so:</p> <pre><code>const { createHigherOrderComponent } = wp.compose; const { Fragment } = wp.element; const { BlockControls } = wp.editor; const { Toolbar } = wp.components; const { IconButton } = wp.components; const withCollapseControl = createHigherOrderComponent( ( BlockEdit ) =&gt; { return ( props ) =&gt; { props.toggleBlockCollapse = (event) =&gt; { props.setAttributes({ collapsed:!props.attributes.collapsed, } let iconProps = { onClick: props.toggleBlockCollapse.bind(props), class: "components-icon-button components-toolbar__control", label: props.attributes.collapsed ? 'Collapse' : 'Expand', icon: props.attributes.collapsed ? 'arrow-down' : 'arrow-up' } return ( &lt;Fragment&gt; &lt;BlockEdit { ...props } className='collapsed'/&gt; &lt;BlockControls&gt; &lt;Toolbar&gt; &lt;IconButton { ...iconProps } /&gt; &lt;/Toolbar&gt; &lt;/BlockControls&gt; &lt;/Fragment&gt; ); }; }, "withCollapseControl" ); wp.hooks.addFilter( 'editor.BlockEdit', 'my-plugin/with-inspector-controls', withCollapseControl ); </code></pre> <p>I seem to be unable to add/ remove an HTML/ CSS class to the BlockEdit component. I am able to toggle the icon button, and my call to setAttributes triggers re-render...</p> <p>I was hoping I could mimic the example in the accepted answer here, but on my BlockEdit component: <a href="https://wordpress.stackexchange.com/questions/324091/add-classname-to-gutenberg-block-wrapper-in-the-editor">Add classname to Gutenberg block wrapper in the editor?</a></p> <p>After taking a deeper look, it appears that className may not be overrideable on the BlockEdit component the way it is on the BlockListBlock component.</p> <p>Perhaps the best approach would be to try to modify the class of the BlockListBlock component, but I am not certain how I would go about linking those together, so possibly looking for a solution in that vein.</p> <p>Thanks!</p> <p>Edit: Please note I have hardcoded in a value for the className in the example BlockEdit component, to demonstrate where things fail ( adding classname ) independent of the other logic in the code. The entirety of the code is shared to help provide answerers with some broader context and my intent :)</p>
[ { "answer_id": 326465, "author": "criticalWP", "author_id": 159617, "author_profile": "https://wordpress.stackexchange.com/users/159617", "pm_score": 2, "selected": false, "text": "<p>I was able to solve this by wrapping the BlockEdit component in my own markup:</p>\n\n<pre><code> &lt...
2019/01/23
[ "https://wordpress.stackexchange.com/questions/326399", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/159617/" ]
I am working with the onClick action on a custom IconButton like so: ``` const { createHigherOrderComponent } = wp.compose; const { Fragment } = wp.element; const { BlockControls } = wp.editor; const { Toolbar } = wp.components; const { IconButton } = wp.components; const withCollapseControl = createHigherOrderComponent( ( BlockEdit ) => { return ( props ) => { props.toggleBlockCollapse = (event) => { props.setAttributes({ collapsed:!props.attributes.collapsed, } let iconProps = { onClick: props.toggleBlockCollapse.bind(props), class: "components-icon-button components-toolbar__control", label: props.attributes.collapsed ? 'Collapse' : 'Expand', icon: props.attributes.collapsed ? 'arrow-down' : 'arrow-up' } return ( <Fragment> <BlockEdit { ...props } className='collapsed'/> <BlockControls> <Toolbar> <IconButton { ...iconProps } /> </Toolbar> </BlockControls> </Fragment> ); }; }, "withCollapseControl" ); wp.hooks.addFilter( 'editor.BlockEdit', 'my-plugin/with-inspector-controls', withCollapseControl ); ``` I seem to be unable to add/ remove an HTML/ CSS class to the BlockEdit component. I am able to toggle the icon button, and my call to setAttributes triggers re-render... I was hoping I could mimic the example in the accepted answer here, but on my BlockEdit component: [Add classname to Gutenberg block wrapper in the editor?](https://wordpress.stackexchange.com/questions/324091/add-classname-to-gutenberg-block-wrapper-in-the-editor) After taking a deeper look, it appears that className may not be overrideable on the BlockEdit component the way it is on the BlockListBlock component. Perhaps the best approach would be to try to modify the class of the BlockListBlock component, but I am not certain how I would go about linking those together, so possibly looking for a solution in that vein. Thanks! Edit: Please note I have hardcoded in a value for the className in the example BlockEdit component, to demonstrate where things fail ( adding classname ) independent of the other logic in the code. The entirety of the code is shared to help provide answerers with some broader context and my intent :)
I was able to solve this by wrapping the BlockEdit component in my own markup: ``` <Fragment> <div className="customClass"> <BlockEdit { ...props }/> <div> <BlockControls> <Toolbar> <IconButton { ...iconProps } /> </Toolbar> </BlockControls> </Fragment> ```
326,417
<p>On a virtual private server machine (Ubuntu 16.04) which I self-host on DigitalOcean I use an all-default and latest <em>Debian</em> stable with all-default and latest <em>Apache</em>, <em>MySQL</em> and <em>PHP</em> to host my WordPress websites.</p> <p>Port 25 is unfiltered.</p> <p>None of the WordPresses is on debug mode.</p> <p>Each Wordpress website contains one simple contact form (CF7) with <em>name</em>, <em>email</em>, <em>phone</em> and <em>body</em> fields. All latest.</p> <h2>My problem</h2> <p>I declared my personal email account for all websites contact-form <strong>plugin</strong> and ought to test the forms but in testing them with some input and clicking <em>submit</em> I got this general error:</p> <blockquote> <p>Failed to send your message</p> </blockquote> <p>I didn't manage to find further data as to why I had this error - any log I checked showed nothing on this.</p> <p>Reading on this I concluded I need an <strong>email proxy</strong> by a <strong>second email account</strong>, but this approach requires me to manage another email account with username and password which I don't want if I don't have to.</p> <h2>My need</h2> <p>I desire to transfer all contact-form inputs <em>from my machine → into my personal email account</em>, but without using an email-proxy like a third email account that will mediate between each CMS and my personal email account.</p> <p>How can I transfer contact-form inputs into my personal email account <strong>without using an email-proxy</strong>, in the above stack?</p>
[ { "answer_id": 326465, "author": "criticalWP", "author_id": 159617, "author_profile": "https://wordpress.stackexchange.com/users/159617", "pm_score": 2, "selected": false, "text": "<p>I was able to solve this by wrapping the BlockEdit component in my own markup:</p>\n\n<pre><code> &lt...
2019/01/23
[ "https://wordpress.stackexchange.com/questions/326417", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/-1/" ]
On a virtual private server machine (Ubuntu 16.04) which I self-host on DigitalOcean I use an all-default and latest *Debian* stable with all-default and latest *Apache*, *MySQL* and *PHP* to host my WordPress websites. Port 25 is unfiltered. None of the WordPresses is on debug mode. Each Wordpress website contains one simple contact form (CF7) with *name*, *email*, *phone* and *body* fields. All latest. My problem ---------- I declared my personal email account for all websites contact-form **plugin** and ought to test the forms but in testing them with some input and clicking *submit* I got this general error: > > Failed to send your message > > > I didn't manage to find further data as to why I had this error - any log I checked showed nothing on this. Reading on this I concluded I need an **email proxy** by a **second email account**, but this approach requires me to manage another email account with username and password which I don't want if I don't have to. My need ------- I desire to transfer all contact-form inputs *from my machine → into my personal email account*, but without using an email-proxy like a third email account that will mediate between each CMS and my personal email account. How can I transfer contact-form inputs into my personal email account **without using an email-proxy**, in the above stack?
I was able to solve this by wrapping the BlockEdit component in my own markup: ``` <Fragment> <div className="customClass"> <BlockEdit { ...props }/> <div> <BlockControls> <Toolbar> <IconButton { ...iconProps } /> </Toolbar> </BlockControls> </Fragment> ```
326,461
<p>I am creating a plugin with custom gutenberg blocks.</p> <p>Each block has a styles.scss file. If I add code to this file, the block is styled in both the back end and front end, as expected per the docs.</p> <p>For example, in a block "section" I want to style the background color only on the back end:</p> <pre><code>.wp-block-pbdsblocks-section { background-color: #e0e0e0; padding: 10px; } </code></pre> <p>But this affects both front and back end. The articles I've been reading say to apply the style by creating an "editor.scss" file in the block directory.</p> <p>I import the editor.scss file into the block's index.js.</p> <p>I can see my code in this file being compiled and added to <code>/assets/css/blocks.style.css</code></p> <p>I have the plugins' php file set to enqueue it:</p> <pre><code>/** * Enqueue block editor only JavaScript and CSS */ function pbdsblocks_editor_scripts() { // Make paths variables so we don't write em twice ;) $blockPath = '/assets/js/editor.blocks.js'; $editorStylePath = '/assets/css/blocks.editor.css'; // Enqueue the bundled block JS file wp_enqueue_script( 'pbdsblocks-blocks-js', plugins_url( $blockPath, __FILE__ ), [ 'wp-i18n', 'wp-element', 'wp-blocks', 'wp-components', 'wp-api', 'wp-editor' ], filemtime( plugin_dir_path(__FILE__) . $blockPath ) ); // Enqueue optional editor only styles wp_enqueue_style( 'pbdsblocks-blocks-editor-css', plugins_url( $editorStylePath, __FILE__), [ 'wp-blocks' ], filemtime( plugin_dir_path( __FILE__ ) . $editorStylePath ) ); } // Hook scripts function into block editor hook add_action( 'enqueue_block_editor_assets', 'pbdsblocks_editor_scripts' ); </code></pre> <p>But the styles only take affect if they're in the <code>style.scss</code> file. Which affects front end and back end.</p>
[ { "answer_id": 326477, "author": "Steve", "author_id": 23610, "author_profile": "https://wordpress.stackexchange.com/users/23610", "pm_score": 1, "selected": false, "text": "<p>FWIW, there was an error in the <code>wp_enqueue_style</code> function I received. This one works fine:</p>\n\...
2019/01/23
[ "https://wordpress.stackexchange.com/questions/326461", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/23610/" ]
I am creating a plugin with custom gutenberg blocks. Each block has a styles.scss file. If I add code to this file, the block is styled in both the back end and front end, as expected per the docs. For example, in a block "section" I want to style the background color only on the back end: ``` .wp-block-pbdsblocks-section { background-color: #e0e0e0; padding: 10px; } ``` But this affects both front and back end. The articles I've been reading say to apply the style by creating an "editor.scss" file in the block directory. I import the editor.scss file into the block's index.js. I can see my code in this file being compiled and added to `/assets/css/blocks.style.css` I have the plugins' php file set to enqueue it: ``` /** * Enqueue block editor only JavaScript and CSS */ function pbdsblocks_editor_scripts() { // Make paths variables so we don't write em twice ;) $blockPath = '/assets/js/editor.blocks.js'; $editorStylePath = '/assets/css/blocks.editor.css'; // Enqueue the bundled block JS file wp_enqueue_script( 'pbdsblocks-blocks-js', plugins_url( $blockPath, __FILE__ ), [ 'wp-i18n', 'wp-element', 'wp-blocks', 'wp-components', 'wp-api', 'wp-editor' ], filemtime( plugin_dir_path(__FILE__) . $blockPath ) ); // Enqueue optional editor only styles wp_enqueue_style( 'pbdsblocks-blocks-editor-css', plugins_url( $editorStylePath, __FILE__), [ 'wp-blocks' ], filemtime( plugin_dir_path( __FILE__ ) . $editorStylePath ) ); } // Hook scripts function into block editor hook add_action( 'enqueue_block_editor_assets', 'pbdsblocks_editor_scripts' ); ``` But the styles only take affect if they're in the `style.scss` file. Which affects front end and back end.
FWIW, there was an error in the `wp_enqueue_style` function I received. This one works fine: ``` // Enqueue optional editor only styles wp_enqueue_style( 'pbdsblocks-blocks-editor-css', plugins_url( $editorStylePath, __FILE__), [ ], filemtime( plugin_dir_path( __FILE__ ) . $editorStylePath ) ); ``` Note the third argument has changed to `[ ]` from `['wp-blocks']`
326,462
<p>Is it possible to limit the categories so that user in a list of groups does not see these posts at all? Not even in a list of posts?</p> <p>I'm using the answer from here:</p> <p><a href="https://wordpress.stackexchange.com/questions/113500/only-show-category-to-certain-user-levels-without-plugin">Only show category to certain user levels without plugin</a></p> <p>My Code:</p> <pre><code>########### // restrikcija posameznih kategorij za grupo ki je subscriber // source: https://wordpress.stackexchange.com/questions/113500/only-show-category-to-certain-user-levels-without-plugin add_filter('template_include', 'restict_by_category'); function check_user() { $user = wp_get_current_user(); $restricted_groups = array( 'company1', 'company2', 'company3', 'subscriber' ); // categories subscribers cannot see if ( ! $user-&gt;ID || array_intersect( $restricted_groups, $user-&gt;roles ) ) { // user is not logged or is a subscriber return false; } return true; } function restict_by_category( $template ) { if ( ! is_main_query() ) { return $template; // only affect main query. } $allow = true; $private_categories = array( 'podjetje', 'personal', 'nekategorizirano', 'razno', 'sola-2' ); // categories subscribers cannot see if ( is_single() ) { $cats = wp_get_object_terms( get_queried_object()-&gt;ID, 'category', array('fields' =&gt; 'slugs') ); // get the categories associated to the required post if ( array_intersect( $private_categories, $cats ) ) { // post has a reserved category, let's check user $allow = check_user(); } } elseif ( is_tax('category', $private_categories) ) { // the archive for one of private categories is required, let's check user $allow = check_user(); } // if allowed include the required template, otherwise include the 'not-allowed' one return $allow ? $template : get_home_url(); //get_template_directory() . '/not-allowed.php'; } ########### </code></pre> <p>The problem is that user still sees post in a list of posts, but when clicked upon it's content is empty (which is OK, but even better would be that it doesnt sees posts at all).</p> <p>And also if I have a master category with lots of sub-categorys, is it possible to also limit all these child categories?</p>
[ { "answer_id": 326477, "author": "Steve", "author_id": 23610, "author_profile": "https://wordpress.stackexchange.com/users/23610", "pm_score": 1, "selected": false, "text": "<p>FWIW, there was an error in the <code>wp_enqueue_style</code> function I received. This one works fine:</p>\n\...
2019/01/23
[ "https://wordpress.stackexchange.com/questions/326462", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/159653/" ]
Is it possible to limit the categories so that user in a list of groups does not see these posts at all? Not even in a list of posts? I'm using the answer from here: [Only show category to certain user levels without plugin](https://wordpress.stackexchange.com/questions/113500/only-show-category-to-certain-user-levels-without-plugin) My Code: ``` ########### // restrikcija posameznih kategorij za grupo ki je subscriber // source: https://wordpress.stackexchange.com/questions/113500/only-show-category-to-certain-user-levels-without-plugin add_filter('template_include', 'restict_by_category'); function check_user() { $user = wp_get_current_user(); $restricted_groups = array( 'company1', 'company2', 'company3', 'subscriber' ); // categories subscribers cannot see if ( ! $user->ID || array_intersect( $restricted_groups, $user->roles ) ) { // user is not logged or is a subscriber return false; } return true; } function restict_by_category( $template ) { if ( ! is_main_query() ) { return $template; // only affect main query. } $allow = true; $private_categories = array( 'podjetje', 'personal', 'nekategorizirano', 'razno', 'sola-2' ); // categories subscribers cannot see if ( is_single() ) { $cats = wp_get_object_terms( get_queried_object()->ID, 'category', array('fields' => 'slugs') ); // get the categories associated to the required post if ( array_intersect( $private_categories, $cats ) ) { // post has a reserved category, let's check user $allow = check_user(); } } elseif ( is_tax('category', $private_categories) ) { // the archive for one of private categories is required, let's check user $allow = check_user(); } // if allowed include the required template, otherwise include the 'not-allowed' one return $allow ? $template : get_home_url(); //get_template_directory() . '/not-allowed.php'; } ########### ``` The problem is that user still sees post in a list of posts, but when clicked upon it's content is empty (which is OK, but even better would be that it doesnt sees posts at all). And also if I have a master category with lots of sub-categorys, is it possible to also limit all these child categories?
FWIW, there was an error in the `wp_enqueue_style` function I received. This one works fine: ``` // Enqueue optional editor only styles wp_enqueue_style( 'pbdsblocks-blocks-editor-css', plugins_url( $editorStylePath, __FILE__), [ ], filemtime( plugin_dir_path( __FILE__ ) . $editorStylePath ) ); ``` Note the third argument has changed to `[ ]` from `['wp-blocks']`
326,497
<p>I have a custom post-type 'News' which has multiple custom taxonomies 'news-category', 'news-tags'. Each post contains between 4-8 'news-tags' and 1 'news-category'.</p> <p>For my current post, I'd like to display related posts based on common 'news-tags' terms added to my current post, while also matching the 'news-category' term. </p> <p>So, I'd like the related posts to look for posts of the same 'news-category' with the most number of 'news-tags' terms in common and display them in descending order.</p> <p>If I were to display 4 related posts:</p> <ul> <li>the first post might have 5 'news-tags' terms in common,</li> <li>the second post might have 3 'news-tags' terms in common,</li> <li>the third post might have 2 'news-tags' terms in common,</li> <li>and the last post might have 'news-tags' 1 term in common.</li> </ul> <p>and they'd all belong to the same 'news-category'.</p> <p>Would it be possible to do this? I've really been struggling with this so I'll appreciate any help.</p>
[ { "answer_id": 326648, "author": "Bram", "author_id": 60517, "author_profile": "https://wordpress.stackexchange.com/users/60517", "pm_score": 4, "selected": true, "text": "<p>Let's split the problem up in three bits: retrieving the related posts from the database, sorting them and displa...
2019/01/24
[ "https://wordpress.stackexchange.com/questions/326497", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/159719/" ]
I have a custom post-type 'News' which has multiple custom taxonomies 'news-category', 'news-tags'. Each post contains between 4-8 'news-tags' and 1 'news-category'. For my current post, I'd like to display related posts based on common 'news-tags' terms added to my current post, while also matching the 'news-category' term. So, I'd like the related posts to look for posts of the same 'news-category' with the most number of 'news-tags' terms in common and display them in descending order. If I were to display 4 related posts: * the first post might have 5 'news-tags' terms in common, * the second post might have 3 'news-tags' terms in common, * the third post might have 2 'news-tags' terms in common, * and the last post might have 'news-tags' 1 term in common. and they'd all belong to the same 'news-category'. Would it be possible to do this? I've really been struggling with this so I'll appreciate any help.
Let's split the problem up in three bits: retrieving the related posts from the database, sorting them and displaying the result. Post retrieval -------------- This is possible using the [taxonomy parameters](https://codex.wordpress.org/Class_Reference/WP_Query#Taxonomy_Parameters) offered in `WP_Query`. Let's first retrieve the category of the current post and find their IDs: ``` $categories = get_the_terms( get_the_ID(), 'news-category' ); foreach ( $categories as $category ) { $category_ids[] = $category->term_id; } ``` We do the same for the tags: ``` $tags = get_the_terms( get_the_ID(), 'news-tags' ); foreach ( $tags as $tag) { $tag_ids[] = $tag->term_id; } ``` Then, we build a set of query arguments (we later feed to a `WP_Query`-call): ``` $related_args = array( 'post_type' => array( 'news', ), 'post_status' => 'publish', 'posts_per_page' => -1, // Get all posts 'post__not_in' => array( get_the_ID() ), // Hide current post in list of related content 'tax_query' => array( 'relation' => 'AND', // Make sure to mach both category and term array( 'taxonomy' => 'news-category', 'field' => 'term_id', 'terms' => $category_ids, ), array( 'taxonomy' => 'news-tags', 'field' => 'term_id', 'terms' => $tag_ids, ), ), ); ``` Finally, we run the query that gives us an array of ``` $related_all = new WP_Query( $related_args ); ``` Please note this query retrieves all posts that match the 'filter', as we're doing the ordering later on. If we'd now only query 4 posts, those might not be the most relevant. *Sidenote: the above query is quite heavy, in the sense that it (potentially) retrieves a large number of posts. When I've created a related posts section for a client project (also a news section), I ordered by date rather than relevance. That allows you to set a limit to the number of posts you retrieve from the database (change the `-1` to `4` in your case, and add `'orderby' => array( 'date' => 'DESC' )` to the `$related_args`-array). If you want to stick with ordering on the overlap, I suggest you add a date filter in the query arguments, or limit the number of results to some finite value, from which set you then retrieve the most relevant posts.* Post ordering ------------- Following the previous step, `$related_all` is a `WP_Query`-object. We access the actual posts as follows, and store them in `$related_all_posts`: ``` $related_all_posts = $related_all->posts; ``` That gives us an array we can more easily work with. We then loop through all the results in that array. Per the comments in the code, when looping through the results, we find the tags associated to the (related) post, find their IDs, compare that with the `$tag_ids` (of the main post) found earlier and see how much overlap there is using [`array_intersect()`](https://secure.php.net/manual/en/function.array-intersect.php): ``` foreach($related_all_posts as $related_post){ // Find all tags of the related post under consideration $related_post_tags = get_the_terms( $related_post->ID, 'news-tags' ); foreach ( $related_post_tags as $related_post_tag ) { $related_tag_ids[] = $related_post_tag->term_id; // Save their IDs in a query } // Find overlap with tags of main post (in $tag_ids) using array_intersect, and save that number in // an array that has the ID of the related post as array key. $related_posts_commonality[$related_post->ID] = count(array_intersect($related_tag_ids, $tag_ids)); } ``` We then sort that latest array by value, from high to low, using [`arsort()`](https://secure.php.net/manual/en/function.arsort.php). ``` arsort($related_posts_commonality); ``` Finally, we limit it to only four posts using [`array_slice()`](https://secure.php.net/manual/en/function.array-slice.php): ``` $related_posts_commonality = array_slice($related_posts_commonality, 0, 4); ``` You can find the IDs of the related posts using [`array_keys`](https://secure.php.net/manual/en/function.array-keys.php), e.g.: ``` $related_posts_IDs = array_keys($related_posts_commonality); ``` Post display ------------ To actually display the posts, there's two routes you can take. You can either use the `$related_posts_commonality` array to loop through the results of `WP_Query` (i.e., `$related_all`), save the matching posts (in their right order) in a new array or object and loop through these once again for display. As this doesn't require additional queries, it's probably the most efficient one. However, it's also a pain. As such, you can also use simply use the IDs we've just found (`$related_posts_IDs`) to run another query. ``` $related_sorted = WP_query(array('post__in' => $related_posts_IDs)); ``` Then, you can use a regular [loop](https://codex.wordpress.org/Class_Reference/WP_Query#Usage) (`while ($related_sorted->have_posts())` and so on) to go through and display the results using functions as `the_title()` and `the_content()`.
326,503
<p>I am trying to write a <code>.htaccess</code> rule to redirect the URL to a subdomain.</p> <p>Example: <code>example.com/pagecategory/page-single</code> → <code>pagecategory.example.com/page-single</code></p> <p>I've added wildcard subdomain on my hosting.</p> <p>Can anyone help me write the <code>.htaccess</code> code?</p>
[ { "answer_id": 326648, "author": "Bram", "author_id": 60517, "author_profile": "https://wordpress.stackexchange.com/users/60517", "pm_score": 4, "selected": true, "text": "<p>Let's split the problem up in three bits: retrieving the related posts from the database, sorting them and displa...
2019/01/24
[ "https://wordpress.stackexchange.com/questions/326503", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/159725/" ]
I am trying to write a `.htaccess` rule to redirect the URL to a subdomain. Example: `example.com/pagecategory/page-single` → `pagecategory.example.com/page-single` I've added wildcard subdomain on my hosting. Can anyone help me write the `.htaccess` code?
Let's split the problem up in three bits: retrieving the related posts from the database, sorting them and displaying the result. Post retrieval -------------- This is possible using the [taxonomy parameters](https://codex.wordpress.org/Class_Reference/WP_Query#Taxonomy_Parameters) offered in `WP_Query`. Let's first retrieve the category of the current post and find their IDs: ``` $categories = get_the_terms( get_the_ID(), 'news-category' ); foreach ( $categories as $category ) { $category_ids[] = $category->term_id; } ``` We do the same for the tags: ``` $tags = get_the_terms( get_the_ID(), 'news-tags' ); foreach ( $tags as $tag) { $tag_ids[] = $tag->term_id; } ``` Then, we build a set of query arguments (we later feed to a `WP_Query`-call): ``` $related_args = array( 'post_type' => array( 'news', ), 'post_status' => 'publish', 'posts_per_page' => -1, // Get all posts 'post__not_in' => array( get_the_ID() ), // Hide current post in list of related content 'tax_query' => array( 'relation' => 'AND', // Make sure to mach both category and term array( 'taxonomy' => 'news-category', 'field' => 'term_id', 'terms' => $category_ids, ), array( 'taxonomy' => 'news-tags', 'field' => 'term_id', 'terms' => $tag_ids, ), ), ); ``` Finally, we run the query that gives us an array of ``` $related_all = new WP_Query( $related_args ); ``` Please note this query retrieves all posts that match the 'filter', as we're doing the ordering later on. If we'd now only query 4 posts, those might not be the most relevant. *Sidenote: the above query is quite heavy, in the sense that it (potentially) retrieves a large number of posts. When I've created a related posts section for a client project (also a news section), I ordered by date rather than relevance. That allows you to set a limit to the number of posts you retrieve from the database (change the `-1` to `4` in your case, and add `'orderby' => array( 'date' => 'DESC' )` to the `$related_args`-array). If you want to stick with ordering on the overlap, I suggest you add a date filter in the query arguments, or limit the number of results to some finite value, from which set you then retrieve the most relevant posts.* Post ordering ------------- Following the previous step, `$related_all` is a `WP_Query`-object. We access the actual posts as follows, and store them in `$related_all_posts`: ``` $related_all_posts = $related_all->posts; ``` That gives us an array we can more easily work with. We then loop through all the results in that array. Per the comments in the code, when looping through the results, we find the tags associated to the (related) post, find their IDs, compare that with the `$tag_ids` (of the main post) found earlier and see how much overlap there is using [`array_intersect()`](https://secure.php.net/manual/en/function.array-intersect.php): ``` foreach($related_all_posts as $related_post){ // Find all tags of the related post under consideration $related_post_tags = get_the_terms( $related_post->ID, 'news-tags' ); foreach ( $related_post_tags as $related_post_tag ) { $related_tag_ids[] = $related_post_tag->term_id; // Save their IDs in a query } // Find overlap with tags of main post (in $tag_ids) using array_intersect, and save that number in // an array that has the ID of the related post as array key. $related_posts_commonality[$related_post->ID] = count(array_intersect($related_tag_ids, $tag_ids)); } ``` We then sort that latest array by value, from high to low, using [`arsort()`](https://secure.php.net/manual/en/function.arsort.php). ``` arsort($related_posts_commonality); ``` Finally, we limit it to only four posts using [`array_slice()`](https://secure.php.net/manual/en/function.array-slice.php): ``` $related_posts_commonality = array_slice($related_posts_commonality, 0, 4); ``` You can find the IDs of the related posts using [`array_keys`](https://secure.php.net/manual/en/function.array-keys.php), e.g.: ``` $related_posts_IDs = array_keys($related_posts_commonality); ``` Post display ------------ To actually display the posts, there's two routes you can take. You can either use the `$related_posts_commonality` array to loop through the results of `WP_Query` (i.e., `$related_all`), save the matching posts (in their right order) in a new array or object and loop through these once again for display. As this doesn't require additional queries, it's probably the most efficient one. However, it's also a pain. As such, you can also use simply use the IDs we've just found (`$related_posts_IDs`) to run another query. ``` $related_sorted = WP_query(array('post__in' => $related_posts_IDs)); ``` Then, you can use a regular [loop](https://codex.wordpress.org/Class_Reference/WP_Query#Usage) (`while ($related_sorted->have_posts())` and so on) to go through and display the results using functions as `the_title()` and `the_content()`.
326,530
<p>I need to disable the Gutenberg text-settings tab in all Blocks. Is this possible with a funtion in funtions.php?</p> <p>I could disable the colors tab, but found no solution for the text-settings:</p> <pre><code>function disable_tabs() { add_theme_support( 'editor-color-palette' ); add_theme_support( 'disable-custom-colors' ); } add_action( 'after_setup_theme', 'disable_tabs' ); </code></pre> <p><a href="https://i.stack.imgur.com/QlcmX.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/QlcmX.jpg" alt="The text-settings tab"></a></p>
[ { "answer_id": 332375, "author": "WebElaine", "author_id": 102815, "author_profile": "https://wordpress.stackexchange.com/users/102815", "pm_score": 3, "selected": false, "text": "<p>The closest I can find in <a href=\"https://wordpress.org/gutenberg/handbook/designers-developers/develop...
2019/01/24
[ "https://wordpress.stackexchange.com/questions/326530", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/81609/" ]
I need to disable the Gutenberg text-settings tab in all Blocks. Is this possible with a funtion in funtions.php? I could disable the colors tab, but found no solution for the text-settings: ``` function disable_tabs() { add_theme_support( 'editor-color-palette' ); add_theme_support( 'disable-custom-colors' ); } add_action( 'after_setup_theme', 'disable_tabs' ); ``` [![The text-settings tab](https://i.stack.imgur.com/QlcmX.jpg)](https://i.stack.imgur.com/QlcmX.jpg)
The closest I can find in [the documentation](https://wordpress.org/gutenberg/handbook/designers-developers/developers/themes/theme-support/) is disabling custom font size (the text input) and forcing the dropdown font size to only contain "Normal". ``` add_action('after_setup_theme', 'wpse_remove_custom_colors'); function wpse_remove_custom_colors() { // removes the text box where users can enter custom pixel sizes add_theme_support('disable-custom-font-sizes'); // forces the dropdown for font sizes to only contain "normal" add_theme_support('editor-font-sizes', array( array( 'name' => 'Normal', 'size' => 16, 'slug' => 'normal' ) ) ); } ``` Note this may not work for non-Core blocks - they may have their own way of registering font size etc. that isn't affected by theme\_support. Hoping someone else from the community knows how to disable the drop caps as well. **Update: a way to remove Drop Caps** This wouldn't be my preferred method, because you can still add a Drop Cap in the editor and it just doesn't render in the front end, but it's all I have been able to achieve so far: There is a `render_block()` hook where you can change what renders on the front end without changing what shows in the editor or gets saved to the database. ``` add_filter('render_block', function($block_content, $block) { // only affect the Core Paragraph block if('core/paragraph' === $block['blockName']) { // remove the class that creates the drop cap $block_content = str_replace('class="has-drop-cap"', '', $block_content); } // always return the content, whether we changed it or not return $block_content; }, 10, 2); ``` This method changes the outer appearance rather than the actual content, so that if you ever wanted to allow drop caps, you could just remove the filter and all the ones that people had added in the editor would suddenly appear.