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
373,972
<p>I have a CPT called jobs and a page named Job Apply. I am trying to achieve something like below url:</p> <pre><code>http://example.com/job-slug/apply </code></pre> <p>Where, <strong>job-slug</strong> can be any job. i.e Programmer, Developer etc..</p> <p>On clicking job's apply button, it should open an apply page which consists a simple form, but url should be as mentioned above.</p> <p>I am trying to achieve it by using add_rewrite_rule(), but after trying too much, it is still redirecting me on the below url:</p> <pre><code>http://example.com/apply </code></pre> <p>Any help would be appreciated. Thanks in advance.</p>
[ { "answer_id": 373443, "author": "Suresh Shinde", "author_id": 167466, "author_profile": "https://wordpress.stackexchange.com/users/167466", "pm_score": -1, "selected": false, "text": "<p>You can do it by .htaccess file, for your case url format as;</p>\n<p>Redirect 301 /%post_id%/ <a hr...
2020/08/29
[ "https://wordpress.stackexchange.com/questions/373972", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/182583/" ]
I have a CPT called jobs and a page named Job Apply. I am trying to achieve something like below url: ``` http://example.com/job-slug/apply ``` Where, **job-slug** can be any job. i.e Programmer, Developer etc.. On clicking job's apply button, it should open an apply page which consists a simple form, but url should be as mentioned above. I am trying to achieve it by using add\_rewrite\_rule(), but after trying too much, it is still redirecting me on the below url: ``` http://example.com/apply ``` Any help would be appreciated. Thanks in advance.
I've written my own solution, sharing it and hoping it will help someone. Add this to your `functions.php`: ``` <?php add_action('parse_request', 'redirect_postid_to_postname'); function redirect_postid_to_postname($wp) { // If /%post_id%/ if (is_numeric($wp->request)) { $post_id = $wp->request; $slug = get_post_field( 'post_name', $post_id ); // If the post slug === the post number, prevent redirection loops. if ($slug !== $post_id) { // Adding url parameters manually to $redirect_to $parameters = $_SERVER[QUERY_STRING]; $redirect_from = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]"; $redirect_to = get_permalink($post_id) . (!empty($parameters) ? ("?" . $parameters) : ""); // Prevent loops if($redirect_from !== $redirect_to) { wp_redirect($redirect_to, 301); exit; } } } } ```
374,082
<p>I installed a plugin that has a custom post type, that looks like the picture below:</p> <p><a href="https://i.stack.imgur.com/GDWKG.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/GDWKG.png" alt="enter image description here" /></a></p> <p>WhatI's like to do is hide the &quot;Pictures&quot; link in this menu. It's a custom post type. The link looks like: <code>edit.php?post_type=cbs_pictures</code></p> <p>I tried:</p> <pre><code>function plt_hide_custom_post_type_ui_menus() { remove_submenu_page('menu-posts-cbs_booking', 'edit.php?post_type=cbs_pictures'); } add_action('admin_menu', 'plt_hide_custom_post_type_ui_menus', 11); </code></pre> <p>I also tried:</p> <pre><code>function your_custom__remove_menu_items() { remove_menu_page( 'edit.php?post_type=cbs_pictures' ); } add_action( 'admin_menu', 'your_custom_remove_menu_items' ); </code></pre> <p>but neither of these snippets worked...the &quot;Pictures&quot; link still shows.</p> <p>Anyone know how this could be hidden? I would like to still be able to use the url to access the page, I would just like the &quot;Pictures&quot; menu item to be hidden. Any ideas?</p> <p>Thanks,<br /> Josh</p>
[ { "answer_id": 373986, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 2, "selected": false, "text": "<p>Very little. Any media you uploaded, and any plugins or themes you installed, will be the in<code>/wp-c...
2020/09/01
[ "https://wordpress.stackexchange.com/questions/374082", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/9820/" ]
I installed a plugin that has a custom post type, that looks like the picture below: [![enter image description here](https://i.stack.imgur.com/GDWKG.png)](https://i.stack.imgur.com/GDWKG.png) WhatI's like to do is hide the "Pictures" link in this menu. It's a custom post type. The link looks like: `edit.php?post_type=cbs_pictures` I tried: ``` function plt_hide_custom_post_type_ui_menus() { remove_submenu_page('menu-posts-cbs_booking', 'edit.php?post_type=cbs_pictures'); } add_action('admin_menu', 'plt_hide_custom_post_type_ui_menus', 11); ``` I also tried: ``` function your_custom__remove_menu_items() { remove_menu_page( 'edit.php?post_type=cbs_pictures' ); } add_action( 'admin_menu', 'your_custom_remove_menu_items' ); ``` but neither of these snippets worked...the "Pictures" link still shows. Anyone know how this could be hidden? I would like to still be able to use the url to access the page, I would just like the "Pictures" menu item to be hidden. Any ideas? Thanks, Josh
All site content for your WordPress site is stored in the database. The files that query and display the data, store settings, etc, are in the theme and plugin folders. There is the wp-config.php file that stores access credentials for your database. And media files are stored in the wp-content folder, but media files locations are stored in the database. If you have a backup of your database, you can essentially recreate all content by installing the latest versions of themes and plugin, then activate as required. You also need a backup of your media file folders and files. With those items, you can essentially recreate your site. That means that it is important to not only backup your database, but also your media files. There are plugins that will allow a re-sync of media files into the database, but a backup of everything (database, themes, plugins, media folders and contents) is an important thing to do - that will help you recover from problems. Your hosting company may do backups of your entire public\_html folder, and your databases, so you could contact them to restore all or part of your site. But a backup plugin that takes care of all databases, and the folders/files in themes/plugins/media is a good thing to have - especially if those backups are stored 'off-site' (for instance, emailed to you).
374,111
<p>I am facing a problem with the loop inside the page template. Here is the code.</p> <pre><code>&lt;?php /* Template Name: Blog-Template */ get_header(); $args = [ 'post_type' =&gt; 'post', 'posts_per_page' =&gt; 1, ]; $queryP = new WP_Query( $args ); if ($queryP-&gt;have_posts()) { while ( $queryP-&gt;have_posts() ) : $queryP-&gt;the_post(); ?&gt; &lt;article&gt; &lt;?php the_title( '&lt;h1&gt;', '&lt;/h1&gt;' ); the_excerpt(); ?&gt; &lt;/article&gt; &lt;?php endwhile; } get_footer(); </code></pre> <p>If I set this page as a blog page in settings then no problem happens. But when I create a custom loop for this template it doesn't work. It shows nothing just header and footer.</p>
[ { "answer_id": 374384, "author": "Hector", "author_id": 48376, "author_profile": "https://wordpress.stackexchange.com/users/48376", "pm_score": 0, "selected": false, "text": "<p>From <a href=\"https://wordpress.org/support/article/creating-a-static-front-page/\" rel=\"nofollow noreferrer...
2020/09/01
[ "https://wordpress.stackexchange.com/questions/374111", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/140102/" ]
I am facing a problem with the loop inside the page template. Here is the code. ``` <?php /* Template Name: Blog-Template */ get_header(); $args = [ 'post_type' => 'post', 'posts_per_page' => 1, ]; $queryP = new WP_Query( $args ); if ($queryP->have_posts()) { while ( $queryP->have_posts() ) : $queryP->the_post(); ?> <article> <?php the_title( '<h1>', '</h1>' ); the_excerpt(); ?> </article> <?php endwhile; } get_footer(); ``` If I set this page as a blog page in settings then no problem happens. But when I create a custom loop for this template it doesn't work. It shows nothing just header and footer.
It solved automatically. I think the WordPress version 5.5.1 is full of bugs. Thanks, everyone for your support.
374,121
<p>I am trying to take my existing object array then json_encode it and add it to a $_SESSION[''] so I can request it on other pages on my website. Is there a way to save my session string (or array) and display it on another page?</p> <p>Below is the code of the array I am trying to add into a session. ( I don't know if I need to encode it, but I thought it would increase performance perhaps?)</p> <pre><code> $postArray = array( &quot;CompanyID&quot; =&gt; &quot;5&quot;, &quot;FirstName&quot; =&gt; $_POST['first_name'], &quot;LastName&quot; =&gt; $_POST['last_name'], &quot;Email&quot; =&gt; $_POST['email'], &quot;Company&quot; =&gt; $_POST['company'], &quot;Phone&quot; =&gt; $_POST['phone'], &quot;Fax&quot; =&gt; $_POST['fax'], &quot;AdressLine1&quot; =&gt; $_POST['address'], &quot;AdressLine2&quot; =&gt; &quot;&quot;, &quot;City&quot; =&gt; $_POST['city'], &quot;DistrictID&quot; =&gt; $_POST['state'], &quot;CountryID&quot; =&gt; $_POST['country'], &quot;PostCode&quot; =&gt; $_POST['postcode'], &quot;SpecialInstructions&quot; =&gt; $_POST['special'], &quot;Items&quot; =&gt; $item_array , &quot;Source&quot; =&gt; &quot;Web submission&quot; ); $json = json_encode($postArray); </code></pre> <p>Then right after that code I try to initialize an action to wp to start and add to session</p> <pre><code>add_action('wp', 'start_my_session'); function start_my_session() { session_start(); $_SESSION['order_details'] = $GLOBALS['json']; } </code></pre> <p>After that I try to call it on a new page with this code</p> <pre><code>&lt;?php add_action('wp_footer', 'show_session_var'); function show_session_var() { if(isset($_SESSION['order_details'])) echo $_SESSION['order_details']; } ?&gt; </code></pre> <p>When I try to retrieve the data I get this error: session_start(): <em>Cannot start session when headers already sent</em> but I need to create a session because wordpress doesn't automatically make one?</p> <p>Any thoughts? I am new to php development in Wordpress.</p>
[ { "answer_id": 374126, "author": "drcrow", "author_id": 178234, "author_profile": "https://wordpress.stackexchange.com/users/178234", "pm_score": 3, "selected": true, "text": "<p>Remove your session_start() and at the beginning of your functions.php put this:</p>\n<pre><code>if (!session...
2020/09/01
[ "https://wordpress.stackexchange.com/questions/374121", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/193744/" ]
I am trying to take my existing object array then json\_encode it and add it to a $\_SESSION[''] so I can request it on other pages on my website. Is there a way to save my session string (or array) and display it on another page? Below is the code of the array I am trying to add into a session. ( I don't know if I need to encode it, but I thought it would increase performance perhaps?) ``` $postArray = array( "CompanyID" => "5", "FirstName" => $_POST['first_name'], "LastName" => $_POST['last_name'], "Email" => $_POST['email'], "Company" => $_POST['company'], "Phone" => $_POST['phone'], "Fax" => $_POST['fax'], "AdressLine1" => $_POST['address'], "AdressLine2" => "", "City" => $_POST['city'], "DistrictID" => $_POST['state'], "CountryID" => $_POST['country'], "PostCode" => $_POST['postcode'], "SpecialInstructions" => $_POST['special'], "Items" => $item_array , "Source" => "Web submission" ); $json = json_encode($postArray); ``` Then right after that code I try to initialize an action to wp to start and add to session ``` add_action('wp', 'start_my_session'); function start_my_session() { session_start(); $_SESSION['order_details'] = $GLOBALS['json']; } ``` After that I try to call it on a new page with this code ``` <?php add_action('wp_footer', 'show_session_var'); function show_session_var() { if(isset($_SESSION['order_details'])) echo $_SESSION['order_details']; } ?> ``` When I try to retrieve the data I get this error: session\_start(): *Cannot start session when headers already sent* but I need to create a session because wordpress doesn't automatically make one? Any thoughts? I am new to php development in Wordpress.
Remove your session\_start() and at the beginning of your functions.php put this: ``` if (!session_id()) { session_start(); } ``` For use from a plugin use this: ``` function register_session(){ if( !session_id() ) session_start(); } add_action('init','register_session'); ```
374,165
<p>I am creating a custom word press theme and i am little stuck in one situation, what i want is to echo the specific values of an array in the form of bordered tables. For example i want to display | location | qualification | date |</p> <p>here below is my code</p> <pre><code> &lt;td class=&quot;row-2 row-email&quot;&gt;&lt;?php $release_edu_qual = get_post_meta( get_the_ID(), '_candidate_education', true ); print_r($release_edu_qual); ?&gt;&lt;/td&gt; </code></pre> <p>and this is the output of the above code:</p> <blockquote> <p>Array ( [0] =&gt; Array ( [location] =&gt; Stanford University [qualification] =&gt; School of Arts &amp; Sciences [date] =&gt; 2012-2015 [notes] =&gt; Maximus faucibus non non nibh. Cras luctus velit et ante vehicula, sit amet commodo magna eleifend. Fusce congue ante id urna porttitor luctus. ) [1] =&gt; Array ( [location] =&gt; University of Pennsylvania [qualification] =&gt; School of Design [date] =&gt; 2010-2012 [notes] =&gt; Phasellus vestibulum metus orci, ut facilisis dolor interdum eget. Pellentesque magna sem, hendrerit nec elit sit amet, ornare efficitur est. ) [2] =&gt; Array ( [location] =&gt; Massachusetts Institute of Technology [qualification] =&gt; [date] =&gt; 2006-2010 [notes] =&gt; Suspendisse lorem lorem, aliquet at lectus quis, porttitor porta sapien. Etiam ut turpis tempor, vulputate risus at, elementum dui. Etiam faucibus. ) )</p> </blockquote>
[ { "answer_id": 374209, "author": "davidb3rn", "author_id": 193744, "author_profile": "https://wordpress.stackexchange.com/users/193744", "pm_score": 0, "selected": false, "text": "<p>To get a specific item in the object when already inside a specific array.</p>\n<pre><code>$location = $r...
2020/09/02
[ "https://wordpress.stackexchange.com/questions/374165", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/194041/" ]
I am creating a custom word press theme and i am little stuck in one situation, what i want is to echo the specific values of an array in the form of bordered tables. For example i want to display | location | qualification | date | here below is my code ``` <td class="row-2 row-email"><?php $release_edu_qual = get_post_meta( get_the_ID(), '_candidate_education', true ); print_r($release_edu_qual); ?></td> ``` and this is the output of the above code: > > Array ( [0] => Array ( [location] => Stanford University > [qualification] => School of Arts & Sciences [date] => 2012-2015 > [notes] > => Maximus faucibus non non nibh. Cras luctus velit et ante vehicula, sit amet commodo magna eleifend. Fusce congue ante id urna porttitor > luctus. ) [1] => Array ( [location] => University of Pennsylvania > [qualification] => School of Design [date] => 2010-2012 [notes] => > Phasellus vestibulum metus orci, ut facilisis dolor interdum eget. > Pellentesque magna sem, hendrerit nec elit sit amet, ornare efficitur > est. ) [2] => Array ( [location] => Massachusetts Institute of > Technology [qualification] => [date] => 2006-2010 [notes] > => Suspendisse lorem lorem, aliquet at lectus quis, porttitor porta sapien. Etiam ut turpis tempor, vulputate risus at, elementum dui. > Etiam faucibus. ) ) > > >
The previous answer is wrong, to access the array elements, you need to get it by the key: ``` $location = $release_edu_qual[0]["location"]; ``` In the above code, we're getting the location of the array that's first (zero based) in the initial array. So to list all the array data you want from that initial array you could use something like: ``` <table> <thead> <tr> <th>Location</th> <th>Qualification</th> <th>Date</th> </tr> </thead> <tbody> <?php foreach( $release_edu_qual as $item ){ echo '<tr>'; echo '<td>' . $item["location"] . '</td>'; echo '<td>' . $item["qualification"] . '</td>'; echo '<td>' . $item["date"] . '</td>'; echo '</tr>'; } ?> </tbody> </table> ```
374,173
<p>I want to create a shortcode where content is displayed if user meta is equal to a value</p> <p>It Works but it's code isn't perfect</p> <p>how would you have done? How Can I improve it?</p> <p>Example content display if firstname user is Jeff</p> <pre><code>[check-if-equal usermeta=&quot;firstname&quot; uservalue=&quot;Jeff&quot;] Yes [/check-if-equal] </code></pre> <p>This is the code handling the above shortcode</p> <pre><code>&lt;?php function func_check_if_equal( $atts, $content = null ) { if ( is_user_logged_in() ) { /* check if logged in */ $user_meta = $atts['usermeta']; $user_value = $atts['uservalue']; /* get value from shortcode parameter */ $user_id = get_current_user_id(); /* get user id */ $user_data = get_userdata( $user_id ); /* get user meta */ if ( $user_data-&gt;$user_meta == $user_value ) { /* if user meta is equal meta value */ return $content; /* show content from shortcode */ } else { return ''; /* meta field don't equal */ } } else { return ''; /* user is not logged in */ } } } add_shortcode( 'check-if-equal', 'func_check_if_equal' ); </code></pre> <p>Thanks</p>
[ { "answer_id": 374209, "author": "davidb3rn", "author_id": 193744, "author_profile": "https://wordpress.stackexchange.com/users/193744", "pm_score": 0, "selected": false, "text": "<p>To get a specific item in the object when already inside a specific array.</p>\n<pre><code>$location = $r...
2020/09/02
[ "https://wordpress.stackexchange.com/questions/374173", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/192355/" ]
I want to create a shortcode where content is displayed if user meta is equal to a value It Works but it's code isn't perfect how would you have done? How Can I improve it? Example content display if firstname user is Jeff ``` [check-if-equal usermeta="firstname" uservalue="Jeff"] Yes [/check-if-equal] ``` This is the code handling the above shortcode ``` <?php function func_check_if_equal( $atts, $content = null ) { if ( is_user_logged_in() ) { /* check if logged in */ $user_meta = $atts['usermeta']; $user_value = $atts['uservalue']; /* get value from shortcode parameter */ $user_id = get_current_user_id(); /* get user id */ $user_data = get_userdata( $user_id ); /* get user meta */ if ( $user_data->$user_meta == $user_value ) { /* if user meta is equal meta value */ return $content; /* show content from shortcode */ } else { return ''; /* meta field don't equal */ } } else { return ''; /* user is not logged in */ } } } add_shortcode( 'check-if-equal', 'func_check_if_equal' ); ``` Thanks
The previous answer is wrong, to access the array elements, you need to get it by the key: ``` $location = $release_edu_qual[0]["location"]; ``` In the above code, we're getting the location of the array that's first (zero based) in the initial array. So to list all the array data you want from that initial array you could use something like: ``` <table> <thead> <tr> <th>Location</th> <th>Qualification</th> <th>Date</th> </tr> </thead> <tbody> <?php foreach( $release_edu_qual as $item ){ echo '<tr>'; echo '<td>' . $item["location"] . '</td>'; echo '<td>' . $item["qualification"] . '</td>'; echo '<td>' . $item["date"] . '</td>'; echo '</tr>'; } ?> </tbody> </table> ```
374,181
<p>I have issue adding the <code>meta_value</code> in search query for the WooCommerce SKU. By default, the search by SKU only work on the admin.</p> <p>I would like to make the frontend search accepting SKU in search.</p> <p>Note : SKU are not in the product title. So I need to create a custom query.</p> <pre><code> function SearchFilter($query) { if ($query-&gt;is_search) { $meta_query_args = array( 'relation' =&gt; 'OR', array( 'key' =&gt; '_sku', 'value' =&gt; $query-&gt;query_vars['s'], 'compare' =&gt; '=', ) ); $query-&gt;set('post_type', array('post','page', 'product')); $query-&gt;set('post_status', array('publish')); $query-&gt;set('meta_query', $meta_query_args); } return $query; } add_filter('pre_get_posts','SearchFilter'); </code></pre> <p><strong>The problem :</strong> When I place this code and I print the current SQL request, it gives me something like this.</p> <pre><code> SELECT SQL_CALC_FOUND_ROWS bhd_posts.ID FROM bhd_posts INNER JOIN bhd_postmeta ON ( bhd_posts.ID = bhd_postmeta.post_id ) WHERE 1=1 AND (((bhd_posts.post_title LIKE '%96242-20VH%') OR (bhd_posts.post_excerpt LIKE '%96242-20VH%') OR (bhd_posts.post_content LIKE '%96242-20VH%'))) AND (bhd_posts.post_password = '') AND ( ( bhd_postmeta.meta_key = '_sku' AND bhd_postmeta.meta_value = '96242-20VH' ) ) AND bhd_posts.post_type IN ('post', 'page', 'product') AND ((bhd_posts.post_status = 'publish')) GROUP BY bhd_posts.ID ORDER BY bhd_posts.post_title LIKE '%96242-20VH%' DESC, bhd_posts.post_date DESC LIMIT 0, 10 </code></pre> <p>As you can see, it tries to fetch for the &quot;classic part&quot; in the table <code>x_posts</code> for <code>post_title</code> OR <code>post_excerpt</code> OR <code>post_content</code> <strong>AND</strong> it must have a <code>meta_value</code> of my SKU.</p> <p>As told above, my product titles do not have the sku in them.</p> <p><strong>Goal :</strong> Having to search in titles, excerpt, content or in meta_value OR search exclusivly with the meta_value.</p>
[ { "answer_id": 378507, "author": "AHSAN KHAN", "author_id": 134461, "author_profile": "https://wordpress.stackexchange.com/users/134461", "pm_score": 3, "selected": false, "text": "<p>If you are using wordpress search you can add this code to make it work</p>\n<pre><code>function search_...
2020/09/02
[ "https://wordpress.stackexchange.com/questions/374181", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/32365/" ]
I have issue adding the `meta_value` in search query for the WooCommerce SKU. By default, the search by SKU only work on the admin. I would like to make the frontend search accepting SKU in search. Note : SKU are not in the product title. So I need to create a custom query. ``` function SearchFilter($query) { if ($query->is_search) { $meta_query_args = array( 'relation' => 'OR', array( 'key' => '_sku', 'value' => $query->query_vars['s'], 'compare' => '=', ) ); $query->set('post_type', array('post','page', 'product')); $query->set('post_status', array('publish')); $query->set('meta_query', $meta_query_args); } return $query; } add_filter('pre_get_posts','SearchFilter'); ``` **The problem :** When I place this code and I print the current SQL request, it gives me something like this. ``` SELECT SQL_CALC_FOUND_ROWS bhd_posts.ID FROM bhd_posts INNER JOIN bhd_postmeta ON ( bhd_posts.ID = bhd_postmeta.post_id ) WHERE 1=1 AND (((bhd_posts.post_title LIKE '%96242-20VH%') OR (bhd_posts.post_excerpt LIKE '%96242-20VH%') OR (bhd_posts.post_content LIKE '%96242-20VH%'))) AND (bhd_posts.post_password = '') AND ( ( bhd_postmeta.meta_key = '_sku' AND bhd_postmeta.meta_value = '96242-20VH' ) ) AND bhd_posts.post_type IN ('post', 'page', 'product') AND ((bhd_posts.post_status = 'publish')) GROUP BY bhd_posts.ID ORDER BY bhd_posts.post_title LIKE '%96242-20VH%' DESC, bhd_posts.post_date DESC LIMIT 0, 10 ``` As you can see, it tries to fetch for the "classic part" in the table `x_posts` for `post_title` OR `post_excerpt` OR `post_content` **AND** it must have a `meta_value` of my SKU. As told above, my product titles do not have the sku in them. **Goal :** Having to search in titles, excerpt, content or in meta\_value OR search exclusivly with the meta\_value.
If you are using wordpress search you can add this code to make it work ``` function search_by_sku( $search, &$query_vars ) { global $wpdb; if(isset($query_vars->query['s']) && !empty($query_vars->query['s'])){ $args = array( 'posts_per_page' => -1, 'post_type' => 'product', 'meta_query' => array( array( 'key' => '_sku', 'value' => $query_vars->query['s'], 'compare' => 'LIKE' ) ) ); $posts = get_posts($args); if(empty($posts)) return $search; $get_post_ids = array(); foreach($posts as $post){ $get_post_ids[] = $post->ID; } if(sizeof( $get_post_ids ) > 0 ) { $search = str_replace( 'AND (((', "AND ((({$wpdb->posts}.ID IN (" . implode( ',', $get_post_ids ) . ")) OR (", $search); } } return $search; } add_filter( 'posts_search', 'search_by_sku', 999, 2 ); ```
374,197
<p>I received an error from google saying that I have mobile usability errors on my site.</p> <p>the &quot;page&quot; that they are referring to is <a href="http://www.example.com/wp-content/plugins/ag-admin" rel="nofollow noreferrer">www.example.com/wp-content/plugins/ag-admin</a>.</p> <p>I'm not asking for help with that plugin, but trying to figure out how to make google not index that directory at all.</p> <p>Is disallawing this in my robots.txt enough or should I even have to do that?</p>
[ { "answer_id": 374200, "author": "Cyclonecode", "author_id": 14870, "author_profile": "https://wordpress.stackexchange.com/users/14870", "pm_score": 1, "selected": false, "text": "<p><strong>Using <code>robots.txt</code></strong></p>\n<p>Yes you could use a <code>robots.txt</code> file f...
2020/09/02
[ "https://wordpress.stackexchange.com/questions/374197", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/105668/" ]
I received an error from google saying that I have mobile usability errors on my site. the "page" that they are referring to is [www.example.com/wp-content/plugins/ag-admin](http://www.example.com/wp-content/plugins/ag-admin). I'm not asking for help with that plugin, but trying to figure out how to make google not index that directory at all. Is disallawing this in my robots.txt enough or should I even have to do that?
Here's the thing There are multiple ways to do what you want, from adding meta tags, to passing headers, but because, you tagged your question with robots.txt So i consider it off-topic to discuss any other solutions. Considering your demand you need to have this as your robots.txt This disallowed access to wp-admin, but depending on use case, you may need ajax, so I gave it an exception, and then disallowed wp-content, and wp-includes. Change your robots.txt situated in root directory, like this ``` User-agent: * Disallow: /wp-admin/ Allow: /wp-admin/admin-ajax.php Noindex: /wp-content/ Noindex: /wp-includes/ ``` This shall ask google to not index anything in wp-content and wp-includes, Google is slow and it would take its bot some time, to realize he is going at wrong place, so it would eventually remove it from its index. **The below HTACCESS METHOD is completely optional, the Robots.txt can do the trick with work, but HTACCESS is much more consistent method, therefore I couldnt resist myself from telling it** Incase you are willing to edit ht-access file, then that would be a better approach. I myself use it on my site. My code below if put in htaccess files, blocks all PHP and backend specific files, but allows all images, videos, pdfs and various similar file formats to be indexed by Google and others. ``` # Serves only static files RewriteCond %{REQUEST_FILENAME} -f RewriteRule ^wp-(content|includes)/([^/]+/)*([^/.]+\.)+ (jp(e?g|2)?|png|gif|bmp|ico|css|js|swf|xml|xsl|html?|mp(eg[34])|avi|wav|og[gv]|xlsx?|docx?|pptx?|gz|zip|rar|pdf|xps|7z|[ot]tf|eot|woff2?|svg|od[tsp]|flv|mov)$ - [L] RewriteRule ^wp-(content|includes|admin/includes)/ - [R=404,L] ```
374,220
<p>We've got a WP+woocommerce site that is over 8 years old. The site has over 60,000 users and a similar number of orders. The wp_postmeta has over 4,000,000 records and wp_usermeta has over 1,500,000. This is causing all kinds of issues because the site was not updated regularly. The site wants to update the DB and it crashes every time, likely because of these tables.</p> <p>Any ideas?</p>
[ { "answer_id": 374223, "author": "Aditya Agarwal", "author_id": 166927, "author_profile": "https://wordpress.stackexchange.com/users/166927", "pm_score": 0, "selected": false, "text": "<p>There are multiple Things to consider,</p>\n<ol>\n<li><p>No database is too big, to be handles, if y...
2020/09/03
[ "https://wordpress.stackexchange.com/questions/374220", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/182332/" ]
We've got a WP+woocommerce site that is over 8 years old. The site has over 60,000 users and a similar number of orders. The wp\_postmeta has over 4,000,000 records and wp\_usermeta has over 1,500,000. This is causing all kinds of issues because the site was not updated regularly. The site wants to update the DB and it crashes every time, likely because of these tables. Any ideas?
Modern MariaDB and MySQL versions allow your tables' keys to be more efficient. Better keys can help a lot to speed up the kinds of database queries WooCommerce (and core WordPress) use. If you have a recent MySQL version that can handle the DYNAMIC row format, these postmeta keys will help a lot. ```sql PRIMARY KEY (`post_id`, `meta_key`, `meta_id`), UNIQUE KEY `meta_id` (`meta_id`), KEY `meta_key` (`meta_key`, `meta_value`(32), `post_id`, `meta_id`), KEY `meta_value` (`meta_value`(32), `meta_id`) ``` [This plugin](https://wordpress.org/plugins/index-wp-mysql-for-speed/) installs those database keys for you. To avoid timeouts when installing the keys, you should run it with wp-cli. [This plugin](https://wordpress.org/plugins/index-wp-users-for-speed/) mitigates some database inefficiencies with many users.
374,269
<p>Returning to WP after nine years – will the classic editor plugin allow me to pretend it's 2011 as I migrate my site over from squarespace?</p> <p>I'd like to move my business website to self-hosted Wordpress. Previously, around 2011 in my old business, we used PHP/HTML/CSS in theme templates to create customizations for our Wordpress site.</p> <p>It seems the entire customization paradigm has changed with WordPress &amp; now focuses on plugins. My preference is make my customizations in raw theme files &amp; to use the classic editor for the blog portion of the website.</p>
[ { "answer_id": 374223, "author": "Aditya Agarwal", "author_id": 166927, "author_profile": "https://wordpress.stackexchange.com/users/166927", "pm_score": 0, "selected": false, "text": "<p>There are multiple Things to consider,</p>\n<ol>\n<li><p>No database is too big, to be handles, if y...
2020/09/03
[ "https://wordpress.stackexchange.com/questions/374269", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/164/" ]
Returning to WP after nine years – will the classic editor plugin allow me to pretend it's 2011 as I migrate my site over from squarespace? I'd like to move my business website to self-hosted Wordpress. Previously, around 2011 in my old business, we used PHP/HTML/CSS in theme templates to create customizations for our Wordpress site. It seems the entire customization paradigm has changed with WordPress & now focuses on plugins. My preference is make my customizations in raw theme files & to use the classic editor for the blog portion of the website.
Modern MariaDB and MySQL versions allow your tables' keys to be more efficient. Better keys can help a lot to speed up the kinds of database queries WooCommerce (and core WordPress) use. If you have a recent MySQL version that can handle the DYNAMIC row format, these postmeta keys will help a lot. ```sql PRIMARY KEY (`post_id`, `meta_key`, `meta_id`), UNIQUE KEY `meta_id` (`meta_id`), KEY `meta_key` (`meta_key`, `meta_value`(32), `post_id`, `meta_id`), KEY `meta_value` (`meta_value`(32), `meta_id`) ``` [This plugin](https://wordpress.org/plugins/index-wp-mysql-for-speed/) installs those database keys for you. To avoid timeouts when installing the keys, you should run it with wp-cli. [This plugin](https://wordpress.org/plugins/index-wp-users-for-speed/) mitigates some database inefficiencies with many users.
374,326
<p>I'm using the <code>wp_list_categories()</code> function which generates an unordered list with list items and anchor tags for the categories. Is there any way to add HTML attributes to the <code>&lt;a&gt;</code> tags which hold the category links?</p> <p>I'd like to add a <code>title</code> attribute which is the same as the category, and a <code>class</code> attribute, but looking at the docs, in the list of associative array properties I can't see how to do this?</p> <p>The code I'm using is:</p> <pre><code>&lt;?php echo '&lt;ul class=&quot;cat-sidebar-list&quot;&gt;'; $args_list = array( 'taxonomy' =&gt; 'news_categories', 'show_count' =&gt; false, 'hierarchical' =&gt; true, 'hide_empty' =&gt; false, 'title_li' =&gt; '', ); echo wp_list_categories($args_list); echo '&lt;/ul&gt;'; ?&gt; </code></pre> <p>Thanks in advance for any help.</p>
[ { "answer_id": 374460, "author": "bueltge", "author_id": 170, "author_profile": "https://wordpress.stackexchange.com/users/170", "pm_score": 1, "selected": false, "text": "<h3>Custom Walker</h3>\n<p>The function <a href=\"https://developer.wordpress.org/reference/functions/wp_list_catego...
2020/09/05
[ "https://wordpress.stackexchange.com/questions/374326", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/106972/" ]
I'm using the `wp_list_categories()` function which generates an unordered list with list items and anchor tags for the categories. Is there any way to add HTML attributes to the `<a>` tags which hold the category links? I'd like to add a `title` attribute which is the same as the category, and a `class` attribute, but looking at the docs, in the list of associative array properties I can't see how to do this? The code I'm using is: ``` <?php echo '<ul class="cat-sidebar-list">'; $args_list = array( 'taxonomy' => 'news_categories', 'show_count' => false, 'hierarchical' => true, 'hide_empty' => false, 'title_li' => '', ); echo wp_list_categories($args_list); echo '</ul>'; ?> ``` Thanks in advance for any help.
The default walker used by `wp_list_categories()` ([`Walker_Category`](https://developer.wordpress.org/reference/classes/walker_category/)) has a hook (a filter hook) named [`category_list_link_attributes`](https://developer.wordpress.org/reference/hooks/category_list_link_attributes/) which you can use to add custom `title` and `class` (as well as other attributes like `data-xxx`) to the *anchor*/`a` tag (`<a>`) in the HTML list generated via `wp_list_categories()`. So for example, you can do something like: ```php add_filter( 'category_list_link_attributes', 'my_category_list_link_attributes', 10, 2 ); function my_category_list_link_attributes( $atts, $category ) { // Set the title to the category description if it's available. Else, use the name. $atts['title'] = $category->description ? $category->description : $category->name; // Set a custom class. $atts['class'] = 'custom-class category-' . $category->slug; // $atts['class'] .= ' custom-class'; // or append a new class // $atts['class'] = 'custom-class ' . $atts['class']; // or maybe prepend it return $atts; } ```
374,371
<p>This is my loop:</p> <pre><code>&lt;?php $comments = get_comments(array( 'status' =&gt; 'approve', 'type' =&gt; 'comment', 'number' =&gt; 10, 'post_status' =&gt; 'public' )); ?&gt; &lt;ul class=&quot;sidebar-comments&quot;&gt; &lt;?php foreach ($comments as $comment) { ?&gt; &lt;li&gt; &lt;div&gt;&lt;?php echo get_avatar($comment, $size = '35'); ?&gt;&lt;/div&gt; &lt;em style=&quot;font-size:12px&quot;&gt;&lt;?php echo strip_tags($comment-&gt;comment_author); ?&gt;&lt;/em&gt; (&lt;a href=&quot;&lt;?php echo get_option('home'); ?&gt;/?p=&lt;?php echo ($comment-&gt;comment_post_ID); ?&gt;/#comment-&lt;?php echo ($comment-&gt;comment_ID); ?&gt;&quot;&gt;link&lt;/a&gt;)&lt;br&gt; &lt;?php echo wp_html_excerpt($comment-&gt;comment_content, 35); ?&gt;... &lt;/li&gt; &lt;?php } ?&gt; &lt;/ul&gt; </code></pre> <p>This always gives an empty result (no errors). If I remove <code>'post_status' =&gt; 'public'</code> from the get_comments arguments, the function works, comments load but also comments from private posts (which I don't want).</p> <p>Any ideas on why <code>'post_status' =&gt; 'public'</code> is not working?</p>
[ { "answer_id": 374378, "author": "botondcs", "author_id": 115678, "author_profile": "https://wordpress.stackexchange.com/users/115678", "pm_score": 2, "selected": true, "text": "<p>Try <code>'post_status' =&gt; 'publish',</code> that should do the trick.</p>\n<p>See <a href=\"https://dev...
2020/09/06
[ "https://wordpress.stackexchange.com/questions/374371", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/23296/" ]
This is my loop: ``` <?php $comments = get_comments(array( 'status' => 'approve', 'type' => 'comment', 'number' => 10, 'post_status' => 'public' )); ?> <ul class="sidebar-comments"> <?php foreach ($comments as $comment) { ?> <li> <div><?php echo get_avatar($comment, $size = '35'); ?></div> <em style="font-size:12px"><?php echo strip_tags($comment->comment_author); ?></em> (<a href="<?php echo get_option('home'); ?>/?p=<?php echo ($comment->comment_post_ID); ?>/#comment-<?php echo ($comment->comment_ID); ?>">link</a>)<br> <?php echo wp_html_excerpt($comment->comment_content, 35); ?>... </li> <?php } ?> </ul> ``` This always gives an empty result (no errors). If I remove `'post_status' => 'public'` from the get\_comments arguments, the function works, comments load but also comments from private posts (which I don't want). Any ideas on why `'post_status' => 'public'` is not working?
Try `'post_status' => 'publish',` that should do the trick. See <https://developer.wordpress.org/reference/functions/get_post_statuses/> for more details.
374,407
<p>I got an auction theme (adifier) and i'm trying to add a button to a specific ads category.</p> <p>Tried a few codes but none seem to work, probably i don't know how to alter it properly. I got the category 3D Design where users should download the files that are uploaded from account page (where I should add another button with upload (I got I plugin with the upload button but don't know how to add it on the account page) ). Thanks in advance for any kind of help!</p> <pre class="lang-php prettyprint-override"><code>add_action( 'adifier_single_product_description', 'extra_button_on_product_page', 9 ); function extra_button_on_product_page() { global $post, $product; if ( has_term( 'accessories1-3d-design', 'product_cat' ) ) { echo '&lt;a class=&quot;button&quot; href=&quot;www.test.com&quot;&gt;Extra Button&lt;/a&gt;';` add_action( 'adifier_3d-design_description', 'extra_button_on_product_category_description', 9 ); function extra_button_on_product_category_description() { if ( is_product_category('accessories1') ) { echo '&lt;a class=&quot;button&quot; href=&quot;www.test.com&quot;&gt;Extra Button&lt;/a&gt;'; } } </code></pre>
[ { "answer_id": 374378, "author": "botondcs", "author_id": 115678, "author_profile": "https://wordpress.stackexchange.com/users/115678", "pm_score": 2, "selected": true, "text": "<p>Try <code>'post_status' =&gt; 'publish',</code> that should do the trick.</p>\n<p>See <a href=\"https://dev...
2020/09/07
[ "https://wordpress.stackexchange.com/questions/374407", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/194276/" ]
I got an auction theme (adifier) and i'm trying to add a button to a specific ads category. Tried a few codes but none seem to work, probably i don't know how to alter it properly. I got the category 3D Design where users should download the files that are uploaded from account page (where I should add another button with upload (I got I plugin with the upload button but don't know how to add it on the account page) ). Thanks in advance for any kind of help! ```php add_action( 'adifier_single_product_description', 'extra_button_on_product_page', 9 ); function extra_button_on_product_page() { global $post, $product; if ( has_term( 'accessories1-3d-design', 'product_cat' ) ) { echo '<a class="button" href="www.test.com">Extra Button</a>';` add_action( 'adifier_3d-design_description', 'extra_button_on_product_category_description', 9 ); function extra_button_on_product_category_description() { if ( is_product_category('accessories1') ) { echo '<a class="button" href="www.test.com">Extra Button</a>'; } } ```
Try `'post_status' => 'publish',` that should do the trick. See <https://developer.wordpress.org/reference/functions/get_post_statuses/> for more details.
374,523
<p><a href="https://i.stack.imgur.com/DkULs.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/DkULs.jpg" alt="enter image description here" /></a>Trying to implement <code>wp-bootstrap-navwalker.php</code> into my made from scratch template for wordpress.<br> The File for the <code>class-wp-bootstrap-navwalker.php</code> is located in the root directory of my theme.</p> <p><strong>functions.php</strong></p> <pre><code>function register_navwalker() { require_once get_template_directory() . '/class-wp-bootstrap-navwalker.php';&lt;br&gt; } add_action( 'after_setup_theme', 'register_navwalker' ); </code></pre> <p>register_nav_menus( array( 'primary' =&gt; __( 'Primary Menu', 'primary' ), ) );</p> <p><strong>cover.php</strong> With the code below within the <code>&lt;nav&gt; and &lt;/nav&gt;</code> tags</p> <pre><code> &lt;?php wp_nav_menu( array( 'theme_location' =&gt; 'top-menu', 'depth' =&gt; 2, 'container' =&gt; 'div', 'container_class' =&gt; 'collapse navbar-collapse', 'container_id' =&gt; 'bs-example-navbar-collapse-1', 'menu_class' =&gt; 'nav navbar-nav', 'fallback_cb' =&gt; 'WP_Bootstrap_Navwalker::fallback', 'walker' =&gt; new WP_Bootstrap_Navwalker(), ) ); ?&gt; </code></pre> <p>When I save changes and reload my website, I get get the wp-bootstrap-navwalker page from github.</p> <p>I've checked the source of the page and see this at the footer: <b>Fatal error</b>: Uncaught Error: Class 'WP_Bootstrap_Navwalker' not found in C:\laragon\www\VzyulTech\wp-content\themes\Version2\index.php:17 Stack trace: #0 C:\laragon\www\VzyulTech\wp-includes\template-loader.php(106): include() #1 C:\laragon\www\VzyulTech\wp-blog-header.php(19): require_once('C:\laragon\www\...') #2 C:\laragon\www\VzyulTech\index.php(17): require('C:\laragon\www\...') #3 {main} thrown in <b>C:\laragon\www\VzyulTech\wp-content\themes\Version2\index.php</b> on line <b>17</b><br /></p> <p>When I check line 17 it is the 'walker' =&gt; new WP_Bootstrap_Navwalker(),</p> <pre><code> wp_nav_menu( array( 'theme_location' =&gt; 'primary', 'depth' =&gt; 2, 'container' =&gt; 'div', 'container_class' =&gt; 'collapse navbar-collapse', 'container_id' =&gt; 'bs-example-navbar-collapse-1', 'menu_class' =&gt; 'nav navbar-nav', 'fallback_cb' =&gt; 'WP_Bootstrap_Navwalker::fallback', 'walker' =&gt; new WP_Bootstrap_Navwalker(), ) ); </code></pre> <p>any help is much appreciated.</p>
[ { "answer_id": 374531, "author": "HK89", "author_id": 179278, "author_profile": "https://wordpress.stackexchange.com/users/179278", "pm_score": 0, "selected": false, "text": "<p>Place class-wp-bootstrap-navwalker.php in your WordPress theme folder /wp-content/your-theme/</p>\n<p>Open you...
2020/09/09
[ "https://wordpress.stackexchange.com/questions/374523", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/194294/" ]
[![enter image description here](https://i.stack.imgur.com/DkULs.jpg)](https://i.stack.imgur.com/DkULs.jpg)Trying to implement `wp-bootstrap-navwalker.php` into my made from scratch template for wordpress. The File for the `class-wp-bootstrap-navwalker.php` is located in the root directory of my theme. **functions.php** ``` function register_navwalker() { require_once get_template_directory() . '/class-wp-bootstrap-navwalker.php';<br> } add_action( 'after_setup_theme', 'register_navwalker' ); ``` register\_nav\_menus( array( 'primary' => \_\_( 'Primary Menu', 'primary' ), ) ); **cover.php** With the code below within the `<nav> and </nav>` tags ``` <?php wp_nav_menu( array( 'theme_location' => 'top-menu', 'depth' => 2, 'container' => 'div', 'container_class' => 'collapse navbar-collapse', 'container_id' => 'bs-example-navbar-collapse-1', 'menu_class' => 'nav navbar-nav', 'fallback_cb' => 'WP_Bootstrap_Navwalker::fallback', 'walker' => new WP_Bootstrap_Navwalker(), ) ); ?> ``` When I save changes and reload my website, I get get the wp-bootstrap-navwalker page from github. I've checked the source of the page and see this at the footer: **Fatal error**: Uncaught Error: Class 'WP\_Bootstrap\_Navwalker' not found in C:\laragon\www\VzyulTech\wp-content\themes\Version2\index.php:17 Stack trace: #0 C:\laragon\www\VzyulTech\wp-includes\template-loader.php(106): include() #1 C:\laragon\www\VzyulTech\wp-blog-header.php(19): require\_once('C:\laragon\www\...') #2 C:\laragon\www\VzyulTech\index.php(17): require('C:\laragon\www\...') #3 {main} thrown in **C:\laragon\www\VzyulTech\wp-content\themes\Version2\index.php** on line **17** When I check line 17 it is the 'walker' => new WP\_Bootstrap\_Navwalker(), ``` wp_nav_menu( array( 'theme_location' => 'primary', 'depth' => 2, 'container' => 'div', 'container_class' => 'collapse navbar-collapse', 'container_id' => 'bs-example-navbar-collapse-1', 'menu_class' => 'nav navbar-nav', 'fallback_cb' => 'WP_Bootstrap_Navwalker::fallback', 'walker' => new WP_Bootstrap_Navwalker(), ) ); ``` any help is much appreciated.
Your `register_navwalker` function is loading `navwalker` with this line: ``` require_once get_template_directory() . './class-wp-bootstrap-navwalker.php'; ``` where you concatenate the path of the theme with this string: ``` './class-wp-bootstrap-navwalker.php' ``` and the dot there at the beginning is a problem. The result would look like this: ``` DOMAIN/wp-content/themes/THEME./class-wp-bootstrap-navwalker.php ``` remove the dot and it should find and load the script. **EDIT:** Also you shouldn't change your original post or question, but add to it. Otherwise comments and answers might not make sense anymore.
374,539
<p>I am learning about WordPress development. I ran into an issue but could not figure out what am I doing wrong</p> <p>I want to show all of the posts on a page using a custom template. I am following this tutorial <a href="https://developer.wordpress.org/themes/basics/the-loop/#blog-archive" rel="nofollow noreferrer">https://developer.wordpress.org/themes/basics/the-loop/#blog-archive</a></p> <p><strong>So far:</strong></p> <p>1: I have created a custom page template with the name of "homepage"</p> <p>2: I have created a page and assigned page template "homepage" and set that page as homepage from the settings panel.</p> <p>3: In the page template, I have added the below code</p> <pre><code>/* * Template Name: Homepage * Template Post Type: page */ get_header(); if ( have_posts() ) : while ( have_posts() ) : the_post(); the_title( '&lt;h2 style=&quot;color:#fff;&quot;&gt;', '&lt;/h2&gt;' ); the_post_thumbnail(); the_excerpt(); endwhile; else: _e( 'Sorry, no posts matched your criteria.', 'textdomain' ); endif; get_footer(); ?&gt; </code></pre> <p>The above code only displays the current page title and featured image, NOT all of the posts title and featured image.</p> <p> As per the documentation I am doing everything right, but on the frontend, it is not showing all of the posts, Any idea what I am doing wrong? </p>
[ { "answer_id": 374540, "author": "t2pe", "author_id": 106499, "author_profile": "https://wordpress.stackexchange.com/users/106499", "pm_score": -1, "selected": false, "text": "<p>When you use a Loop in a specific Page or Post, the loop contains data only from that single Page or Post. So...
2020/09/09
[ "https://wordpress.stackexchange.com/questions/374539", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/194371/" ]
I am learning about WordPress development. I ran into an issue but could not figure out what am I doing wrong I want to show all of the posts on a page using a custom template. I am following this tutorial <https://developer.wordpress.org/themes/basics/the-loop/#blog-archive> **So far:** 1: I have created a custom page template with the name of "homepage" 2: I have created a page and assigned page template "homepage" and set that page as homepage from the settings panel. 3: In the page template, I have added the below code ``` /* * Template Name: Homepage * Template Post Type: page */ get_header(); if ( have_posts() ) : while ( have_posts() ) : the_post(); the_title( '<h2 style="color:#fff;">', '</h2>' ); the_post_thumbnail(); the_excerpt(); endwhile; else: _e( 'Sorry, no posts matched your criteria.', 'textdomain' ); endif; get_footer(); ?> ``` The above code only displays the current page title and featured image, NOT all of the posts title and featured image. As per the documentation I am doing everything right, but on the frontend, it is not showing all of the posts, Any idea what I am doing wrong?
> > As per the documentation I am doing everything right, but on the > frontend, it is not showing all of the posts, Any idea what I am doing > wrong? > > > The documentation does not say to use a custom page template for displaying the blog archive. As shown in the [template hierarchy](https://developer.wordpress.org/themes/basics/template-hierarchy/#visual-overview) the template for your blog posts archive should be home.php, or index.php. Then in *that* template you add the loop as described at [your link](https://developer.wordpress.org/themes/basics/the-loop/#blog-archive): ``` <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); the_title( '<h2>', '</h2>' ); the_post_thumbnail(); the_excerpt(); endwhile; else: _e( 'Sorry, no posts matched your criteria.', 'textdomain' ); endif; ?> ``` This template should not have the `Template Name:` header, or be assigned to a page. Instead it will be applied automatically to whichever page you have selected as the latest posts page in *Settings > Reading*. Note that all templates in the template hierarchy use the same basic loop: ``` while ( have_posts() ) : the_post(); endwhile; ``` You do not query any posts from the template. WordPress automatically queries the correct posts, and the template's only job is to display whichever posts have been queried. Which template is used, and why, is determined by the template hierarchy, linked above.
374,555
<p>Is there any technical way to search post titles and return the results of the most used duplicated words in them?</p> <p>I.e Three articles in total:</p> <ul> <li>The quick brown fox jumps over the lazy dog</li> <li>A brown bag for the summer</li> <li>New record - Athlete jumps higher</li> </ul> <p>Most used words in post titles:</p> <ol> <li>Brown</li> <li>Jumps</li> </ol>
[ { "answer_id": 374540, "author": "t2pe", "author_id": 106499, "author_profile": "https://wordpress.stackexchange.com/users/106499", "pm_score": -1, "selected": false, "text": "<p>When you use a Loop in a specific Page or Post, the loop contains data only from that single Page or Post. So...
2020/09/09
[ "https://wordpress.stackexchange.com/questions/374555", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/151253/" ]
Is there any technical way to search post titles and return the results of the most used duplicated words in them? I.e Three articles in total: * The quick brown fox jumps over the lazy dog * A brown bag for the summer * New record - Athlete jumps higher Most used words in post titles: 1. Brown 2. Jumps
> > As per the documentation I am doing everything right, but on the > frontend, it is not showing all of the posts, Any idea what I am doing > wrong? > > > The documentation does not say to use a custom page template for displaying the blog archive. As shown in the [template hierarchy](https://developer.wordpress.org/themes/basics/template-hierarchy/#visual-overview) the template for your blog posts archive should be home.php, or index.php. Then in *that* template you add the loop as described at [your link](https://developer.wordpress.org/themes/basics/the-loop/#blog-archive): ``` <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); the_title( '<h2>', '</h2>' ); the_post_thumbnail(); the_excerpt(); endwhile; else: _e( 'Sorry, no posts matched your criteria.', 'textdomain' ); endif; ?> ``` This template should not have the `Template Name:` header, or be assigned to a page. Instead it will be applied automatically to whichever page you have selected as the latest posts page in *Settings > Reading*. Note that all templates in the template hierarchy use the same basic loop: ``` while ( have_posts() ) : the_post(); endwhile; ``` You do not query any posts from the template. WordPress automatically queries the correct posts, and the template's only job is to display whichever posts have been queried. Which template is used, and why, is determined by the template hierarchy, linked above.
374,569
<p>I know I can use <code>define('WP_POST_REVISIONS', 5);</code> to limit future post revisions to 5, but how would I go about purging all <em>existing</em> revisions except the latest 5?</p>
[ { "answer_id": 374540, "author": "t2pe", "author_id": 106499, "author_profile": "https://wordpress.stackexchange.com/users/106499", "pm_score": -1, "selected": false, "text": "<p>When you use a Loop in a specific Page or Post, the loop contains data only from that single Page or Post. So...
2020/09/09
[ "https://wordpress.stackexchange.com/questions/374569", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/49543/" ]
I know I can use `define('WP_POST_REVISIONS', 5);` to limit future post revisions to 5, but how would I go about purging all *existing* revisions except the latest 5?
> > As per the documentation I am doing everything right, but on the > frontend, it is not showing all of the posts, Any idea what I am doing > wrong? > > > The documentation does not say to use a custom page template for displaying the blog archive. As shown in the [template hierarchy](https://developer.wordpress.org/themes/basics/template-hierarchy/#visual-overview) the template for your blog posts archive should be home.php, or index.php. Then in *that* template you add the loop as described at [your link](https://developer.wordpress.org/themes/basics/the-loop/#blog-archive): ``` <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); the_title( '<h2>', '</h2>' ); the_post_thumbnail(); the_excerpt(); endwhile; else: _e( 'Sorry, no posts matched your criteria.', 'textdomain' ); endif; ?> ``` This template should not have the `Template Name:` header, or be assigned to a page. Instead it will be applied automatically to whichever page you have selected as the latest posts page in *Settings > Reading*. Note that all templates in the template hierarchy use the same basic loop: ``` while ( have_posts() ) : the_post(); endwhile; ``` You do not query any posts from the template. WordPress automatically queries the correct posts, and the template's only job is to display whichever posts have been queried. Which template is used, and why, is determined by the template hierarchy, linked above.
374,623
<p>Wordpress wpallimport plugin This filter allows modifying the option shown in the options type dropdown for import</p> <p>The function is as follow: I want to add $custom_types as string array.</p> <pre><code>function wpai_custom_types( $custom_types ) { // Modify the custom types to be shown on Step 1. $custom_types = array(&quot;woocommerce orders&quot; , &quot; posts&quot;) // Return the updated list. return $custom_types; } add_filter( 'pmxi_custom_types', 'wpai_custom_types', 10, 1 ); </code></pre> <p>But it won't work</p>
[ { "answer_id": 374540, "author": "t2pe", "author_id": 106499, "author_profile": "https://wordpress.stackexchange.com/users/106499", "pm_score": -1, "selected": false, "text": "<p>When you use a Loop in a specific Page or Post, the loop contains data only from that single Page or Post. So...
2020/09/10
[ "https://wordpress.stackexchange.com/questions/374623", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/194464/" ]
Wordpress wpallimport plugin This filter allows modifying the option shown in the options type dropdown for import The function is as follow: I want to add $custom\_types as string array. ``` function wpai_custom_types( $custom_types ) { // Modify the custom types to be shown on Step 1. $custom_types = array("woocommerce orders" , " posts") // Return the updated list. return $custom_types; } add_filter( 'pmxi_custom_types', 'wpai_custom_types', 10, 1 ); ``` But it won't work
> > As per the documentation I am doing everything right, but on the > frontend, it is not showing all of the posts, Any idea what I am doing > wrong? > > > The documentation does not say to use a custom page template for displaying the blog archive. As shown in the [template hierarchy](https://developer.wordpress.org/themes/basics/template-hierarchy/#visual-overview) the template for your blog posts archive should be home.php, or index.php. Then in *that* template you add the loop as described at [your link](https://developer.wordpress.org/themes/basics/the-loop/#blog-archive): ``` <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); the_title( '<h2>', '</h2>' ); the_post_thumbnail(); the_excerpt(); endwhile; else: _e( 'Sorry, no posts matched your criteria.', 'textdomain' ); endif; ?> ``` This template should not have the `Template Name:` header, or be assigned to a page. Instead it will be applied automatically to whichever page you have selected as the latest posts page in *Settings > Reading*. Note that all templates in the template hierarchy use the same basic loop: ``` while ( have_posts() ) : the_post(); endwhile; ``` You do not query any posts from the template. WordPress automatically queries the correct posts, and the template's only job is to display whichever posts have been queried. Which template is used, and why, is determined by the template hierarchy, linked above.
374,693
<p>I have a little non-standard WP dev environment, I use one WP core for all my projects and switch each project in core's wp-config.php just changing the <code>$project</code> variable (e.g. proj1, proj2, example...). Projects and core are separated and each project has its own DB, wp-content folder, wp-config-dev.php (DB credentials and table prefix), and wp-config.php (usual wp-config that I deploy on the server).</p> <pre class="lang-php prettyprint-override"><code>//core's wp-config.php &lt;?php $project = 'example'; define( 'WP_CONTENT_DIR', 'C:/dev/projects/'.$project.'/wp/wp-content' ); define( 'WP_CONTENT_URL', 'https://projects.folder/'.$project.'/wp/wp-content' ); include('C:/dev/projects/'.$project.'/wp/wp-config-dev.php'); if ( ! defined( 'ABSPATH' ) ) { define( 'ABSPATH', dirname( __FILE__ ) . '/' ); } require_once( ABSPATH . 'wp-settings.php' ); // custom functions include('custom.php'); </code></pre> <p>All my projects on the development environment have the same user and password (e.g. foo and bar) and I change them when I export DB when my project is ready to production, so my goal to switch each project just with changing <code>$project</code> and not login in every time cuz it is really annoying.</p> <p>When i switch beetwen projects i have always to log in again into switched project. In included <code>custom.php</code> file i have <code>wp_signon()</code> function that was worked on WP 4+ but since WP 5.0 it is stopped working. Earlier that approach automatically logged in each project and i even can't log out cuz it keep me logged on page reload :)</p> <pre class="lang-php prettyprint-override"><code>$current_user = wp_get_current_user(); if (!user_can( $current_user, 'administrator' )) { //without if(){} i have same behaviour $creds = array(); $creds['user_login'] = 'foo'; $creds['user_password'] = 'bar'; $creds['remember'] = false; wp_signon( $creds, false ); } </code></pre> <p>Now after the switch, I need to update the page again to the admin bar appear and when I go to the console it redirects me to wp-login.php where is user input had filled and the password input are empty.</p> <p><a href="https://i.stack.imgur.com/eohV2.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/eohV2.png" alt="enter image description here" /></a></p> <p>So how to make it always automatically logged in when I change the project and make that each session has no expiration time?</p> <p><strong>Note.</strong> I need to make it work only in the custom.php file that I include to core's wp-config, I don't need to make it in each project instance that I deploy on the server.</p> <hr /> <p><strong>Update</strong>. Now autologin works fine, the problem was in second parameter of the <code>wp_signon()</code> function, it should be true if you use HTTPS on your site.</p> <pre class="lang-php prettyprint-override"><code>//custom.php echo &quot;is_user_logged_in() — &quot;; var_dump(is_user_logged_in()); //this condition not working after switch project, have to reload page if (!is_user_logged_in()) { $creds = array(); $creds['user_login'] = 'foo'; $creds['user_password'] = 'bar'; $creds['remember'] = false; $user = wp_signon( $creds, true ); //set second parameter to true to enable secure cookies add_filter( 'auth_cookie_expiration', 'keep_me_logged_in_for_1_year' ); function keep_me_logged_in_for_1_year( $expirein ) { return 31556926; // 1 year in seconds } } </code></pre> <p>It always keep me logged in for current project and I haven't problem with redirection to wp-login page but when i switch to another project I still need to reload page to login and for the admin bar to appear.</p> <p><em>In drop down menu i switch project with changing <code>$project</code> var in core's config</em> <a href="https://i.stack.imgur.com/OmSSG.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/OmSSG.gif" alt="enter image description here" /></a></p> <p>How to login immediately and without reloads after changing <code>$project</code>? Is there a problem with that engine got another DB and wp-content folder?</p>
[ { "answer_id": 374755, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 2, "selected": false, "text": "<p>Here's one milder suggestion to try out, assuming different cookie domains, if you're using WordPress 5.5+</p...
2020/09/11
[ "https://wordpress.stackexchange.com/questions/374693", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/168832/" ]
I have a little non-standard WP dev environment, I use one WP core for all my projects and switch each project in core's wp-config.php just changing the `$project` variable (e.g. proj1, proj2, example...). Projects and core are separated and each project has its own DB, wp-content folder, wp-config-dev.php (DB credentials and table prefix), and wp-config.php (usual wp-config that I deploy on the server). ```php //core's wp-config.php <?php $project = 'example'; define( 'WP_CONTENT_DIR', 'C:/dev/projects/'.$project.'/wp/wp-content' ); define( 'WP_CONTENT_URL', 'https://projects.folder/'.$project.'/wp/wp-content' ); include('C:/dev/projects/'.$project.'/wp/wp-config-dev.php'); if ( ! defined( 'ABSPATH' ) ) { define( 'ABSPATH', dirname( __FILE__ ) . '/' ); } require_once( ABSPATH . 'wp-settings.php' ); // custom functions include('custom.php'); ``` All my projects on the development environment have the same user and password (e.g. foo and bar) and I change them when I export DB when my project is ready to production, so my goal to switch each project just with changing `$project` and not login in every time cuz it is really annoying. When i switch beetwen projects i have always to log in again into switched project. In included `custom.php` file i have `wp_signon()` function that was worked on WP 4+ but since WP 5.0 it is stopped working. Earlier that approach automatically logged in each project and i even can't log out cuz it keep me logged on page reload :) ```php $current_user = wp_get_current_user(); if (!user_can( $current_user, 'administrator' )) { //without if(){} i have same behaviour $creds = array(); $creds['user_login'] = 'foo'; $creds['user_password'] = 'bar'; $creds['remember'] = false; wp_signon( $creds, false ); } ``` Now after the switch, I need to update the page again to the admin bar appear and when I go to the console it redirects me to wp-login.php where is user input had filled and the password input are empty. [![enter image description here](https://i.stack.imgur.com/eohV2.png)](https://i.stack.imgur.com/eohV2.png) So how to make it always automatically logged in when I change the project and make that each session has no expiration time? **Note.** I need to make it work only in the custom.php file that I include to core's wp-config, I don't need to make it in each project instance that I deploy on the server. --- **Update**. Now autologin works fine, the problem was in second parameter of the `wp_signon()` function, it should be true if you use HTTPS on your site. ```php //custom.php echo "is_user_logged_in() — "; var_dump(is_user_logged_in()); //this condition not working after switch project, have to reload page if (!is_user_logged_in()) { $creds = array(); $creds['user_login'] = 'foo'; $creds['user_password'] = 'bar'; $creds['remember'] = false; $user = wp_signon( $creds, true ); //set second parameter to true to enable secure cookies add_filter( 'auth_cookie_expiration', 'keep_me_logged_in_for_1_year' ); function keep_me_logged_in_for_1_year( $expirein ) { return 31556926; // 1 year in seconds } } ``` It always keep me logged in for current project and I haven't problem with redirection to wp-login page but when i switch to another project I still need to reload page to login and for the admin bar to appear. *In drop down menu i switch project with changing `$project` var in core's config* [![enter image description here](https://i.stack.imgur.com/OmSSG.gif)](https://i.stack.imgur.com/OmSSG.gif) How to login immediately and without reloads after changing `$project`? Is there a problem with that engine got another DB and wp-content folder?
I found out my solution, I just need make an additional redirect to make `wp_signon()` work after I switch project. ```php if (!is_user_logged_in()) { $creds = array(); $creds['user_login'] = 'foo'; $creds['user_password'] = 'bar'; $creds['remember'] = false; $user = wp_signon( $creds, true ); add_filter( 'auth_cookie_expiration', 'keep_me_logged_in_for_1_year' ); function keep_me_logged_in_for_1_year( $expirein ) { return 31556926; // 1 year in seconds } //add redirection header("Location: "."https://".$_SERVER['HTTP_HOST']); exit(); } ```
374,695
<p>Using Basic Authentication as an Administrator, I am getting an error code <code>401 Unauthorized : [rest_cannot_view_plugins] Sorry, you are not allowed to manage plugins for this site.</code> error when I attempt to access the GET <code>/wp-json/wp/v2/plugins</code> endpoint of my server. I can pull Post and Page info with no problem, but when I query against the plugins, I'm getting the 401 error. I've confirmed that the userid used in the API call should be able to manage plugins using the CLI tool:</p> <pre><code># wp user list-caps $USER | grep plugin activate_plugins edit_plugins update_plugins delete_plugins install_plugins </code></pre> <p>Any pointers would be appreciated.</p>
[ { "answer_id": 374700, "author": "Adam", "author_id": 13418, "author_profile": "https://wordpress.stackexchange.com/users/13418", "pm_score": 3, "selected": true, "text": "<h3>SUGGESTIONS</h3>\n<p>I suggest the following:</p>\n<ul>\n<li>first ensure you are running WordPress version <cod...
2020/09/11
[ "https://wordpress.stackexchange.com/questions/374695", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/194523/" ]
Using Basic Authentication as an Administrator, I am getting an error code `401 Unauthorized : [rest_cannot_view_plugins] Sorry, you are not allowed to manage plugins for this site.` error when I attempt to access the GET `/wp-json/wp/v2/plugins` endpoint of my server. I can pull Post and Page info with no problem, but when I query against the plugins, I'm getting the 401 error. I've confirmed that the userid used in the API call should be able to manage plugins using the CLI tool: ``` # wp user list-caps $USER | grep plugin activate_plugins edit_plugins update_plugins delete_plugins install_plugins ``` Any pointers would be appreciated.
### SUGGESTIONS I suggest the following: * first ensure you are running WordPress version `5.5.*` as this version adds the endpoints for `/wp/v2/plugins` see: [New and modified REST API endpoints in WordPress 5.5](https://make.wordpress.org/core/2020/07/16/new-and-modified-rest-api-endpoints-in-wordpress-5-5/) * using basic authentication issue a request as per the following using curl ``` curl --user username:password https://example.com/wp-json ``` The first request should succeed regardless because it will likely be (unless you've done otherwise) unsecured. Then try: ``` curl --user username:password https://example.com/wp-json/wp/v2/plugins ``` If this fails you may not have the means to issue basic authentication requests, so add it for the purpose of testing. Install the following: <https://github.com/WP-API/Basic-Auth/blob/master/basic-auth.php> I'd simply recommend placing that file in your site `wp-content/mu-plugins` directory. If the directory does not exist, create it first. Then repeat the curl request: ``` curl --user username:password https://example.com/wp-json/wp/v2/plugins ``` If you are authenticated correctly, you should receive back a response appropriate for that endpoint. --- ### TESTS * I have tested this via first trying on an install `5.3.*` and the route does not exist (as we should expect) * I have tested this on an install `5.5.*` and the route does exist as expected but requires an authentication method (for testing I have used Basic Authentication) and you can read more about Authentication methods in general here: <https://developer.wordpress.org/rest-api/using-the-rest-api/authentication/> ### NOTE (on authentication): Depending on what you are trying to achieve you may benefit from more robust authentication like OAuth or Application Passwords (see <https://wordpress.org/plugins/application-passwords/>) but here the choice is ultimately yours, Basic Authentication may suffice, but be mindful of security considerations around storing plain text username and passwords for the given user making the request. You may want to create a specific use with just enough permissions/capabilities for this purpose if relying on Basic Authentication. Useful reading: * <https://developer.wordpress.org/rest-api/> * <https://developer.wordpress.org/rest-api/using-the-rest-api/authentication/> * <https://github.com/WP-API/Basic-Auth/blob/master/basic-auth.php>
374,790
<p>I am creating a page template in Wordpress that displays multiple tags that are in a particular category. I have this working, but now I want to have the number of posts within each tag that is displayed as well like if I had a tag called apples with 5 posts it would look like this:</p> <pre><code>Apples(5) </code></pre> <p>As of now it just shows <code>Apples</code></p> <p>Here is my code I want to modify:</p> <pre class="lang-php prettyprint-override"><code> &lt;?php if (is_category()){ $cat = get_query_var('cat'); $yourcat = get_category ($cat); } $tag_IDs = array(); query_posts('category_name=health'); if (have_posts()) : while (have_posts()) : the_post(); $posttags = get_the_tags(); if ($posttags): foreach($posttags as $tag) { if (!in_array($tag-&gt;term_id , $tag_IDs)): $tag_IDs[] = $tag-&gt;term_id; $tag_names[$tag-&gt;term_id] = $tag-&gt;name; endif; } endif; endwhile; endif; wp_reset_query(); echo &quot;&lt;ul&gt;&quot;; foreach($tag_IDs as $tag_ID){ echo '&lt;a href=&quot;'.get_tag_link($tag_ID).'&quot;&gt;'.$tag_names[$tag_ID].'&lt;/a&gt;'; } echo &quot;&lt;/ul&gt;&quot;; ?&gt; </code></pre> <p><a href="https://i.stack.imgur.com/f923K.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/f923K.png" alt="enter image description here" /></a> <a href="https://i.stack.imgur.com/0C6iM.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/0C6iM.png" alt="enter image description here" /></a></p>
[ { "answer_id": 374792, "author": "Luis Chuquilin", "author_id": 194591, "author_profile": "https://wordpress.stackexchange.com/users/194591", "pm_score": 1, "selected": false, "text": "<pre><code>function wp_get_postcount($id)\n{\n $contador = 0;\n $taxonomia = 'categoria';\n $a...
2020/09/13
[ "https://wordpress.stackexchange.com/questions/374790", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/60779/" ]
I am creating a page template in Wordpress that displays multiple tags that are in a particular category. I have this working, but now I want to have the number of posts within each tag that is displayed as well like if I had a tag called apples with 5 posts it would look like this: ``` Apples(5) ``` As of now it just shows `Apples` Here is my code I want to modify: ```php <?php if (is_category()){ $cat = get_query_var('cat'); $yourcat = get_category ($cat); } $tag_IDs = array(); query_posts('category_name=health'); if (have_posts()) : while (have_posts()) : the_post(); $posttags = get_the_tags(); if ($posttags): foreach($posttags as $tag) { if (!in_array($tag->term_id , $tag_IDs)): $tag_IDs[] = $tag->term_id; $tag_names[$tag->term_id] = $tag->name; endif; } endif; endwhile; endif; wp_reset_query(); echo "<ul>"; foreach($tag_IDs as $tag_ID){ echo '<a href="'.get_tag_link($tag_ID).'">'.$tag_names[$tag_ID].'</a>'; } echo "</ul>"; ?> ``` [![enter image description here](https://i.stack.imgur.com/f923K.png)](https://i.stack.imgur.com/f923K.png) [![enter image description here](https://i.stack.imgur.com/0C6iM.png)](https://i.stack.imgur.com/0C6iM.png)
Here is the code I rewrote that solved my problem. It loops through a category and shows how many articles all the tags inside the category has. ``` <?php $custom_query = new WP_Query( 'posts_per_page=-1&category_name=health' ); if ( $custom_query->have_posts() ) : $all_tags = array(); while ( $custom_query->have_posts() ) : $custom_query->the_post(); $posttags = get_the_tags(); if ( $posttags ) { foreach($posttags as $tag) { $all_tags[$tag->term_id]['id'] = $tag->term_id; $all_tags[$tag->term_id]['name'] = $tag->name; $all_tags[$tag->term_id]['count']++; } } endwhile; endif; $tags_arr = array_unique( $all_tags ); $tags_str = implode( ",", $tags_arr ); $args = array( 'smallest' => 12, 'largest' => 12, 'unit' => 'px', 'number' => 0, 'format' => 'list', 'include' => $tags_str ); foreach ( $all_tags as $tag_ID => $tag ) { echo '<a href="'.get_tag_link($tag_ID).'">' . $tag['name'] . '</a> ('; echo $tag['count'] . ')<br>'; } wp_reset_query() ?> ```
374,953
<p>I need to list all custom terms (brands) that are associated with products from the category that is currently being viewed. E.g. I have these brands created:</p> <ul> <li>Shirt Brand A</li> <li>Shirt Brand B</li> <li>Shirt Brand C</li> <li>Jeans Brand A</li> <li>Jeans Brand B</li> </ul> <p>On 'Shirts' category page, only Shirts Brands <code>A</code>, <code>B</code> and <code>C</code> are displayed.</p> <p>This is how I did it:</p> <pre><code>$args = array( 'taxonomy' =&gt; 'brand', 'orderby' =&gt; 'count', 'order' =&gt; 'DESC', 'hide_empty' =&gt; false ); $brands = get_terms($args); foreach($brands as $brand) { if(is_product_category()) { $cat_id = get_queried_object_id(); $count_args = array( 'post_type' =&gt; 'product', 'post_status' =&gt; 'publish', 'tax_query' =&gt; array( array( 'taxonomy' =&gt; 'product_cat', 'field' =&gt; 'term_id', 'terms' =&gt; $cat_id, 'operator' =&gt; 'IN' ), array( 'taxonomy' =&gt; 'brand', 'field' =&gt; 'slug', 'terms' =&gt; $brand-&gt;slug, 'operator' =&gt; 'IN' ) ) ); $count_products = new WP_Query($count_args); if($count_products-&gt;post_count &lt;= 0) continue; // Skip if this query contains zero products // Display brand that has at least 1 product in this category display_brand(); } } </code></pre> <p>Of course it works, however with 300+ brands created it sometimes takes 0,5 - 1,5 seconds for this loop to get processed, which is unnecessary lot. AFAIK there is no direct database relation between terms and product categories (only number of posts for each term), but is there a better way to do this with better performance?</p>
[ { "answer_id": 374960, "author": "DevelJoe", "author_id": 188571, "author_profile": "https://wordpress.stackexchange.com/users/188571", "pm_score": 1, "selected": false, "text": "<p>Define your terms as <strong>hierarchical</strong> custom taxonomies, as child taxonomies from the corresp...
2020/09/16
[ "https://wordpress.stackexchange.com/questions/374953", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/138610/" ]
I need to list all custom terms (brands) that are associated with products from the category that is currently being viewed. E.g. I have these brands created: * Shirt Brand A * Shirt Brand B * Shirt Brand C * Jeans Brand A * Jeans Brand B On 'Shirts' category page, only Shirts Brands `A`, `B` and `C` are displayed. This is how I did it: ``` $args = array( 'taxonomy' => 'brand', 'orderby' => 'count', 'order' => 'DESC', 'hide_empty' => false ); $brands = get_terms($args); foreach($brands as $brand) { if(is_product_category()) { $cat_id = get_queried_object_id(); $count_args = array( 'post_type' => 'product', 'post_status' => 'publish', 'tax_query' => array( array( 'taxonomy' => 'product_cat', 'field' => 'term_id', 'terms' => $cat_id, 'operator' => 'IN' ), array( 'taxonomy' => 'brand', 'field' => 'slug', 'terms' => $brand->slug, 'operator' => 'IN' ) ) ); $count_products = new WP_Query($count_args); if($count_products->post_count <= 0) continue; // Skip if this query contains zero products // Display brand that has at least 1 product in this category display_brand(); } } ``` Of course it works, however with 300+ brands created it sometimes takes 0,5 - 1,5 seconds for this loop to get processed, which is unnecessary lot. AFAIK there is no direct database relation between terms and product categories (only number of posts for each term), but is there a better way to do this with better performance?
To fine-tune DevelJoe's answer a bit more, you could access the queried posts from the global `$wp_query` instead of doing an extra `WP_Query`. ``` // make the current query available from global variable global $wp_query; // helper variable $brands = array(); // loop queried posts foreach ( $wp_query->posts as $queried_post ) { // check if they have terms from custom taxonomy $current_post_brands = get_the_terms( $queried_post, 'brands' ); // post object accepted here also, not just ID if ( ! is_wp_error( $current_post_brands ) && $current_post_brands ) { // push found brands to helper variable foreach ( $current_post_brands as $current_post_brand ) { // avoid having same brands multiple time in the helper variable if ( ! isset( $brands[$current_post_brand->term_id] ) ) { $brands[$current_post_brand->term_id] = $current_post_brand; } } } } // do something with the brand terms (WP_Term) foreach ( $brands as $brand_id => $brand_term ) { // yay? } ``` This is probably a faster way, because WP automatically caches the terms of the queried posts - to my undestanding. This caching is dicussed for example here, [Explanation of update\_post\_(meta/term)\_cache](https://wordpress.stackexchange.com/questions/215871/explanation-of-update-post-meta-term-cache) --- **EDIT 23.9.2020** (*Facepalm*) Let me try this again... One way could be to first query all the posts in the current category. Then loop found posts to check their brand terms. Finally spit out an array of unique brand terms. Optionally you could also save the result into a transient so that the querying and looping doesn't run on every page load, thus saving some server resources. ``` function helper_get_brands_in_category( int $cat_id ) { $transient = get_transient( 'brands_in_category_' . $cat_id ); if ( $transient ) { return $transient; } $args = array( 'post_type' => 'product', 'posts_per_page' => 1000, // is this enough? 'post_status' => 'publish', 'no_found_rows' => true, 'update_post_meta_cache' => false, // not needed in this case 'fields' => 'ids', // not all post data needed here 'tax_query' => array( array( 'taxonomy' => 'product_cat', 'field' => 'term_id', 'terms' => $cat_id, ) ), ); $query = new WP_Query( $args ); $brands = array(); foreach ($query->posts as $post_id) { $post_brands = get_the_terms( $post_id, 'brands' ); if ( ! is_wp_error( $post_brands ) && $post_brands ) { foreach ( $post_brands as $post_brand ) { if ( ! isset( $brands[$post_brand->term_id] ) ) { $brands[$post_brand->term_id] = $post_brand; } } } } set_transient( 'brands_in_category_' . $cat_id, $brands, WEEK_IN_SECONDS ); // change expiration date as needed return $brands; } // Usage $brands_in_category = helper_get_brands_in_category( get_queried_object_id() ); ``` If you save the brands into transients, then you may also want to invalidate the transients whenever new brands are added. Something along these lines, ``` function clear_brands_in_category_transients( $term_id, $tt_id ) { $product_cats = get_terms( array( 'taxonomy' => 'product_cat', 'hide_empty' => false, 'fields' => 'ids', ) ); if ( ! is_wp_error( $product_cats ) && $product_cats ) { foreach ($product_cats as $cat_id) { delete_transient( 'brands_in_category_' . $cat_id ); } } } add_action( 'create_brands', 'clear_brands_in_category_transients', 10, 2 ); ``` I used the [create\_{$taxonomy}](https://developer.wordpress.org/reference/hooks/create_taxonomy/) hook above.
374,975
<p>I have just deployed the Wordpress application on my Kubernetes cluster following the instructions from <a href="https://kubernetes.io/docs/tutorials/stateful-application/mysql-wordpress-persistent-volume/" rel="nofollow noreferrer">https://kubernetes.io/docs/tutorials/stateful-application/mysql-wordpress-persistent-volume/</a></p> <p>Now I would like to populate the Wordpress database with a lot of posts for testing purposes. I do not really care about the content of these posts. As far as I am concerned they can be completely random. All I care that there are a lot of them.</p> <p>Is there a way to do it?</p>
[ { "answer_id": 374960, "author": "DevelJoe", "author_id": 188571, "author_profile": "https://wordpress.stackexchange.com/users/188571", "pm_score": 1, "selected": false, "text": "<p>Define your terms as <strong>hierarchical</strong> custom taxonomies, as child taxonomies from the corresp...
2020/09/16
[ "https://wordpress.stackexchange.com/questions/374975", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/194759/" ]
I have just deployed the Wordpress application on my Kubernetes cluster following the instructions from <https://kubernetes.io/docs/tutorials/stateful-application/mysql-wordpress-persistent-volume/> Now I would like to populate the Wordpress database with a lot of posts for testing purposes. I do not really care about the content of these posts. As far as I am concerned they can be completely random. All I care that there are a lot of them. Is there a way to do it?
To fine-tune DevelJoe's answer a bit more, you could access the queried posts from the global `$wp_query` instead of doing an extra `WP_Query`. ``` // make the current query available from global variable global $wp_query; // helper variable $brands = array(); // loop queried posts foreach ( $wp_query->posts as $queried_post ) { // check if they have terms from custom taxonomy $current_post_brands = get_the_terms( $queried_post, 'brands' ); // post object accepted here also, not just ID if ( ! is_wp_error( $current_post_brands ) && $current_post_brands ) { // push found brands to helper variable foreach ( $current_post_brands as $current_post_brand ) { // avoid having same brands multiple time in the helper variable if ( ! isset( $brands[$current_post_brand->term_id] ) ) { $brands[$current_post_brand->term_id] = $current_post_brand; } } } } // do something with the brand terms (WP_Term) foreach ( $brands as $brand_id => $brand_term ) { // yay? } ``` This is probably a faster way, because WP automatically caches the terms of the queried posts - to my undestanding. This caching is dicussed for example here, [Explanation of update\_post\_(meta/term)\_cache](https://wordpress.stackexchange.com/questions/215871/explanation-of-update-post-meta-term-cache) --- **EDIT 23.9.2020** (*Facepalm*) Let me try this again... One way could be to first query all the posts in the current category. Then loop found posts to check their brand terms. Finally spit out an array of unique brand terms. Optionally you could also save the result into a transient so that the querying and looping doesn't run on every page load, thus saving some server resources. ``` function helper_get_brands_in_category( int $cat_id ) { $transient = get_transient( 'brands_in_category_' . $cat_id ); if ( $transient ) { return $transient; } $args = array( 'post_type' => 'product', 'posts_per_page' => 1000, // is this enough? 'post_status' => 'publish', 'no_found_rows' => true, 'update_post_meta_cache' => false, // not needed in this case 'fields' => 'ids', // not all post data needed here 'tax_query' => array( array( 'taxonomy' => 'product_cat', 'field' => 'term_id', 'terms' => $cat_id, ) ), ); $query = new WP_Query( $args ); $brands = array(); foreach ($query->posts as $post_id) { $post_brands = get_the_terms( $post_id, 'brands' ); if ( ! is_wp_error( $post_brands ) && $post_brands ) { foreach ( $post_brands as $post_brand ) { if ( ! isset( $brands[$post_brand->term_id] ) ) { $brands[$post_brand->term_id] = $post_brand; } } } } set_transient( 'brands_in_category_' . $cat_id, $brands, WEEK_IN_SECONDS ); // change expiration date as needed return $brands; } // Usage $brands_in_category = helper_get_brands_in_category( get_queried_object_id() ); ``` If you save the brands into transients, then you may also want to invalidate the transients whenever new brands are added. Something along these lines, ``` function clear_brands_in_category_transients( $term_id, $tt_id ) { $product_cats = get_terms( array( 'taxonomy' => 'product_cat', 'hide_empty' => false, 'fields' => 'ids', ) ); if ( ! is_wp_error( $product_cats ) && $product_cats ) { foreach ($product_cats as $cat_id) { delete_transient( 'brands_in_category_' . $cat_id ); } } } add_action( 'create_brands', 'clear_brands_in_category_transients', 10, 2 ); ``` I used the [create\_{$taxonomy}](https://developer.wordpress.org/reference/hooks/create_taxonomy/) hook above.
375,049
<p>There is a website where we use WooCommerce infrastructure. I have products for which I use variations, and I want to make variations like the sample site below. When the customer selects the x option from the product with the x y z option, I want the number of names and the price of the checkbox field that I have determined on the product page. Can I do this with a ready-made plugin? Or do you have any suggestions? Thank you. Sample site: <a href="https://www.bstkafes.com/index.php?page=urunler&amp;urun-grup=k-26&amp;urun=41" rel="nofollow noreferrer">https://www.bstkafes.com/index.php?page=urunler&amp;urun-grup=k-26&amp;urun=41</a></p>
[ { "answer_id": 374960, "author": "DevelJoe", "author_id": 188571, "author_profile": "https://wordpress.stackexchange.com/users/188571", "pm_score": 1, "selected": false, "text": "<p>Define your terms as <strong>hierarchical</strong> custom taxonomies, as child taxonomies from the corresp...
2020/09/18
[ "https://wordpress.stackexchange.com/questions/375049", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/194805/" ]
There is a website where we use WooCommerce infrastructure. I have products for which I use variations, and I want to make variations like the sample site below. When the customer selects the x option from the product with the x y z option, I want the number of names and the price of the checkbox field that I have determined on the product page. Can I do this with a ready-made plugin? Or do you have any suggestions? Thank you. Sample site: <https://www.bstkafes.com/index.php?page=urunler&urun-grup=k-26&urun=41>
To fine-tune DevelJoe's answer a bit more, you could access the queried posts from the global `$wp_query` instead of doing an extra `WP_Query`. ``` // make the current query available from global variable global $wp_query; // helper variable $brands = array(); // loop queried posts foreach ( $wp_query->posts as $queried_post ) { // check if they have terms from custom taxonomy $current_post_brands = get_the_terms( $queried_post, 'brands' ); // post object accepted here also, not just ID if ( ! is_wp_error( $current_post_brands ) && $current_post_brands ) { // push found brands to helper variable foreach ( $current_post_brands as $current_post_brand ) { // avoid having same brands multiple time in the helper variable if ( ! isset( $brands[$current_post_brand->term_id] ) ) { $brands[$current_post_brand->term_id] = $current_post_brand; } } } } // do something with the brand terms (WP_Term) foreach ( $brands as $brand_id => $brand_term ) { // yay? } ``` This is probably a faster way, because WP automatically caches the terms of the queried posts - to my undestanding. This caching is dicussed for example here, [Explanation of update\_post\_(meta/term)\_cache](https://wordpress.stackexchange.com/questions/215871/explanation-of-update-post-meta-term-cache) --- **EDIT 23.9.2020** (*Facepalm*) Let me try this again... One way could be to first query all the posts in the current category. Then loop found posts to check their brand terms. Finally spit out an array of unique brand terms. Optionally you could also save the result into a transient so that the querying and looping doesn't run on every page load, thus saving some server resources. ``` function helper_get_brands_in_category( int $cat_id ) { $transient = get_transient( 'brands_in_category_' . $cat_id ); if ( $transient ) { return $transient; } $args = array( 'post_type' => 'product', 'posts_per_page' => 1000, // is this enough? 'post_status' => 'publish', 'no_found_rows' => true, 'update_post_meta_cache' => false, // not needed in this case 'fields' => 'ids', // not all post data needed here 'tax_query' => array( array( 'taxonomy' => 'product_cat', 'field' => 'term_id', 'terms' => $cat_id, ) ), ); $query = new WP_Query( $args ); $brands = array(); foreach ($query->posts as $post_id) { $post_brands = get_the_terms( $post_id, 'brands' ); if ( ! is_wp_error( $post_brands ) && $post_brands ) { foreach ( $post_brands as $post_brand ) { if ( ! isset( $brands[$post_brand->term_id] ) ) { $brands[$post_brand->term_id] = $post_brand; } } } } set_transient( 'brands_in_category_' . $cat_id, $brands, WEEK_IN_SECONDS ); // change expiration date as needed return $brands; } // Usage $brands_in_category = helper_get_brands_in_category( get_queried_object_id() ); ``` If you save the brands into transients, then you may also want to invalidate the transients whenever new brands are added. Something along these lines, ``` function clear_brands_in_category_transients( $term_id, $tt_id ) { $product_cats = get_terms( array( 'taxonomy' => 'product_cat', 'hide_empty' => false, 'fields' => 'ids', ) ); if ( ! is_wp_error( $product_cats ) && $product_cats ) { foreach ($product_cats as $cat_id) { delete_transient( 'brands_in_category_' . $cat_id ); } } } add_action( 'create_brands', 'clear_brands_in_category_transients', 10, 2 ); ``` I used the [create\_{$taxonomy}](https://developer.wordpress.org/reference/hooks/create_taxonomy/) hook above.
375,160
<p>I work on a project that shows some travels (depending on the destination category). I try to sort the travels on the start date (var_confirmed_date) but the result is the same as no sorting.</p> <p>Here is my query:</p> <pre><code>`$args = array( 'posts_per_page' =&gt; -1, 'post_type' =&gt; 'product', 'meta_value' =&gt; 'meta_value', 'meta_key' =&gt; 'var_confirmed_date', 'order' =&gt; 'ASC', 'meta_type' =&gt; 'DATE', 'tax_query' =&gt; array( array( 'taxonomy' =&gt; 'destination', 'field' =&gt; 'id', 'terms' =&gt; array($t_id) ) ), 'meta_query' =&gt; array( array( 'key' =&gt; 'var_confirmed_date', 'value' =&gt; date(&quot;Y-m-d&quot;,time()), 'compare' =&gt; '&gt;=', 'type' =&gt; 'DATE', ), ), ); $loop = new WP_Query( $args );` </code></pre> <p>Any idea to make it work correctly?</p> <p>Thanks.</p>
[ { "answer_id": 375151, "author": "Cyclonecode", "author_id": 14870, "author_profile": "https://wordpress.stackexchange.com/users/14870", "pm_score": 0, "selected": false, "text": "<p>You will need to make sure so you have the redis php extension installed and enabled. You can check the l...
2020/09/20
[ "https://wordpress.stackexchange.com/questions/375160", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/194888/" ]
I work on a project that shows some travels (depending on the destination category). I try to sort the travels on the start date (var\_confirmed\_date) but the result is the same as no sorting. Here is my query: ``` `$args = array( 'posts_per_page' => -1, 'post_type' => 'product', 'meta_value' => 'meta_value', 'meta_key' => 'var_confirmed_date', 'order' => 'ASC', 'meta_type' => 'DATE', 'tax_query' => array( array( 'taxonomy' => 'destination', 'field' => 'id', 'terms' => array($t_id) ) ), 'meta_query' => array( array( 'key' => 'var_confirmed_date', 'value' => date("Y-m-d",time()), 'compare' => '>=', 'type' => 'DATE', ), ), ); $loop = new WP_Query( $args );` ``` Any idea to make it work correctly? Thanks.
The file `wp-content/object-cache.php` is one of the [dropins](https://wpengineer.com/2500/wordpress-dropins/) – PHP files with custom code that are not plugins. It is used when you are using a [persistent object cache plugin](https://codex.wordpress.org/Class_Reference/WP_Object_Cache#Persistent_Cache_Plugins), and it will be loaded automatically. Normally the plugin will create that file. But if you move all the files without the plugin, the code in that file doesn't work anymore, and you get your error message. So you either have to delete the file, or install the plugin again. In this case probably the [Redis Object Cache](https://wordpress.org/plugins/redis-cache/) plugin.
375,198
<p>I'm trying to use a REST filter to require a certain parameter is set.</p> <p>Using custom taxonomies and custom posts I've been able to make it so when I request</p> <pre><code>/wp-json/wp/v2/car?visible_to=123 </code></pre> <p>That the only <code>Car</code>s that come back are ones with a <code>visible_to</code> taxonomy of 123.</p> <p>However when someone asks for</p> <pre><code>/wp-json/wp/v2/car </code></pre> <p>I want to throw an error, saying that ?visible_to needs to be set.</p> <p>I've tried hooking into <code>rest_index</code>, <code>rest_pre_dispatch</code>, and some others. Each only fires when I have <code>?visible_to</code> set in the URL, without them the hooks don't fire.</p> <p>For example, I would expect this to fire on every REST request</p> <pre><code>add_filter( 'rest_pre_dispatch','to_limit_access', 1, 3); function to_limit_access($args, $request, $context) { return new WP_Error( 'rest_disabled', __( 'The REST API is disabled on this site.' ), array( 'status' =&gt; 404 ) ); } </code></pre> <p>But it will only return a WP_Error on</p> <pre><code>/wp-json/wp/v2/car?visible_to=123 </code></pre> <p>Both</p> <pre><code>/wp-json/wp/v2/car </code></pre> <p>And</p> <pre><code>/wp-json/wp/v2/car/6 </code></pre> <p>Run without that filter being hit.</p> <p>Can someone explain why this would be the case and what I can do to avoid it?</p> <p>I've also tried specific filters like <code>rest_prepare_car</code> but I couldn't get it to fire at all.</p>
[ { "answer_id": 375200, "author": "Toby", "author_id": 1213, "author_profile": "https://wordpress.stackexchange.com/users/1213", "pm_score": 0, "selected": false, "text": "<p>In turns out we had a caching plugin enabled that was getting in the way of some requests but not others, leading ...
2020/09/21
[ "https://wordpress.stackexchange.com/questions/375198", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/1213/" ]
I'm trying to use a REST filter to require a certain parameter is set. Using custom taxonomies and custom posts I've been able to make it so when I request ``` /wp-json/wp/v2/car?visible_to=123 ``` That the only `Car`s that come back are ones with a `visible_to` taxonomy of 123. However when someone asks for ``` /wp-json/wp/v2/car ``` I want to throw an error, saying that ?visible\_to needs to be set. I've tried hooking into `rest_index`, `rest_pre_dispatch`, and some others. Each only fires when I have `?visible_to` set in the URL, without them the hooks don't fire. For example, I would expect this to fire on every REST request ``` add_filter( 'rest_pre_dispatch','to_limit_access', 1, 3); function to_limit_access($args, $request, $context) { return new WP_Error( 'rest_disabled', __( 'The REST API is disabled on this site.' ), array( 'status' => 404 ) ); } ``` But it will only return a WP\_Error on ``` /wp-json/wp/v2/car?visible_to=123 ``` Both ``` /wp-json/wp/v2/car ``` And ``` /wp-json/wp/v2/car/6 ``` Run without that filter being hit. Can someone explain why this would be the case and what I can do to avoid it? I've also tried specific filters like `rest_prepare_car` but I couldn't get it to fire at all.
If you want a parameter to be required for a post type's REST API endpoint you can use the [`rest_{$this->post_type}_collection_params`](https://developer.wordpress.org/reference/hooks/rest_this-post_type_collection_params/) filter to filter the [`$args`](https://developer.wordpress.org/rest-api/extending-the-rest-api/adding-custom-endpoints/#arguments) of the `GET` endpoint: ``` add_filter( 'rest_car_collection_params', function( array $query_params ) { $query_params['visible_to']['required'] = true; return $query_params; } ); ```
375,220
<p>I am fetching data from an API using JS. How can I use this data with PHP. More specifically, assign this data to a <code>$_SESSION</code> variable in PHP so that I can use it in other pages(templates files)?</p>
[ { "answer_id": 375200, "author": "Toby", "author_id": 1213, "author_profile": "https://wordpress.stackexchange.com/users/1213", "pm_score": 0, "selected": false, "text": "<p>In turns out we had a caching plugin enabled that was getting in the way of some requests but not others, leading ...
2020/09/21
[ "https://wordpress.stackexchange.com/questions/375220", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/148212/" ]
I am fetching data from an API using JS. How can I use this data with PHP. More specifically, assign this data to a `$_SESSION` variable in PHP so that I can use it in other pages(templates files)?
If you want a parameter to be required for a post type's REST API endpoint you can use the [`rest_{$this->post_type}_collection_params`](https://developer.wordpress.org/reference/hooks/rest_this-post_type_collection_params/) filter to filter the [`$args`](https://developer.wordpress.org/rest-api/extending-the-rest-api/adding-custom-endpoints/#arguments) of the `GET` endpoint: ``` add_filter( 'rest_car_collection_params', function( array $query_params ) { $query_params['visible_to']['required'] = true; return $query_params; } ); ```
375,267
<h2>Background</h2> <p>I need to retrieve terms for a post in an arbitrary site on a multisite network. This is not necessarily the site that the WP instance is running in at that moment. <code>wp_get_object_terms()</code> requires the taxonomy for which to retrieve the terms. So, to retrieve all terms for all taxonomies, it would be necessary to first retrieve the taxonomies. This does not appear to be possible, as the taxonomies that are registered by plugins may not be getting registered on the <em>current</em> (original) site that the instance is running in, because the plugins themselves would not be active on that site.</p> <h2>Question</h2> <p>How can I retrieve all taxonomies of an <em>arbitrary</em> site <em>programmatically</em>? In other words, given that I have a site <code>$siteId</code>, how can I retrieve all taxonomies on that site?</p> <p>Alternatively, how can I retrieve all taxonomy terms for a post in an <em>arbitrary</em> site <em>programmatically</em>? In other words, given post <code>$post</code> and site <code>$siteId</code>, how can I retrieve all terms for all taxonomies of that post in that site?</p>
[ { "answer_id": 375278, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 2, "selected": false, "text": "<blockquote>\n<p>how can I retrieve all taxonomy terms for a post in an arbitrary site programmatically? In oth...
2020/09/22
[ "https://wordpress.stackexchange.com/questions/375267", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/64825/" ]
Background ---------- I need to retrieve terms for a post in an arbitrary site on a multisite network. This is not necessarily the site that the WP instance is running in at that moment. `wp_get_object_terms()` requires the taxonomy for which to retrieve the terms. So, to retrieve all terms for all taxonomies, it would be necessary to first retrieve the taxonomies. This does not appear to be possible, as the taxonomies that are registered by plugins may not be getting registered on the *current* (original) site that the instance is running in, because the plugins themselves would not be active on that site. Question -------- How can I retrieve all taxonomies of an *arbitrary* site *programmatically*? In other words, given that I have a site `$siteId`, how can I retrieve all taxonomies on that site? Alternatively, how can I retrieve all taxonomy terms for a post in an *arbitrary* site *programmatically*? In other words, given post `$post` and site `$siteId`, how can I retrieve all terms for all taxonomies of that post in that site?
> > how can I retrieve all taxonomy terms for a post in an arbitrary site programmatically? In other words, given post $post and site $siteId, how can I retrieve all terms for all taxonomies of that post in that site? > > > You can do this by omitting the taxonomy from `WP_Term_Query`: ```php $query = new WP_Term_Query( [ 'object_ids' => [ $post_id ] ] ); $terms = $query->get_terms(); ``` Note that this gives you no information that the taxonomys of those terms were registered with, so permalinks and labels may not be available > > How can I retrieve all taxonomies of an arbitrary site? In other words, given that I have a site $siteId, how can I retrieve all taxonomies on that site? > > > **Unfortunately, no, there is no API or function call in PHP that will give you this information.** Generally needing this information is a sign that something has gone wrong at the high level architecture, and that simpler easier solutions exist. Every decision has trade offs and built in constraints, and this is one of those situations where breaching a constraint requires a tradeoff or an architectural change. The root problem is that `switch_to_blog` changes the tables and globals, but it doesn't load any code from the other blog being switched to, so we need to recover what the registered posts types and taxonomies are from that site. Work Arounds ------------ However, there are work arounds, which one is best for you will depend on several things, and each has their own advantages and disadvantages. 1. Retrieving all terms and inspecting their taxonomy field 2. WP CLI 3. REST API 4. Dedicated REST API endpoints 5. Pushing Data 6. Uniform taxonomies, but with different visibility 7. Preparing data in advance These are all work arounds that try to cater for the edge case you've asked about. Of all of these, only WP CLI reliably gives all the needed information without performance and scaling issues. Whichever method is used, cache the result. ### Retrieving all Terms We can retrieve all terms in a site, then loop over them to identify the `taxonomy` fields: ```php $query = new WP_Term_Query([]); $terms = $query->get_terms(); $taxonomies = wp_list_pluck( $terms, 'taxonomy' ); $taxonomies = array_unique( $taxonomies ); ``` However, there are some major problems with this: * it does not scale, pulling all terms into memory takes time and memory, eventually the site will have more than can be held leading either to hitting the execution time limit, or memory exhaustion * it only shows used taxonomies, if there are no categories then the category taxonomy will not show * this gives you no information that the taxonomy of those terms were registered with, so permalinks and labels may not be available ### WP CLI WP CLI can give you exactly what you need for both of your questions, *if it's available*. By assembling a command and calling it from PHP, you can programmatically retrieve the data you wish while avoiding a HTTP request. * we call WP CLI via either `exec` or `proc_open` * we specify which site we want via the `--url` parameter, we can get the URL via a standard API call such as `get_site_url( $site_id )` * We add the `--format` parameter to ensure WP CLI gives us machine readable results, either `--format="csv"` for a CSV string that functions such as `fgetcsv` etc can process, or `--format="json"` which `json_decode` can process. JSON will be easier * we parse the result in PHP For example, here is the local copy of my site: ``` vagrant@vvv:/srv/www/tomjn/public_html$ wp taxonomy list +----------------+------------------+-------------+---------------+---------------+--------------+--------+ | name | label | description | object_type | show_tagcloud | hierarchical | public | +----------------+------------------+-------------+---------------+---------------+--------------+--------+ | category | Categories | | post | 1 | 1 | 1 | | post_tag | Tags | | post | 1 | | 1 | | nav_menu | Navigation Menus | | nav_menu_item | | | | | link_category | Link Categories | | link | 1 | | | | post_format | Formats | | post | | | 1 | | technology | Technologies | | project | 1 | | 1 | | tomjn_talk_tag | Talk Tags | | tomjn_talks | 1 | | 1 | | series | Series | | post | | | 1 | +----------------+------------------+-------------+---------------+---------------+--------------+--------+ ``` I can also pass `--format=json` or `--format=csv` to get a machine parseable result. I can target individual sites in a multisite install by passing the `--url` parameter e.g. ``` wp taxonomy list --url="https://example.com/" --format="json" ``` I can then call this from PHP and parse the result to get a list of taxonomies. The same is true of terms, e.g. listing ``` ❯ wp term list category +---------+------------------+-----------------+-----------------------+-------------+--------+-------+ | term_id | term_taxonomy_id | name | slug | description | parent | count | +---------+------------------+-----------------+-----------------------+-------------+--------+-------+ | 129 | 136 | Auto-Aggregated | auto-aggregated | | 0 | 1 | | 245 | 276 | Big WP | big-wp | | 4 | 0 | | 95 | 100 | CSS | css | | 7 | 1 | | 7 | 7 | Design | design | | 0 | 3 | | 30 | 32 | Development | development | | 17 | 31 | ... ``` Or a posts categories: ``` ❯ wp post term list 15 category --format=csv term_id,name,slug,taxonomy 5,WordCamp,wordcamp,category ``` Be sure to set the right working path, and the `wp` is installed available and executable. Also be careful, if you ask WP CLI for every post in the database, it will give you it, even if it takes 1 hour to run. Your request will have ran out of time long before then leading to an error. So don't always provide an upper bounds on how many posts you want, even if you don't expect to reach it. It's also possible to request more data than the server has memory to hold, WP CLI will crash with an out of memory error in those situations. E.g. importing a 5GB wxr import file, or requesting 10k posts. *However, if WP CLI isn't available...* ### REST API You can query for taxonomies with the REST API. Every site supports it, but there are 2 caveats: * HTTP requests are expensive, and you can't bypass this cost with a PHP function as you need to load WP from scratch to get the registered taxonomies and post types you desired * Private and hidden taxonomies won't be shown, some taxonomies will only show with authentication, requiring you to add an authentication plugin But if that's okay with you, you can use the built in discovery to discover post types and taxonomies. Visit `example.com/wp-json/wp/v2/taxonomies` and you'll get a JSON list of public taxonomies, each object in the list has a `types` subfield that lists the post types it applies to. You can also fetch a post this way via the `/wp/v2/posts` endpoint, but you'll get term IDs rather than term names back, likely requiring additional queries. ### Custom Endpoint You can try to sidestep the restrictions above by building a custom endpoint. This would allow you to return everything you needed using a single request. To do this, call `register_rest_route` to register an endpoint, and return an array of keys and values from the callback. The API will encode these as JSON ### Pushing The Data Rather than retrieving this information from other sites in a multisite installation, it's much more efficient to have those sites push the information to you then caching the result. This is the most performant method. ### Uniform taxonomies, but with different visibility Some sites can take advantage of this particular possibility. If all sites have the same taxonomies registered then you can query all terms by switching blogs regardless of sites. ***But nobody said the taxonomies need to have the same options*** For example, site A has a category taxonomy, and site B has a tags taxonomy. A does not use tags, and b does not use categories. So we register both taxonomies on both sites, but on A we make tags a hidden private taxonomy, and on B we make categories a hidden private taxonomy. This work around won't be suitable for all situations though, and can't account for taxonomies registered by 3rd party plugins ### Preparing data in advance We don't know the other sites registered taxonomies and terms for each post because we didn't load that sites code. However, that site does. So why not make the site store this information somewhere it can be retrieved? For example, a site could store an option containing the registered taxonomies and their attributes. The same could be done for a posts terms, a post meta field can be updated on the save hook to contain a list of terms with their names, URLs, and the taxonomy they belong to, so that a term list can be recreated elsewhere without needing to know the registered taxonomies.
375,287
<p>Is there any way to change a site's homepage (Settings -&gt; Reading), via API? We're running a React app with a Headless WP 'backend', and I'd like to let users change the homepage of their sites though our app.</p> <p>I searched but couldn't find a solution to this.</p> <p>Thanks</p>
[ { "answer_id": 375278, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 2, "selected": false, "text": "<blockquote>\n<p>how can I retrieve all taxonomy terms for a post in an arbitrary site programmatically? In oth...
2020/09/22
[ "https://wordpress.stackexchange.com/questions/375287", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/185432/" ]
Is there any way to change a site's homepage (Settings -> Reading), via API? We're running a React app with a Headless WP 'backend', and I'd like to let users change the homepage of their sites though our app. I searched but couldn't find a solution to this. Thanks
> > how can I retrieve all taxonomy terms for a post in an arbitrary site programmatically? In other words, given post $post and site $siteId, how can I retrieve all terms for all taxonomies of that post in that site? > > > You can do this by omitting the taxonomy from `WP_Term_Query`: ```php $query = new WP_Term_Query( [ 'object_ids' => [ $post_id ] ] ); $terms = $query->get_terms(); ``` Note that this gives you no information that the taxonomys of those terms were registered with, so permalinks and labels may not be available > > How can I retrieve all taxonomies of an arbitrary site? In other words, given that I have a site $siteId, how can I retrieve all taxonomies on that site? > > > **Unfortunately, no, there is no API or function call in PHP that will give you this information.** Generally needing this information is a sign that something has gone wrong at the high level architecture, and that simpler easier solutions exist. Every decision has trade offs and built in constraints, and this is one of those situations where breaching a constraint requires a tradeoff or an architectural change. The root problem is that `switch_to_blog` changes the tables and globals, but it doesn't load any code from the other blog being switched to, so we need to recover what the registered posts types and taxonomies are from that site. Work Arounds ------------ However, there are work arounds, which one is best for you will depend on several things, and each has their own advantages and disadvantages. 1. Retrieving all terms and inspecting their taxonomy field 2. WP CLI 3. REST API 4. Dedicated REST API endpoints 5. Pushing Data 6. Uniform taxonomies, but with different visibility 7. Preparing data in advance These are all work arounds that try to cater for the edge case you've asked about. Of all of these, only WP CLI reliably gives all the needed information without performance and scaling issues. Whichever method is used, cache the result. ### Retrieving all Terms We can retrieve all terms in a site, then loop over them to identify the `taxonomy` fields: ```php $query = new WP_Term_Query([]); $terms = $query->get_terms(); $taxonomies = wp_list_pluck( $terms, 'taxonomy' ); $taxonomies = array_unique( $taxonomies ); ``` However, there are some major problems with this: * it does not scale, pulling all terms into memory takes time and memory, eventually the site will have more than can be held leading either to hitting the execution time limit, or memory exhaustion * it only shows used taxonomies, if there are no categories then the category taxonomy will not show * this gives you no information that the taxonomy of those terms were registered with, so permalinks and labels may not be available ### WP CLI WP CLI can give you exactly what you need for both of your questions, *if it's available*. By assembling a command and calling it from PHP, you can programmatically retrieve the data you wish while avoiding a HTTP request. * we call WP CLI via either `exec` or `proc_open` * we specify which site we want via the `--url` parameter, we can get the URL via a standard API call such as `get_site_url( $site_id )` * We add the `--format` parameter to ensure WP CLI gives us machine readable results, either `--format="csv"` for a CSV string that functions such as `fgetcsv` etc can process, or `--format="json"` which `json_decode` can process. JSON will be easier * we parse the result in PHP For example, here is the local copy of my site: ``` vagrant@vvv:/srv/www/tomjn/public_html$ wp taxonomy list +----------------+------------------+-------------+---------------+---------------+--------------+--------+ | name | label | description | object_type | show_tagcloud | hierarchical | public | +----------------+------------------+-------------+---------------+---------------+--------------+--------+ | category | Categories | | post | 1 | 1 | 1 | | post_tag | Tags | | post | 1 | | 1 | | nav_menu | Navigation Menus | | nav_menu_item | | | | | link_category | Link Categories | | link | 1 | | | | post_format | Formats | | post | | | 1 | | technology | Technologies | | project | 1 | | 1 | | tomjn_talk_tag | Talk Tags | | tomjn_talks | 1 | | 1 | | series | Series | | post | | | 1 | +----------------+------------------+-------------+---------------+---------------+--------------+--------+ ``` I can also pass `--format=json` or `--format=csv` to get a machine parseable result. I can target individual sites in a multisite install by passing the `--url` parameter e.g. ``` wp taxonomy list --url="https://example.com/" --format="json" ``` I can then call this from PHP and parse the result to get a list of taxonomies. The same is true of terms, e.g. listing ``` ❯ wp term list category +---------+------------------+-----------------+-----------------------+-------------+--------+-------+ | term_id | term_taxonomy_id | name | slug | description | parent | count | +---------+------------------+-----------------+-----------------------+-------------+--------+-------+ | 129 | 136 | Auto-Aggregated | auto-aggregated | | 0 | 1 | | 245 | 276 | Big WP | big-wp | | 4 | 0 | | 95 | 100 | CSS | css | | 7 | 1 | | 7 | 7 | Design | design | | 0 | 3 | | 30 | 32 | Development | development | | 17 | 31 | ... ``` Or a posts categories: ``` ❯ wp post term list 15 category --format=csv term_id,name,slug,taxonomy 5,WordCamp,wordcamp,category ``` Be sure to set the right working path, and the `wp` is installed available and executable. Also be careful, if you ask WP CLI for every post in the database, it will give you it, even if it takes 1 hour to run. Your request will have ran out of time long before then leading to an error. So don't always provide an upper bounds on how many posts you want, even if you don't expect to reach it. It's also possible to request more data than the server has memory to hold, WP CLI will crash with an out of memory error in those situations. E.g. importing a 5GB wxr import file, or requesting 10k posts. *However, if WP CLI isn't available...* ### REST API You can query for taxonomies with the REST API. Every site supports it, but there are 2 caveats: * HTTP requests are expensive, and you can't bypass this cost with a PHP function as you need to load WP from scratch to get the registered taxonomies and post types you desired * Private and hidden taxonomies won't be shown, some taxonomies will only show with authentication, requiring you to add an authentication plugin But if that's okay with you, you can use the built in discovery to discover post types and taxonomies. Visit `example.com/wp-json/wp/v2/taxonomies` and you'll get a JSON list of public taxonomies, each object in the list has a `types` subfield that lists the post types it applies to. You can also fetch a post this way via the `/wp/v2/posts` endpoint, but you'll get term IDs rather than term names back, likely requiring additional queries. ### Custom Endpoint You can try to sidestep the restrictions above by building a custom endpoint. This would allow you to return everything you needed using a single request. To do this, call `register_rest_route` to register an endpoint, and return an array of keys and values from the callback. The API will encode these as JSON ### Pushing The Data Rather than retrieving this information from other sites in a multisite installation, it's much more efficient to have those sites push the information to you then caching the result. This is the most performant method. ### Uniform taxonomies, but with different visibility Some sites can take advantage of this particular possibility. If all sites have the same taxonomies registered then you can query all terms by switching blogs regardless of sites. ***But nobody said the taxonomies need to have the same options*** For example, site A has a category taxonomy, and site B has a tags taxonomy. A does not use tags, and b does not use categories. So we register both taxonomies on both sites, but on A we make tags a hidden private taxonomy, and on B we make categories a hidden private taxonomy. This work around won't be suitable for all situations though, and can't account for taxonomies registered by 3rd party plugins ### Preparing data in advance We don't know the other sites registered taxonomies and terms for each post because we didn't load that sites code. However, that site does. So why not make the site store this information somewhere it can be retrieved? For example, a site could store an option containing the registered taxonomies and their attributes. The same could be done for a posts terms, a post meta field can be updated on the save hook to contain a list of terms with their names, URLs, and the taxonomy they belong to, so that a term list can be recreated elsewhere without needing to know the registered taxonomies.
375,363
<p>I have a WordPress site installed locally on my computer. The project was almost finished. Today I turned on my computer but it no longer works (categorically refusing to turn on), the repairman told me it's hard drive problem but I managed to get the project files which was in this hard drive thanks to a file recovery box (I recovered the WordPress files which were in www).</p> <p>Before that, I had made a backup of the project in Dropbox via the UpdraftPlus plugin.</p> <p>Now I bought a new computer and would like to know if there is a way to get my project back and how.</p> <p>I count on you if not I will lose two months of work. Thank you in advance for your answers.</p>
[ { "answer_id": 375278, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 2, "selected": false, "text": "<blockquote>\n<p>how can I retrieve all taxonomy terms for a post in an arbitrary site programmatically? In oth...
2020/09/24
[ "https://wordpress.stackexchange.com/questions/375363", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/195106/" ]
I have a WordPress site installed locally on my computer. The project was almost finished. Today I turned on my computer but it no longer works (categorically refusing to turn on), the repairman told me it's hard drive problem but I managed to get the project files which was in this hard drive thanks to a file recovery box (I recovered the WordPress files which were in www). Before that, I had made a backup of the project in Dropbox via the UpdraftPlus plugin. Now I bought a new computer and would like to know if there is a way to get my project back and how. I count on you if not I will lose two months of work. Thank you in advance for your answers.
> > how can I retrieve all taxonomy terms for a post in an arbitrary site programmatically? In other words, given post $post and site $siteId, how can I retrieve all terms for all taxonomies of that post in that site? > > > You can do this by omitting the taxonomy from `WP_Term_Query`: ```php $query = new WP_Term_Query( [ 'object_ids' => [ $post_id ] ] ); $terms = $query->get_terms(); ``` Note that this gives you no information that the taxonomys of those terms were registered with, so permalinks and labels may not be available > > How can I retrieve all taxonomies of an arbitrary site? In other words, given that I have a site $siteId, how can I retrieve all taxonomies on that site? > > > **Unfortunately, no, there is no API or function call in PHP that will give you this information.** Generally needing this information is a sign that something has gone wrong at the high level architecture, and that simpler easier solutions exist. Every decision has trade offs and built in constraints, and this is one of those situations where breaching a constraint requires a tradeoff or an architectural change. The root problem is that `switch_to_blog` changes the tables and globals, but it doesn't load any code from the other blog being switched to, so we need to recover what the registered posts types and taxonomies are from that site. Work Arounds ------------ However, there are work arounds, which one is best for you will depend on several things, and each has their own advantages and disadvantages. 1. Retrieving all terms and inspecting their taxonomy field 2. WP CLI 3. REST API 4. Dedicated REST API endpoints 5. Pushing Data 6. Uniform taxonomies, but with different visibility 7. Preparing data in advance These are all work arounds that try to cater for the edge case you've asked about. Of all of these, only WP CLI reliably gives all the needed information without performance and scaling issues. Whichever method is used, cache the result. ### Retrieving all Terms We can retrieve all terms in a site, then loop over them to identify the `taxonomy` fields: ```php $query = new WP_Term_Query([]); $terms = $query->get_terms(); $taxonomies = wp_list_pluck( $terms, 'taxonomy' ); $taxonomies = array_unique( $taxonomies ); ``` However, there are some major problems with this: * it does not scale, pulling all terms into memory takes time and memory, eventually the site will have more than can be held leading either to hitting the execution time limit, or memory exhaustion * it only shows used taxonomies, if there are no categories then the category taxonomy will not show * this gives you no information that the taxonomy of those terms were registered with, so permalinks and labels may not be available ### WP CLI WP CLI can give you exactly what you need for both of your questions, *if it's available*. By assembling a command and calling it from PHP, you can programmatically retrieve the data you wish while avoiding a HTTP request. * we call WP CLI via either `exec` or `proc_open` * we specify which site we want via the `--url` parameter, we can get the URL via a standard API call such as `get_site_url( $site_id )` * We add the `--format` parameter to ensure WP CLI gives us machine readable results, either `--format="csv"` for a CSV string that functions such as `fgetcsv` etc can process, or `--format="json"` which `json_decode` can process. JSON will be easier * we parse the result in PHP For example, here is the local copy of my site: ``` vagrant@vvv:/srv/www/tomjn/public_html$ wp taxonomy list +----------------+------------------+-------------+---------------+---------------+--------------+--------+ | name | label | description | object_type | show_tagcloud | hierarchical | public | +----------------+------------------+-------------+---------------+---------------+--------------+--------+ | category | Categories | | post | 1 | 1 | 1 | | post_tag | Tags | | post | 1 | | 1 | | nav_menu | Navigation Menus | | nav_menu_item | | | | | link_category | Link Categories | | link | 1 | | | | post_format | Formats | | post | | | 1 | | technology | Technologies | | project | 1 | | 1 | | tomjn_talk_tag | Talk Tags | | tomjn_talks | 1 | | 1 | | series | Series | | post | | | 1 | +----------------+------------------+-------------+---------------+---------------+--------------+--------+ ``` I can also pass `--format=json` or `--format=csv` to get a machine parseable result. I can target individual sites in a multisite install by passing the `--url` parameter e.g. ``` wp taxonomy list --url="https://example.com/" --format="json" ``` I can then call this from PHP and parse the result to get a list of taxonomies. The same is true of terms, e.g. listing ``` ❯ wp term list category +---------+------------------+-----------------+-----------------------+-------------+--------+-------+ | term_id | term_taxonomy_id | name | slug | description | parent | count | +---------+------------------+-----------------+-----------------------+-------------+--------+-------+ | 129 | 136 | Auto-Aggregated | auto-aggregated | | 0 | 1 | | 245 | 276 | Big WP | big-wp | | 4 | 0 | | 95 | 100 | CSS | css | | 7 | 1 | | 7 | 7 | Design | design | | 0 | 3 | | 30 | 32 | Development | development | | 17 | 31 | ... ``` Or a posts categories: ``` ❯ wp post term list 15 category --format=csv term_id,name,slug,taxonomy 5,WordCamp,wordcamp,category ``` Be sure to set the right working path, and the `wp` is installed available and executable. Also be careful, if you ask WP CLI for every post in the database, it will give you it, even if it takes 1 hour to run. Your request will have ran out of time long before then leading to an error. So don't always provide an upper bounds on how many posts you want, even if you don't expect to reach it. It's also possible to request more data than the server has memory to hold, WP CLI will crash with an out of memory error in those situations. E.g. importing a 5GB wxr import file, or requesting 10k posts. *However, if WP CLI isn't available...* ### REST API You can query for taxonomies with the REST API. Every site supports it, but there are 2 caveats: * HTTP requests are expensive, and you can't bypass this cost with a PHP function as you need to load WP from scratch to get the registered taxonomies and post types you desired * Private and hidden taxonomies won't be shown, some taxonomies will only show with authentication, requiring you to add an authentication plugin But if that's okay with you, you can use the built in discovery to discover post types and taxonomies. Visit `example.com/wp-json/wp/v2/taxonomies` and you'll get a JSON list of public taxonomies, each object in the list has a `types` subfield that lists the post types it applies to. You can also fetch a post this way via the `/wp/v2/posts` endpoint, but you'll get term IDs rather than term names back, likely requiring additional queries. ### Custom Endpoint You can try to sidestep the restrictions above by building a custom endpoint. This would allow you to return everything you needed using a single request. To do this, call `register_rest_route` to register an endpoint, and return an array of keys and values from the callback. The API will encode these as JSON ### Pushing The Data Rather than retrieving this information from other sites in a multisite installation, it's much more efficient to have those sites push the information to you then caching the result. This is the most performant method. ### Uniform taxonomies, but with different visibility Some sites can take advantage of this particular possibility. If all sites have the same taxonomies registered then you can query all terms by switching blogs regardless of sites. ***But nobody said the taxonomies need to have the same options*** For example, site A has a category taxonomy, and site B has a tags taxonomy. A does not use tags, and b does not use categories. So we register both taxonomies on both sites, but on A we make tags a hidden private taxonomy, and on B we make categories a hidden private taxonomy. This work around won't be suitable for all situations though, and can't account for taxonomies registered by 3rd party plugins ### Preparing data in advance We don't know the other sites registered taxonomies and terms for each post because we didn't load that sites code. However, that site does. So why not make the site store this information somewhere it can be retrieved? For example, a site could store an option containing the registered taxonomies and their attributes. The same could be done for a posts terms, a post meta field can be updated on the save hook to contain a list of terms with their names, URLs, and the taxonomy they belong to, so that a term list can be recreated elsewhere without needing to know the registered taxonomies.
375,439
<p>Hello I want to know how to edit wordpress html and add custom html for example I want to add html element like icon beside a link. here is the code:</p> <p>wordpress original source code:</p> <pre><code>&lt;a rel=&quot;nofollow&quot; class=&quot;comment-reply-link&quot;&gt; Reply &lt;/a&gt; </code></pre> <p>I want to edit this wordpress html code to add this icon to be:</p> <pre><code>&lt;a rel=&quot;nofollow&quot; class=&quot;comment-reply-link&quot;&gt; &lt;i class=&quot;material-icons&quot;&gt; Reply &lt;/i&gt; &lt;/a&gt; </code></pre> <p>UPDATE: another example to be clear: I want to add custom id to the link which is wordpress blog comment element source code not a theme source code. please, how to do that? and many thanks in advance</p>
[ { "answer_id": 375442, "author": "Patrice Poliquin", "author_id": 32365, "author_profile": "https://wordpress.stackexchange.com/users/32365", "pm_score": 0, "selected": false, "text": "<p><strong>TL:DR;</strong></p>\n<p>Quick answer would be that you can't add text to a custom icon libra...
2020/09/25
[ "https://wordpress.stackexchange.com/questions/375439", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/188733/" ]
Hello I want to know how to edit wordpress html and add custom html for example I want to add html element like icon beside a link. here is the code: wordpress original source code: ``` <a rel="nofollow" class="comment-reply-link"> Reply </a> ``` I want to edit this wordpress html code to add this icon to be: ``` <a rel="nofollow" class="comment-reply-link"> <i class="material-icons"> Reply </i> </a> ``` UPDATE: another example to be clear: I want to add custom id to the link which is wordpress blog comment element source code not a theme source code. please, how to do that? and many thanks in advance
That HTML is generated in the `get_comment_reply_link` function: <https://github.com/WordPress/WordPress/blob/0418dad234c13a88e06f5e50c83bcebaaf5ab211/wp-includes/comment-template.php#L1654> Which gives us what's needed. Here are 3 options: 1. The function takes an arguments array, and `reply_text` is one of the options, so just set this value to what you wanted e.g. `'reply_text' => '<i class="material-icons"> Reply </i>'` 2. There's a filter at the end of the function that gives you the opportunity to modify the entire links HTML named `comment_reply_link`, look up the docs for that filter for details 3. You don't need to modify the HTML markup at all, this can be done with CSS Changing the call to `get_comment_reply_link` will require changes to your theme, possibly the creation of a comments template. You will need to adjust `wp_list_comments` to take a `callback` argument with a function to display the comment, allowing you to change its HTML Using the filter can be done in a themes `functions.php` or in a plugin. Using CSS will require you to enquire with the material design library you've chosen.
375,454
<p>When I open the block editor on a new post or page or edit an existing post or page, the Default Gutenberg Block is the paragraph block. How do I change this to a gallery block or another block?</p>
[ { "answer_id": 375618, "author": "Will", "author_id": 48698, "author_profile": "https://wordpress.stackexchange.com/users/48698", "pm_score": 0, "selected": false, "text": "<p>This is possible with the <a href=\"https://developer.wordpress.org/block-editor/packages/packages-blocks/#setDe...
2020/09/25
[ "https://wordpress.stackexchange.com/questions/375454", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/195187/" ]
When I open the block editor on a new post or page or edit an existing post or page, the Default Gutenberg Block is the paragraph block. How do I change this to a gallery block or another block?
You can use the Gutenberg Block Template it is used to have a content placeholder for your Gutenberg content. <https://developer.wordpress.org/block-editor/developers/block-api/block-templates/> ``` <?php function myplugin_register_template() { $post_type_object = get_post_type_object( 'post' ); $post_type_object->template = array( array( 'core/image' ), ); } add_action( 'init', 'myplugin_register_template' ); ```
375,459
<p>I have special roles on my site. I use easy digital download. My user has access to the download page. I want the metabox not to see the number of sales. Can I hide this metabox for this role or user?</p> <p>Of course, now that I had to, I deleted it with CSS (<code>display : none</code>) Thank you in advance for your guidance.</p>
[ { "answer_id": 375618, "author": "Will", "author_id": 48698, "author_profile": "https://wordpress.stackexchange.com/users/48698", "pm_score": 0, "selected": false, "text": "<p>This is possible with the <a href=\"https://developer.wordpress.org/block-editor/packages/packages-blocks/#setDe...
2020/09/25
[ "https://wordpress.stackexchange.com/questions/375459", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/195197/" ]
I have special roles on my site. I use easy digital download. My user has access to the download page. I want the metabox not to see the number of sales. Can I hide this metabox for this role or user? Of course, now that I had to, I deleted it with CSS (`display : none`) Thank you in advance for your guidance.
You can use the Gutenberg Block Template it is used to have a content placeholder for your Gutenberg content. <https://developer.wordpress.org/block-editor/developers/block-api/block-templates/> ``` <?php function myplugin_register_template() { $post_type_object = get_post_type_object( 'post' ); $post_type_object->template = array( array( 'core/image' ), ); } add_action( 'init', 'myplugin_register_template' ); ```
375,473
<p>I checked everything suggested in <a href="https://wordpress.stackexchange.com/questions/184104/page-editor-missing-templates-drop-down">that response</a>: &quot;page attributes&quot; option is checked, template file is located at theme root folder, I tried several file encoding options in my text editor (UTF8 with or without BOM), I tried switching to another theme then back to my custom theme, I do have the right stuff on top:</p> <pre><code>&lt;?php /* Template Name: Page Actualites */ ?&gt; </code></pre> <p>Why am I still not seeing the page template dropdown list?</p>
[ { "answer_id": 375475, "author": "bueltge", "author_id": 170, "author_profile": "https://wordpress.stackexchange.com/users/170", "pm_score": 0, "selected": false, "text": "<p>The <a href=\"https://developer.wordpress.org/themes/template-files-section/page-template-files/#creating-custom-...
2020/09/26
[ "https://wordpress.stackexchange.com/questions/375473", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/11634/" ]
I checked everything suggested in [that response](https://wordpress.stackexchange.com/questions/184104/page-editor-missing-templates-drop-down): "page attributes" option is checked, template file is located at theme root folder, I tried several file encoding options in my text editor (UTF8 with or without BOM), I tried switching to another theme then back to my custom theme, I do have the right stuff on top: ``` <?php /* Template Name: Page Actualites */ ?> ``` Why am I still not seeing the page template dropdown list?
The page was set as the posts page in `settings > reading`, which prevents from chosing a specific page template since this setting automatically assigns `index.php` as the page template for that page.
375,547
<p>I need to change the timeformat in this column</p> <p><a href="https://i.stack.imgur.com/huMdd.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/huMdd.png" alt="" /></a></p> <p>to be in hours, not measured in seconds and minutes. This meaning that 30 minutes should be measured in 0.5 hours and so on.</p> <p>I think I need to edit this line of code. Any suggestions on how to change the measurement to ONLY HOURS?</p> <pre><code>return human_time_diff(strtotime($item['time_login']), strtotime($item['time_last_seen'])); </code></pre>
[ { "answer_id": 375475, "author": "bueltge", "author_id": 170, "author_profile": "https://wordpress.stackexchange.com/users/170", "pm_score": 0, "selected": false, "text": "<p>The <a href=\"https://developer.wordpress.org/themes/template-files-section/page-template-files/#creating-custom-...
2020/09/28
[ "https://wordpress.stackexchange.com/questions/375547", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/195292/" ]
I need to change the timeformat in this column [![](https://i.stack.imgur.com/huMdd.png)](https://i.stack.imgur.com/huMdd.png) to be in hours, not measured in seconds and minutes. This meaning that 30 minutes should be measured in 0.5 hours and so on. I think I need to edit this line of code. Any suggestions on how to change the measurement to ONLY HOURS? ``` return human_time_diff(strtotime($item['time_login']), strtotime($item['time_last_seen'])); ```
The page was set as the posts page in `settings > reading`, which prevents from chosing a specific page template since this setting automatically assigns `index.php` as the page template for that page.
375,560
<p>Is this the correct way to translate a sting of text?</p> <pre><code>_e( '&lt;h2 class=&quot;title&quot;&gt;' . $var . '&lt;/h2&gt;', 'text-domain' ); </code></pre> <p>or, is this?</p> <pre><code>echo '&lt;h2 class=&quot;title&quot;&gt;'; _e( $var, 'text-domain' ); echo '&lt;/h2&gt;'; </code></pre> <p>or this?</p> <pre><code>printf( __( '&lt;h2 class=&quot;title&quot;&gt;%s&lt;/h2&gt;', 'text-domain' ), $var ); </code></pre> <p><strong>Edit:</strong> Update or this?</p> <pre><code>printf( '&lt;h2 class=&quot;title&quot;&gt;%s&lt;/h2&gt;', esc_html__( $var, 'text-domain' ) ); </code></pre>
[ { "answer_id": 375562, "author": "DaFois", "author_id": 108884, "author_profile": "https://wordpress.stackexchange.com/users/108884", "pm_score": 1, "selected": false, "text": "<ul>\n<li>Both of the functions are used in the localisation of wordpress themes.</li>\n<li>Both are used to di...
2020/09/28
[ "https://wordpress.stackexchange.com/questions/375560", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/104464/" ]
Is this the correct way to translate a sting of text? ``` _e( '<h2 class="title">' . $var . '</h2>', 'text-domain' ); ``` or, is this? ``` echo '<h2 class="title">'; _e( $var, 'text-domain' ); echo '</h2>'; ``` or this? ``` printf( __( '<h2 class="title">%s</h2>', 'text-domain' ), $var ); ``` **Edit:** Update or this? ``` printf( '<h2 class="title">%s</h2>', esc_html__( $var, 'text-domain' ) ); ```
**None of them are correct**. These APIs are not intended for dynamic data or content from the database. This would be the best practice answer: ```php echo '<h2 class="title">'; esc_html_e( 'static string', 'text-domain' ); echo '</h2>'; ``` ***If you want to translate posts and other database user entered content, use a translation plugin, not the localisation API.*** There are many very popular plugins to do this, each with their own tradeoffs based on how you want localisation to work for your site. But Why? -------- ***You should never use variables as the first parameter of a localisation API call.*** Aside from being extreme bad practice, it means the string will not get picked up by tools, so it's impossible to generate translation files to translaters. It does not matter how you pass `$var` to the function, it will always be incorrect. Do not pass variables to localisation functions in WordPress. **These functions are intended for static strings, not dynamic values.** If you want to localise content from the database, this API is not the way to do it. ### HTML tags Localised strings shouldn't include H2 tags and other HTML tags, but instead provide the text content that goes in those tags. There are rare cases when you do, in which case `__()` and `wp_kses_post` or `sprintf` can be useful. ### `_e()` vs `__()` `_e()` is equivalent to `echo __()` ### Why are `_e` and `__` wrong? Because neither do escaping. This is the canonical correct answer: ```php echo '<h2 class="title">'; esc_html_e( 'static string', 'text-domain' ); echo '</h2>'; ``` `esc_html_e(` is shorthand for `echo esc_html( __(`. We know that inside the H2 tag there will be text, but no tags, so we use `esc_html` to escape any HTML that appears If this were an attribute of a tag, then it would be `attribute="<?php esc_attr_e(...); ?>"` So then, why does `__(` etc exist? Because escaping has to happen as late as possible, and only once. Otherwise we run the risk of double escaping strings. ### Fixing The `printf` example We can escape the localised string prior to passing it to `printf` allowing it to be escaped: ```php printf( '<h2 class="title">%s</h2>', esc_html__( 'static string','text-domain' ) ); ``` So How Do You Translate Dynamic Content? ---------------------------------------- If you want to enable posts/terms/titles/etc in multiple languages, you need a translation plugin. The i18n APIs are for hardcoded static strings, not database or generated content.
375,574
<p>so I have this wordpress website <a href="https://knivesreviews.net/" rel="nofollow noreferrer">knivesreviews</a></p> <p>I ha ve blog section there, but it really is just category. I would like to make it separate wordpress installation, but I'm afraid it will mess up my database. I want it it separate installation,because I will be adding eshop with knives to the original website and need it to be on separate database for security and other reasons. What is the easiest way how to have two installations of wordpress at one site and is it even possible?</p>
[ { "answer_id": 375562, "author": "DaFois", "author_id": 108884, "author_profile": "https://wordpress.stackexchange.com/users/108884", "pm_score": 1, "selected": false, "text": "<ul>\n<li>Both of the functions are used in the localisation of wordpress themes.</li>\n<li>Both are used to di...
2020/09/28
[ "https://wordpress.stackexchange.com/questions/375574", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/195318/" ]
so I have this wordpress website [knivesreviews](https://knivesreviews.net/) I ha ve blog section there, but it really is just category. I would like to make it separate wordpress installation, but I'm afraid it will mess up my database. I want it it separate installation,because I will be adding eshop with knives to the original website and need it to be on separate database for security and other reasons. What is the easiest way how to have two installations of wordpress at one site and is it even possible?
**None of them are correct**. These APIs are not intended for dynamic data or content from the database. This would be the best practice answer: ```php echo '<h2 class="title">'; esc_html_e( 'static string', 'text-domain' ); echo '</h2>'; ``` ***If you want to translate posts and other database user entered content, use a translation plugin, not the localisation API.*** There are many very popular plugins to do this, each with their own tradeoffs based on how you want localisation to work for your site. But Why? -------- ***You should never use variables as the first parameter of a localisation API call.*** Aside from being extreme bad practice, it means the string will not get picked up by tools, so it's impossible to generate translation files to translaters. It does not matter how you pass `$var` to the function, it will always be incorrect. Do not pass variables to localisation functions in WordPress. **These functions are intended for static strings, not dynamic values.** If you want to localise content from the database, this API is not the way to do it. ### HTML tags Localised strings shouldn't include H2 tags and other HTML tags, but instead provide the text content that goes in those tags. There are rare cases when you do, in which case `__()` and `wp_kses_post` or `sprintf` can be useful. ### `_e()` vs `__()` `_e()` is equivalent to `echo __()` ### Why are `_e` and `__` wrong? Because neither do escaping. This is the canonical correct answer: ```php echo '<h2 class="title">'; esc_html_e( 'static string', 'text-domain' ); echo '</h2>'; ``` `esc_html_e(` is shorthand for `echo esc_html( __(`. We know that inside the H2 tag there will be text, but no tags, so we use `esc_html` to escape any HTML that appears If this were an attribute of a tag, then it would be `attribute="<?php esc_attr_e(...); ?>"` So then, why does `__(` etc exist? Because escaping has to happen as late as possible, and only once. Otherwise we run the risk of double escaping strings. ### Fixing The `printf` example We can escape the localised string prior to passing it to `printf` allowing it to be escaped: ```php printf( '<h2 class="title">%s</h2>', esc_html__( 'static string','text-domain' ) ); ``` So How Do You Translate Dynamic Content? ---------------------------------------- If you want to enable posts/terms/titles/etc in multiple languages, you need a translation plugin. The i18n APIs are for hardcoded static strings, not database or generated content.
375,600
<p>I like the gutenberg &quot;latest posts&quot; block. The problem I have with it is that it doesn't hardcrop images that users upload to the posts. Is there a way to choose a hard-cropped or custom size that I have created through the <code>add_image_size()</code> function?</p> <p>I don't really have any code, but I think this question is on topic because it's purely about wordpress core. I'm sorry if it isn't!</p> <p>What I have used to create my custom image size is this though:</p> <pre><code>add_action( 'after_setup_theme', 'aeroleds_image_sizes' ); function aeroleds_image_sizes() { add_image_size( 'banner-image', 400, 300, true ); // (cropped) } </code></pre>
[ { "answer_id": 375601, "author": "Paul", "author_id": 195289, "author_profile": "https://wordpress.stackexchange.com/users/195289", "pm_score": 1, "selected": false, "text": "<p>it looks like you have to also pass your custom image thumbnail sizes to the filter <code>image_size_names_ch...
2020/09/29
[ "https://wordpress.stackexchange.com/questions/375600", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/105668/" ]
I like the gutenberg "latest posts" block. The problem I have with it is that it doesn't hardcrop images that users upload to the posts. Is there a way to choose a hard-cropped or custom size that I have created through the `add_image_size()` function? I don't really have any code, but I think this question is on topic because it's purely about wordpress core. I'm sorry if it isn't! What I have used to create my custom image size is this though: ``` add_action( 'after_setup_theme', 'aeroleds_image_sizes' ); function aeroleds_image_sizes() { add_image_size( 'banner-image', 400, 300, true ); // (cropped) } ```
The Latest Posts block uses (`wp.data.select( 'core/block-editor' ).getSettings()` to get) the image sizes in the editor settings which can be filtered via the [`block_editor_settings` hook](https://developer.wordpress.org/reference/hooks/block_editor_settings/) in PHP: > > `apply_filters( 'block_editor_settings', array $editor_settings, WP_Post $post )` > > > Filters the settings to pass to the block editor. > > > And the setting name used for the image sizes is `imageSizes`. So for example, to make the custom `banner-image` size be available in the featured image size dropdown (in the Latest Posts block's settings): ```php add_filter( 'block_editor_settings', 'wpse_375600' ); function wpse_375600( $editor_settings ) { $editor_settings['imageSizes'][] = [ 'slug' => 'banner-image', 'name' => 'Banner Image', ]; return $editor_settings; } ``` And in addition to that the filter being specific to the block editor, your callback can also get access to the post being edited, which is the second parameter (`$post`) in the filter hook as you can see above. So you could for example filter the settings only for certain posts. **Resources:** * [The Latest Posts block on GitHub](https://github.com/WordPress/gutenberg/tree/master/packages/block-library/src/latest-posts) * [The Block Editor's Data » `getSettings()`](https://developer.wordpress.org/block-editor/data/data-core-block-editor/#getSettings) * [Editor Filters » Editor Settings](https://developer.wordpress.org/block-editor/developers/filters/editor-filters/#editor-settings)
375,624
<p>I use this query to call posts from a custom-type post I setup apart</p> <pre><code>$args = array( 'posts_per_page' =&gt; 5, 'order'=&gt; 'DES', 'post_type' =&gt; 'custom-post' ); $myposts = get_posts( $args ); foreach ( $myposts as $post ) : setup_postdata( $post ); ?&gt; &lt;div class=&quot;thumbnail&quot;&gt; &lt;?php echo get_the_post_thumbnail( $post-&gt;ID, 'thumbnail' ); ?&gt; &lt;/div&gt; &lt;?php the_title( sprintf( '&lt;h2&gt;&lt;a href=&quot;%s&quot;&gt;', esc_url( get_permalink() ) ),'&lt;/a&gt;&lt;/h2&gt;' ); ?&gt; &lt;?php echo '&lt;p&gt;' . get_the_excerpt() . '&lt;/p&gt;' ?&gt; &lt;?php endforeach; wp_reset_postdata(); </code></pre> <p>Two questions:</p> <ol> <li>Is that correct or can I improve it better somehow?</li> <li>Is it possible to call posts that are placed <strong>both</strong> in 2 different taxonomy generated from that custom post type (&quot;flowers&quot; and &quot;colors&quot; for instance) and then call post that is in the &quot;flowers&quot; category but <strong>not</strong> in the &quot;colors&quot; one?</li> </ol> <p>Thank you</p>
[ { "answer_id": 375601, "author": "Paul", "author_id": 195289, "author_profile": "https://wordpress.stackexchange.com/users/195289", "pm_score": 1, "selected": false, "text": "<p>it looks like you have to also pass your custom image thumbnail sizes to the filter <code>image_size_names_ch...
2020/09/29
[ "https://wordpress.stackexchange.com/questions/375624", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/195370/" ]
I use this query to call posts from a custom-type post I setup apart ``` $args = array( 'posts_per_page' => 5, 'order'=> 'DES', 'post_type' => 'custom-post' ); $myposts = get_posts( $args ); foreach ( $myposts as $post ) : setup_postdata( $post ); ?> <div class="thumbnail"> <?php echo get_the_post_thumbnail( $post->ID, 'thumbnail' ); ?> </div> <?php the_title( sprintf( '<h2><a href="%s">', esc_url( get_permalink() ) ),'</a></h2>' ); ?> <?php echo '<p>' . get_the_excerpt() . '</p>' ?> <?php endforeach; wp_reset_postdata(); ``` Two questions: 1. Is that correct or can I improve it better somehow? 2. Is it possible to call posts that are placed **both** in 2 different taxonomy generated from that custom post type ("flowers" and "colors" for instance) and then call post that is in the "flowers" category but **not** in the "colors" one? Thank you
The Latest Posts block uses (`wp.data.select( 'core/block-editor' ).getSettings()` to get) the image sizes in the editor settings which can be filtered via the [`block_editor_settings` hook](https://developer.wordpress.org/reference/hooks/block_editor_settings/) in PHP: > > `apply_filters( 'block_editor_settings', array $editor_settings, WP_Post $post )` > > > Filters the settings to pass to the block editor. > > > And the setting name used for the image sizes is `imageSizes`. So for example, to make the custom `banner-image` size be available in the featured image size dropdown (in the Latest Posts block's settings): ```php add_filter( 'block_editor_settings', 'wpse_375600' ); function wpse_375600( $editor_settings ) { $editor_settings['imageSizes'][] = [ 'slug' => 'banner-image', 'name' => 'Banner Image', ]; return $editor_settings; } ``` And in addition to that the filter being specific to the block editor, your callback can also get access to the post being edited, which is the second parameter (`$post`) in the filter hook as you can see above. So you could for example filter the settings only for certain posts. **Resources:** * [The Latest Posts block on GitHub](https://github.com/WordPress/gutenberg/tree/master/packages/block-library/src/latest-posts) * [The Block Editor's Data » `getSettings()`](https://developer.wordpress.org/block-editor/data/data-core-block-editor/#getSettings) * [Editor Filters » Editor Settings](https://developer.wordpress.org/block-editor/developers/filters/editor-filters/#editor-settings)
375,637
<p>Finally I've solved the wildcard subdomain for my hosting. But now I'm facing another problem.</p> <p>If you try <a href="https://randomname.minepi.hu" rel="nofollow noreferrer">https://randomname.minepi.hu</a> then it will redirect for the main domain and wordpress deleting the given data. If you try this link: <a href="https://randonname.minepi.hu/test/" rel="nofollow noreferrer">https://randonname.minepi.hu/test/</a> you can see its a simple php page and now the subdomain stays there, and I can processs the given info on the site.</p> <p>Okay the SSL have to be setup somehow later, not sure how could I do that since I'm just using Easy SSL now, and I don't see wildcard subdomain options but thats a different tale. Right now I would be happy if Wordpress not deleting the subdomain from the URL.</p> <p>Maybe its some edit needed in the MySQL tables, or are there any easier options?</p>
[ { "answer_id": 375601, "author": "Paul", "author_id": 195289, "author_profile": "https://wordpress.stackexchange.com/users/195289", "pm_score": 1, "selected": false, "text": "<p>it looks like you have to also pass your custom image thumbnail sizes to the filter <code>image_size_names_ch...
2020/09/29
[ "https://wordpress.stackexchange.com/questions/375637", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/195329/" ]
Finally I've solved the wildcard subdomain for my hosting. But now I'm facing another problem. If you try <https://randomname.minepi.hu> then it will redirect for the main domain and wordpress deleting the given data. If you try this link: <https://randonname.minepi.hu/test/> you can see its a simple php page and now the subdomain stays there, and I can processs the given info on the site. Okay the SSL have to be setup somehow later, not sure how could I do that since I'm just using Easy SSL now, and I don't see wildcard subdomain options but thats a different tale. Right now I would be happy if Wordpress not deleting the subdomain from the URL. Maybe its some edit needed in the MySQL tables, or are there any easier options?
The Latest Posts block uses (`wp.data.select( 'core/block-editor' ).getSettings()` to get) the image sizes in the editor settings which can be filtered via the [`block_editor_settings` hook](https://developer.wordpress.org/reference/hooks/block_editor_settings/) in PHP: > > `apply_filters( 'block_editor_settings', array $editor_settings, WP_Post $post )` > > > Filters the settings to pass to the block editor. > > > And the setting name used for the image sizes is `imageSizes`. So for example, to make the custom `banner-image` size be available in the featured image size dropdown (in the Latest Posts block's settings): ```php add_filter( 'block_editor_settings', 'wpse_375600' ); function wpse_375600( $editor_settings ) { $editor_settings['imageSizes'][] = [ 'slug' => 'banner-image', 'name' => 'Banner Image', ]; return $editor_settings; } ``` And in addition to that the filter being specific to the block editor, your callback can also get access to the post being edited, which is the second parameter (`$post`) in the filter hook as you can see above. So you could for example filter the settings only for certain posts. **Resources:** * [The Latest Posts block on GitHub](https://github.com/WordPress/gutenberg/tree/master/packages/block-library/src/latest-posts) * [The Block Editor's Data » `getSettings()`](https://developer.wordpress.org/block-editor/data/data-core-block-editor/#getSettings) * [Editor Filters » Editor Settings](https://developer.wordpress.org/block-editor/developers/filters/editor-filters/#editor-settings)
375,639
<p>I am making a plugin to upload records and I want to put the option to choose category, also I would like those categories to be the ones that are normally created with wordpress, but I don't know if can</p> <p>How do I put the option to choose category in the form?</p>
[ { "answer_id": 375641, "author": "ktscript", "author_id": 194230, "author_profile": "https://wordpress.stackexchange.com/users/194230", "pm_score": -1, "selected": false, "text": "<p>you can try this code:</p>\n<pre><code>$parent_cat = get_query_var('cat');\nwp_list_categories(&quot;chil...
2020/09/29
[ "https://wordpress.stackexchange.com/questions/375639", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/139955/" ]
I am making a plugin to upload records and I want to put the option to choose category, also I would like those categories to be the ones that are normally created with wordpress, but I don't know if can How do I put the option to choose category in the form?
IDs are your friends. Get the category list using [get\_category](https://developer.wordpress.org/reference/functions/get_categories) (i'm assuming we are talking about the in-built Wordpress "category" taxonomy, which slug is *category*). ``` $categories = get_categories( array( 'hide_empty' => false // This is optional ) ); ``` Use the obtained category list in the output of your <select> field: ``` <?php // get $selected_term_id from somewhere ?> <select name="category_id"> <?php foreach( $categories as $category ) : ?> <?php $is_selected = $category->term_id == $selected_term_id ? 'selected' : ''; ?> <option value="<?php esc_attr_e( $category->term_id ); ?>" <?php echo $is_selected; ?>><?php esc_html_e( $category->cat_name ); ?></option> <?php endforeach; ?> </select> ```
375,650
<p>I am trying to register a new post type to hide post in searches but still allow for the post to be seen by url.</p> <pre><code>function reg_ghost_status(){ register_post_status( 'ghosted', array( 'label' =&gt; 'Ghost Post', 'publicly_queryable' =&gt; false, 'exclude_from_search' =&gt; true, 'public' =&gt; true, //on false hides everywhere 'show_in_admin_all_list' =&gt; true, 'show_in_admin_status_list' =&gt; true, ) ); } add_action( 'init', 'reg_ghost_status' ); </code></pre> <p>I could not get this work and tried all sorts of combinations. It seems since it is 'public' it shows everywhere no matter what settings. So I than tried using the pre_set_query but I don't know how to use exclude instead of include by post_status.</p> <pre><code>function sxcsexclude_ghost_from_search($query) { if ( $query-&gt;is_single ) { $query-&gt;set('perm', 'readable'); $query-&gt;set('post_status', array( 'publish', 'draft', 'ghosted', 'future' )); return $query; } } add_action( 'pre_get_posts', '11111exclude_ghost_from_search' ); </code></pre> <p>Can someone tell me why the register_post_status is not working.</p> <p>Thanks</p>
[ { "answer_id": 375664, "author": "wrydere", "author_id": 66722, "author_profile": "https://wordpress.stackexchange.com/users/66722", "pm_score": 1, "selected": false, "text": "<p>If it was me, I would probably just override the queries on the individual templates that you are trying to h...
2020/09/29
[ "https://wordpress.stackexchange.com/questions/375650", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/192315/" ]
I am trying to register a new post type to hide post in searches but still allow for the post to be seen by url. ``` function reg_ghost_status(){ register_post_status( 'ghosted', array( 'label' => 'Ghost Post', 'publicly_queryable' => false, 'exclude_from_search' => true, 'public' => true, //on false hides everywhere 'show_in_admin_all_list' => true, 'show_in_admin_status_list' => true, ) ); } add_action( 'init', 'reg_ghost_status' ); ``` I could not get this work and tried all sorts of combinations. It seems since it is 'public' it shows everywhere no matter what settings. So I than tried using the pre\_set\_query but I don't know how to use exclude instead of include by post\_status. ``` function sxcsexclude_ghost_from_search($query) { if ( $query->is_single ) { $query->set('perm', 'readable'); $query->set('post_status', array( 'publish', 'draft', 'ghosted', 'future' )); return $query; } } add_action( 'pre_get_posts', '11111exclude_ghost_from_search' ); ``` Can someone tell me why the register\_post\_status is not working. Thanks
If it was me, I would probably just override the queries on the individual templates that you are trying to hide "ghosted" posts on. However, I can see how in some situations it would be better to override the main query. How about: ``` function public_query_published_only($query) { if ( !$query->is_single() && !current_user_can('manage_options') && !is_admin() ) { $query->set('post_status', array('publish') ); return $query; } } add_action( 'pre_get_posts', 'public_query_published_only' ); ``` So: if the query is not for a single post, and the user isn't a logged-in user, and the query isn't from the admin interface, only show posts with a status of "publish". (Of course, you could also add any other statuses that you deem to be query-able.) Because there is not an exclusion filter for post status, this is the best I could think of without resorting to SQL.
375,682
<p>I'm writing a new plugin, and one of the things it does is create a new dynamic block. I generally write my plugins based off of <a href="http://wppb.io" rel="nofollow noreferrer">WPPB</a>, which does things in an object-oriented way, and semantically separates admin functionality from public functionality.</p> <p>I have the admin class successfully creating the edit side of the block. But for the &quot;save&quot; side, for a dynamic block, it makes semantic sense for the render function to be in the public class ... but (I think) it needs to get registered in the admin class (actually, now that I'm writing this, is there any harm to calling register_block_type more than once?).</p> <p>I'm thinking there's more than one way to skin this cat, and I'm trying to figure out the &quot;best&quot;, where &quot;best&quot; is making optimal use of both PHP OOP and WordPress builtin functionality, to maximize speed, minimize size, and provide clean, readable code.</p> <p>Option 1: make sure the main plugin class instantiates the public class first, and then passes it to the admin class:</p> <pre><code>class My_Plugin { $my_public = new My_Public(); $my_admin = new My_Admin($my_public); } class My_Admin { public function __construct($my_public) { $this-&gt;my_public = $my_public; } register_block_type( 'my-plugin/my-block', array( 'editor_script' =&gt; 'my_editor_function', 'render_callback' =&gt; array($this-&gt;my_public, 'my_save_function') ) ); } class My_Public { public function my_save_function() { //do stuff to render the public side of the block } } </code></pre> <p>Option 2: do something with WordPress Actions and Hooks:</p> <pre><code>class My_Admin { register_block_type( 'my-plugin/my-block', array( 'editor_script' =&gt; 'my-editor-function', 'render_callback' =&gt; 'render_front_end') ) ); public function render_front_end() { do_action('my_plugin_render_action'); } } class My_Public { public function my_save_function() { //do stuff to render the public side of the block } add_action('my_plugin_render_action', 'my_save_function', 10); } </code></pre> <p>Or, hypothetically, Option 3: if there's no problem calling the register function more than once:</p> <pre><code>class My_Admin { register_block_type( 'my-plugin/my-block', array( 'editor_script' =&gt; 'my-editor-function', ) ); } class My_Public { register_block_type( 'my-plugin/my-block', array( 'render_callback' =&gt; 'my_save_function' ) ); public function my_save_function() { //do stuff to render the public side of the block } } </code></pre> <p>Is one of these preferable? Do all of these work? Is there a better way to do this?</p>
[ { "answer_id": 375685, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 3, "selected": true, "text": "<p>Option 1 is the solution, here's a smaller example:</p>\n<pre class=\"lang-php prettyprint-override\"><code>$...
2020/09/30
[ "https://wordpress.stackexchange.com/questions/375682", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/194028/" ]
I'm writing a new plugin, and one of the things it does is create a new dynamic block. I generally write my plugins based off of [WPPB](http://wppb.io), which does things in an object-oriented way, and semantically separates admin functionality from public functionality. I have the admin class successfully creating the edit side of the block. But for the "save" side, for a dynamic block, it makes semantic sense for the render function to be in the public class ... but (I think) it needs to get registered in the admin class (actually, now that I'm writing this, is there any harm to calling register\_block\_type more than once?). I'm thinking there's more than one way to skin this cat, and I'm trying to figure out the "best", where "best" is making optimal use of both PHP OOP and WordPress builtin functionality, to maximize speed, minimize size, and provide clean, readable code. Option 1: make sure the main plugin class instantiates the public class first, and then passes it to the admin class: ``` class My_Plugin { $my_public = new My_Public(); $my_admin = new My_Admin($my_public); } class My_Admin { public function __construct($my_public) { $this->my_public = $my_public; } register_block_type( 'my-plugin/my-block', array( 'editor_script' => 'my_editor_function', 'render_callback' => array($this->my_public, 'my_save_function') ) ); } class My_Public { public function my_save_function() { //do stuff to render the public side of the block } } ``` Option 2: do something with WordPress Actions and Hooks: ``` class My_Admin { register_block_type( 'my-plugin/my-block', array( 'editor_script' => 'my-editor-function', 'render_callback' => 'render_front_end') ) ); public function render_front_end() { do_action('my_plugin_render_action'); } } class My_Public { public function my_save_function() { //do stuff to render the public side of the block } add_action('my_plugin_render_action', 'my_save_function', 10); } ``` Or, hypothetically, Option 3: if there's no problem calling the register function more than once: ``` class My_Admin { register_block_type( 'my-plugin/my-block', array( 'editor_script' => 'my-editor-function', ) ); } class My_Public { register_block_type( 'my-plugin/my-block', array( 'render_callback' => 'my_save_function' ) ); public function my_save_function() { //do stuff to render the public side of the block } } ``` Is one of these preferable? Do all of these work? Is there a better way to do this?
Option 1 is the solution, here's a smaller example: ```php $obj = new Obj(); .... register_block_type( 'my-plugin/my-block', [ 'editor_script' => 'editor-script-handle', 'render_callback' => [ $obj, 'block_save_function' ] ] ); ``` In that code `[ $obj, 'block_save_function' ]` is equivalent to `$obj->block_save_function(...`. The important thing to note, is that `render_callback`'s value is a PHP `callable` type. You need a reference to the object, and the name of the method to call. This is true of all callbacks, such as when you add an action or filter. Likewise, option 2 and 3 can be fixed by using the same syntax. To learn more about the different ways to create callables, see the PHP official documentation here <https://www.php.net/manual/en/language.types.callable.php>
375,799
<p>I am trying to get all user details (including WooCommerce meta data) in a function that is called with <code>user_register</code> and <code>profile_update</code> hooks. This is the simplified code:</p> <pre><code>function get_all_user_data($user_id) { $user_data = get_userdata($user_id); $login = $user_data-&gt;user_login; $b_firstname = get_user_meta($user_id, 'billing_first_name', true); } add_action('user_register','get_all_user_data'); add_action('profile_update','get_all_user_data'); </code></pre> <p><strong>The behavior:</strong></p> <ol> <li>User is registered, I can access it's userdata (e.g. login) immediately</li> <li>WooCommerce billing address is updated and saved, however I still only can access the $login variable, 'billing_first_name' meta is apparently still empty at this time</li> <li>WooCommerce shipping address is updated and saved, after this I can access the billing information that were saved in previous step, but not the shipping data that was saved in current step</li> </ol> <p>The same goes for a scenario in which the user is registered during WooCommerce checkout, no WC data is accessible at that time yet.</p> <p>PS: I have also tried the <code>woocommerce_after_save_address_validation</code> hook, but that seems to have the same behavior as the <code>profile_update</code> in my case.</p> <p><strong>Edit:</strong> <code>edit_user_profile_update</code> doesn't work as well. Setting the action priority to a high number (executed later) doesn't help either. <code>insert_user_meta</code> filter works, but only returns native WP's user meta, not WooCommerce customer's meta.</p>
[ { "answer_id": 375980, "author": "Lonk", "author_id": 77848, "author_profile": "https://wordpress.stackexchange.com/users/77848", "pm_score": 1, "selected": false, "text": "<p>My solution would be this:</p>\n<pre><code>function get_all_user_data($user_id) {\n\n $user_data = get_userda...
2020/10/02
[ "https://wordpress.stackexchange.com/questions/375799", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/138610/" ]
I am trying to get all user details (including WooCommerce meta data) in a function that is called with `user_register` and `profile_update` hooks. This is the simplified code: ``` function get_all_user_data($user_id) { $user_data = get_userdata($user_id); $login = $user_data->user_login; $b_firstname = get_user_meta($user_id, 'billing_first_name', true); } add_action('user_register','get_all_user_data'); add_action('profile_update','get_all_user_data'); ``` **The behavior:** 1. User is registered, I can access it's userdata (e.g. login) immediately 2. WooCommerce billing address is updated and saved, however I still only can access the $login variable, 'billing\_first\_name' meta is apparently still empty at this time 3. WooCommerce shipping address is updated and saved, after this I can access the billing information that were saved in previous step, but not the shipping data that was saved in current step The same goes for a scenario in which the user is registered during WooCommerce checkout, no WC data is accessible at that time yet. PS: I have also tried the `woocommerce_after_save_address_validation` hook, but that seems to have the same behavior as the `profile_update` in my case. **Edit:** `edit_user_profile_update` doesn't work as well. Setting the action priority to a high number (executed later) doesn't help either. `insert_user_meta` filter works, but only returns native WP's user meta, not WooCommerce customer's meta.
I got it working. The key was the `woocommerce_update_customer` action. In the end my function was triggered only by these two actions: ``` add_action('user_register','get_all_user_data', 99); add_action('woocommerce_update_customer','get_all_user_data', 99); ``` I don't need the `profile_update` because I don't need to track changes in default WP's user data. However it can be used along with woocommerce\_update \_customer, but keep in mind your function will be triggered twice.
375,880
<p>when I activated the theme. it is only one page. the navbar links are Home #About #Services #Contact</p> <p>the problem when I make template name on the frontpage</p> <pre><code>&lt;?php /* Template Name: front-page */ get_header(); ?&gt; </code></pre> <p>then I created a page from the dashboard called Home</p> <p>it added slug /home at the end of the url</p> <p>so the website url differed because of this homepage template. it added the home slug the url. I need to remove /home slug. just want the same link without changing.</p> <p>what should I do, please? to make template for homepage without changing the url of the website?</p> <p>and many thanks in advance.</p>
[ { "answer_id": 375834, "author": "Anarko", "author_id": 195470, "author_profile": "https://wordpress.stackexchange.com/users/195470", "pm_score": 1, "selected": false, "text": "<p>Manually Fix Another Update in Process</p>\n<p>First you need to visit the cPanel dashboard of your WordPres...
2020/10/03
[ "https://wordpress.stackexchange.com/questions/375880", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/188733/" ]
when I activated the theme. it is only one page. the navbar links are Home #About #Services #Contact the problem when I make template name on the frontpage ``` <?php /* Template Name: front-page */ get_header(); ?> ``` then I created a page from the dashboard called Home it added slug /home at the end of the url so the website url differed because of this homepage template. it added the home slug the url. I need to remove /home slug. just want the same link without changing. what should I do, please? to make template for homepage without changing the url of the website? and many thanks in advance.
Manually Fix Another Update in Process First you need to visit the cPanel dashboard of your WordPress hosting account. Under the database section, click on the phpMyAdmin icon. [![enter image description here](https://i.stack.imgur.com/RL5DN.png)](https://i.stack.imgur.com/RL5DN.png) Next you need to select your WordPress database in phpMyAdmin. This will show you all the tables inside your WordPress database. You need to click on the Browse button next to the WordPress options **table (wp\_options)**. [![enter image description here](https://i.stack.imgur.com/FLMPT.png)](https://i.stack.imgur.com/FLMPT.png) This will show you all the rows inside the options table. You need to find the row with the option name ‘**core\_updater.lock**’ and click on the delete button next to it. [![Delete core updater lock option](https://i.stack.imgur.com/IALKe.png)](https://i.stack.imgur.com/IALKe.png) PhpMyAdmin will now delete the row from your WordPress database. You can switch back to your WordPress website and proceed with updating your WordPress website.
376,081
<p>I am trying to add the post (pages, posts) excerpt in the <code>wp-json/wp/v2/search</code> get endpoint but this endpoint seems to not take into account the <code>register_rest_field</code> method.</p> <pre class="lang-php prettyprint-override"><code>add_action('rest_api_init', function() { register_rest_field('post', 'excerpt', array( 'get_callback' =&gt; function ($post_arr) { die(var_dump($post_arr)); return $post_arr['excerpt']; }, )); register_rest_field('page', 'excerpt', array( 'get_callback' =&gt; function ($post_arr) { die(var_dump($post_arr)); return $post_arr['excerpt']; }, )); }); </code></pre> <p>This causes <code>wp-json/wp/v2/pages</code> and <code>wp-json/wp/v2/posts</code> to die, but <code>wp-json/wp/v2/search</code> works perfectly, although it renders posts and pages.</p> <p>Any idea how I can add my excerpt to the results of the <code>wp-json/wp/v2/search</code> route?</p>
[ { "answer_id": 376085, "author": "Sally CJ", "author_id": 137402, "author_profile": "https://wordpress.stackexchange.com/users/137402", "pm_score": 4, "selected": true, "text": "<p>For the search endpoint, the object type (the first parameter for <code>register_rest_field()</code>) is <c...
2020/10/07
[ "https://wordpress.stackexchange.com/questions/376081", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/97197/" ]
I am trying to add the post (pages, posts) excerpt in the `wp-json/wp/v2/search` get endpoint but this endpoint seems to not take into account the `register_rest_field` method. ```php add_action('rest_api_init', function() { register_rest_field('post', 'excerpt', array( 'get_callback' => function ($post_arr) { die(var_dump($post_arr)); return $post_arr['excerpt']; }, )); register_rest_field('page', 'excerpt', array( 'get_callback' => function ($post_arr) { die(var_dump($post_arr)); return $post_arr['excerpt']; }, )); }); ``` This causes `wp-json/wp/v2/pages` and `wp-json/wp/v2/posts` to die, but `wp-json/wp/v2/search` works perfectly, although it renders posts and pages. Any idea how I can add my excerpt to the results of the `wp-json/wp/v2/search` route?
For the search endpoint, the object type (the first parameter for `register_rest_field()`) is `search-result` and not the post type (e.g. `post`, `page`, etc.). So try with this, which worked for me: ```php add_action( 'rest_api_init', function () { // Registers a REST field for the /wp/v2/search endpoint. register_rest_field( 'search-result', 'excerpt', array( 'get_callback' => function ( $post_arr ) { return $post_arr['excerpt']; }, ) ); } ); ```
376,094
<p>As the title states, I need to pass at least one parameter, maybe more, to the <a href="https://developer.wordpress.org/reference/functions/add_shortcode/" rel="nofollow noreferrer"><code>add_shortcode()</code></a> function. In other words, those parameters I am passing will be used in the callback function of <code>add_shortcode()</code>. How can I do that?</p> <p>Please note, those have NOTHING to do with the following structure <code>[shortcode 1 2 3]</code> where <code>1</code>, <code>2</code>, and <code>3</code> are the parameters passed by the user. In my case, the parameters are for programming purposes only and should not be the user's responsibility.</p> <p>Thanks</p>
[ { "answer_id": 376096, "author": "GeorgeP", "author_id": 160985, "author_profile": "https://wordpress.stackexchange.com/users/160985", "pm_score": 0, "selected": false, "text": "<p>You can pass an array of attributes ($atts) in the callback function that will run whenever you run add_sho...
2020/10/07
[ "https://wordpress.stackexchange.com/questions/376094", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/34253/" ]
As the title states, I need to pass at least one parameter, maybe more, to the [`add_shortcode()`](https://developer.wordpress.org/reference/functions/add_shortcode/) function. In other words, those parameters I am passing will be used in the callback function of `add_shortcode()`. How can I do that? Please note, those have NOTHING to do with the following structure `[shortcode 1 2 3]` where `1`, `2`, and `3` are the parameters passed by the user. In my case, the parameters are for programming purposes only and should not be the user's responsibility. Thanks
You can use a [closure](https://www.php.net/manual/en/class.closure.php) for that together with the `use` keyword. Simple example: ``` $dynamic_value = 4; add_shortcode( 'shortcodename', function( $attributes, $content, $shortcode_name ) use $dynamic_value { return $dynamic_value; } ); ``` See also [Passing a parameter to filter and action functions](https://wordpress.stackexchange.com/a/45920/73).
376,116
<pre><code>soliloquy( the_field( 'slider' ) ); </code></pre> <p>This is my code to add the ID for a slider from a ACF number field to a slider function call however it outputs the ID and doesn't execute the soliloquy function.</p> <p>I think it might have something to do with the single qoutes.</p> <p>Not sure how to wrap the slider ID in single qoutes</p>
[ { "answer_id": 376117, "author": "Dev", "author_id": 104464, "author_profile": "https://wordpress.stackexchange.com/users/104464", "pm_score": 0, "selected": false, "text": "<p>This works but i prefer to use the ACF specific custom field function</p>\n<pre><code>soliloquy( get_post_meta(...
2020/10/08
[ "https://wordpress.stackexchange.com/questions/376116", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/104464/" ]
``` soliloquy( the_field( 'slider' ) ); ``` This is my code to add the ID for a slider from a ACF number field to a slider function call however it outputs the ID and doesn't execute the soliloquy function. I think it might have something to do with the single qoutes. Not sure how to wrap the slider ID in single qoutes
You need to use **get\_field()** function instead. It will RETURN the value instead of printing. So, your code will be: ``` soliloquy( get_field( 'slider' ) ); ```
376,288
<p>I have a simple Gutenberg block that styles text as a <a href="https://github.com/prtksxna/a-sticky-note/" rel="nofollow noreferrer">post it note</a>. It uses a <code>BlockControls</code> to show some basic formatting like alignment and text styles. Since I upgraded to 5.5, to <code>BlockControls</code> doesn't show up floating over the widget. However, if I change my setting to be <em>Top Toolbar</em> it shows up on top and functions normally (<a href="https://i.stack.imgur.com/sc0Kw.png" rel="nofollow noreferrer">setting screenshot</a>). Note that the <code>InspectorControls</code> are showing up just fine. Here is my `index.js':</p> <pre class="lang-js prettyprint-override"><code>/* eslint no-unused-vars: 0 */ import { registerBlockType } from '@wordpress/blocks'; import { RichText, AlignmentToolbar, BlockControls, InspectorControls, ColorPalette, } from '@wordpress/block-editor'; import { PanelBody, PanelRow, FontSizePicker } from '@wordpress/components'; import { __ } from '@wordpress/i18n'; registerBlockType( 'sticky-note/sticky-note', { title: 'Sticky note', icon: 'pressthis', category: 'layout', styles: [ { name: 'paper', label: 'Paper', // TODO: What to do here? Use _x isDefault: true, }, { name: 'flat', label: 'Flat', }, ], supports: { align: true, alignWide: false, reusable: false, lightBlockWrapper: true, }, attributes: { content: { type: 'array', source: 'children', selector: 'p', }, alignment: { type: 'string', default: 'none', }, color: { type: 'string', default: '#f9eeaa', }, fontSize: { type: 'number', default: 16, }, }, example: { attributes: { content: 'Type something…', alignment: 'center', }, }, edit( props ) { const { attributes: { content, alignment, color, fontSize }, setAttributes, } = props; const onChangeContent = ( newContent ) =&gt; { setAttributes( { content: newContent } ); }; const onChangeAlignment = ( newAlignment ) =&gt; { props.setAttributes( { alignment: newAlignment === undefined ? 'none' : newAlignment, } ); }; const onChangeColor = ( newColor ) =&gt; { props.setAttributes( { color: newColor === undefined ? '#f9eeaa' : newColor, } ); }; const fontSizes = [ { name: __( 'Normal' ), slug: 'normal', size: 16, }, { name: __( 'Medium' ), slug: 'medium', size: 20, }, { name: __( 'Large' ), slug: 'large', size: 36, }, { name: __( 'Huge' ), slug: 'huge', size: 48, }, ]; const fallbackFontSize = 20; const onFontSizeChange = ( newFontSize ) =&gt; { props.setAttributes( { fontSize: newFontSize === undefined ? fallbackFontSize : newFontSize, } ); }; return ( &lt;div&gt; { &lt;BlockControls&gt; &lt;AlignmentToolbar value={ alignment } onChange={ onChangeAlignment } /&gt; &lt;/BlockControls&gt; } { &lt;InspectorControls&gt; &lt;PanelBody title={ __( 'Color' ) }&gt; &lt;PanelRow&gt; &lt;ColorPalette disableCustomColors={ false } value={ color } onChange={ onChangeColor } clearable={ true } /&gt; &lt;/PanelRow&gt; &lt;/PanelBody&gt; &lt;PanelBody title={ __( 'Font size' ) }&gt; &lt;PanelRow&gt; &lt;FontSizePicker fontSizes={ fontSizes } fallbackFontSize={ fallbackFontSize } value={ fontSize } onChange={ onFontSizeChange } /&gt; &lt;/PanelRow&gt; &lt;/PanelBody&gt; &lt;/InspectorControls&gt; } &lt;RichText tagName=&quot;p&quot; className=&quot;wp-block-sticky-note-sticky-note&quot; style={ { textAlign: alignment, backgroundColor: color, fontSize, } } onChange={ onChangeContent } value={ content } /&gt; &lt;/div&gt; ); }, save: ( props ) =&gt; { return ( &lt;RichText.Content className={ `sticky-note-${ props.attributes.alignment }` } style={ { fontSize: props.attributes.fontSize, backgroundColor: props.attributes.color, } } tagName=&quot;p&quot; value={ props.attributes.content } /&gt; ); }, } ); </code></pre> <p>This is what the block looks like in the editor, see the floating block controls are missing: <a href="https://i.stack.imgur.com/MgWkB.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/MgWkB.png" alt="block without toolbar" /></a></p> <p>But they show up fine and work when the top toolbar setting is selected: <a href="https://i.stack.imgur.com/oqiJD.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/oqiJD.png" alt="top toolbar working fine" /></a></p> <p>I have tried removing all the CSS but that doesn't seem to have any effect. I have tested it up to 5.2, where it was working fine. You can find the entire code base on <a href="https://github.com/prtksxna/a-sticky-note" rel="nofollow noreferrer">Github</a>.</p>
[ { "answer_id": 376290, "author": "Sally CJ", "author_id": 137402, "author_profile": "https://wordpress.stackexchange.com/users/137402", "pm_score": 3, "selected": true, "text": "<p>So I tested your <a href=\"https://github.com/prtksxna/a-sticky-note\" rel=\"nofollow noreferrer\">code</a>...
2020/10/11
[ "https://wordpress.stackexchange.com/questions/376288", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/148774/" ]
I have a simple Gutenberg block that styles text as a [post it note](https://github.com/prtksxna/a-sticky-note/). It uses a `BlockControls` to show some basic formatting like alignment and text styles. Since I upgraded to 5.5, to `BlockControls` doesn't show up floating over the widget. However, if I change my setting to be *Top Toolbar* it shows up on top and functions normally ([setting screenshot](https://i.stack.imgur.com/sc0Kw.png)). Note that the `InspectorControls` are showing up just fine. Here is my `index.js': ```js /* eslint no-unused-vars: 0 */ import { registerBlockType } from '@wordpress/blocks'; import { RichText, AlignmentToolbar, BlockControls, InspectorControls, ColorPalette, } from '@wordpress/block-editor'; import { PanelBody, PanelRow, FontSizePicker } from '@wordpress/components'; import { __ } from '@wordpress/i18n'; registerBlockType( 'sticky-note/sticky-note', { title: 'Sticky note', icon: 'pressthis', category: 'layout', styles: [ { name: 'paper', label: 'Paper', // TODO: What to do here? Use _x isDefault: true, }, { name: 'flat', label: 'Flat', }, ], supports: { align: true, alignWide: false, reusable: false, lightBlockWrapper: true, }, attributes: { content: { type: 'array', source: 'children', selector: 'p', }, alignment: { type: 'string', default: 'none', }, color: { type: 'string', default: '#f9eeaa', }, fontSize: { type: 'number', default: 16, }, }, example: { attributes: { content: 'Type something…', alignment: 'center', }, }, edit( props ) { const { attributes: { content, alignment, color, fontSize }, setAttributes, } = props; const onChangeContent = ( newContent ) => { setAttributes( { content: newContent } ); }; const onChangeAlignment = ( newAlignment ) => { props.setAttributes( { alignment: newAlignment === undefined ? 'none' : newAlignment, } ); }; const onChangeColor = ( newColor ) => { props.setAttributes( { color: newColor === undefined ? '#f9eeaa' : newColor, } ); }; const fontSizes = [ { name: __( 'Normal' ), slug: 'normal', size: 16, }, { name: __( 'Medium' ), slug: 'medium', size: 20, }, { name: __( 'Large' ), slug: 'large', size: 36, }, { name: __( 'Huge' ), slug: 'huge', size: 48, }, ]; const fallbackFontSize = 20; const onFontSizeChange = ( newFontSize ) => { props.setAttributes( { fontSize: newFontSize === undefined ? fallbackFontSize : newFontSize, } ); }; return ( <div> { <BlockControls> <AlignmentToolbar value={ alignment } onChange={ onChangeAlignment } /> </BlockControls> } { <InspectorControls> <PanelBody title={ __( 'Color' ) }> <PanelRow> <ColorPalette disableCustomColors={ false } value={ color } onChange={ onChangeColor } clearable={ true } /> </PanelRow> </PanelBody> <PanelBody title={ __( 'Font size' ) }> <PanelRow> <FontSizePicker fontSizes={ fontSizes } fallbackFontSize={ fallbackFontSize } value={ fontSize } onChange={ onFontSizeChange } /> </PanelRow> </PanelBody> </InspectorControls> } <RichText tagName="p" className="wp-block-sticky-note-sticky-note" style={ { textAlign: alignment, backgroundColor: color, fontSize, } } onChange={ onChangeContent } value={ content } /> </div> ); }, save: ( props ) => { return ( <RichText.Content className={ `sticky-note-${ props.attributes.alignment }` } style={ { fontSize: props.attributes.fontSize, backgroundColor: props.attributes.color, } } tagName="p" value={ props.attributes.content } /> ); }, } ); ``` This is what the block looks like in the editor, see the floating block controls are missing: [![block without toolbar](https://i.stack.imgur.com/MgWkB.png)](https://i.stack.imgur.com/MgWkB.png) But they show up fine and work when the top toolbar setting is selected: [![top toolbar working fine](https://i.stack.imgur.com/oqiJD.png)](https://i.stack.imgur.com/oqiJD.png) I have tried removing all the CSS but that doesn't seem to have any effect. I have tested it up to 5.2, where it was working fine. You can find the entire code base on [Github](https://github.com/prtksxna/a-sticky-note).
So I tested your [code](https://github.com/prtksxna/a-sticky-note), and it seems that the issue happened because you enabled the `lightBlockWrapper` support for your block type (i.e. `lightBlockWrapper: true` in the `support` property), which then doesn't wrap the block in `.wp-block` — check a [sample diff here](https://www.diffchecker.com/FnrBD8um). And to fix the issue, you'd only need to disable the `lightBlockWrapper` support — use `lightBlockWrapper: false` or just don't set `lightBlockWrapper` at all..
376,309
<p>I've made a form on WordPress theme frontend that let registered user change some of their user metadata on page, but it didn't work, code like below:</p> <pre><code> &lt;form name=&quot;update_basic_user_meta&quot; id=&quot;update_basic_user_meta&quot; action=&quot;&lt;?php echo esc_url( home_url() ); ?&gt;?update_basic_user_meta=true&quot; method=&quot;POST&quot;&gt; &lt;select name=&quot;gender&quot;&gt; &lt;option value=&quot;male&quot; &gt;&lt;?php _e('Male','text-domain');?&gt;&lt;/option&gt; &lt;option value=&quot;female&quot; &gt;&lt;?php _e('Female','text-domain');?&gt;&lt;/option&gt; &lt;/select&gt; &lt;div&gt; &lt;label&gt;&lt;input type=&quot;radio&quot; name=&quot;specialty&quot; value=&quot;0&quot;&gt; &lt;?php _e('Read','text-domain');?&gt;&lt;/label&gt;&lt;br&gt; &lt;label&gt;&lt;input type=&quot;radio&quot; name=&quot;specialty&quot; value=&quot;1&quot;&gt; &lt;?php _e('Write','text-domain');?&gt;&lt;/label&gt;&lt;br&gt; &lt;label&gt;&lt;input type=&quot;radio&quot; name=&quot;specialty&quot; value=&quot;2&quot;&gt; &lt;?php _e('Translate','text-domain');?&gt;&lt;/label&gt; &lt;/div&gt; &lt;button name=&quot;submit&quot; type=&quot;submit&quot;&gt;&lt;?php _e('Submit','text-domain');?&gt;&lt;/button&gt; &lt;input type=&quot;hidden&quot; name=&quot;redirect_to&quot; value=&quot;&lt;?php echo $_SERVER['REQUEST_URI']; ?&gt;&quot; /&gt; &lt;/form&gt; &lt;?php function update_basic_user_meta() { $user_id = current_user_id(); update_user_meta( $user_id, 'gender', $_POST['gender'] ); update_user_meta( $user_id, 'specialty', $_POST['specialty'] ); } add_filter('init', 'update_basic_user_meta'); ?&gt; </code></pre> <p>The &quot;Gender&quot; &quot;Specialty&quot; user metadata field is existed and work well on backend user profile page.</p> <p>Don't have a clue how this form didn’t affect any of the user metadata.</p> <p>Please help :) Thank you all.</p>
[ { "answer_id": 376322, "author": "Sally CJ", "author_id": 137402, "author_profile": "https://wordpress.stackexchange.com/users/137402", "pm_score": 3, "selected": true, "text": "<p>There are 3 main issues in your code:</p>\n<ol>\n<li><p>I see you're using <code>current_user_id()</code> w...
2020/10/12
[ "https://wordpress.stackexchange.com/questions/376309", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/148298/" ]
I've made a form on WordPress theme frontend that let registered user change some of their user metadata on page, but it didn't work, code like below: ``` <form name="update_basic_user_meta" id="update_basic_user_meta" action="<?php echo esc_url( home_url() ); ?>?update_basic_user_meta=true" method="POST"> <select name="gender"> <option value="male" ><?php _e('Male','text-domain');?></option> <option value="female" ><?php _e('Female','text-domain');?></option> </select> <div> <label><input type="radio" name="specialty" value="0"> <?php _e('Read','text-domain');?></label><br> <label><input type="radio" name="specialty" value="1"> <?php _e('Write','text-domain');?></label><br> <label><input type="radio" name="specialty" value="2"> <?php _e('Translate','text-domain');?></label> </div> <button name="submit" type="submit"><?php _e('Submit','text-domain');?></button> <input type="hidden" name="redirect_to" value="<?php echo $_SERVER['REQUEST_URI']; ?>" /> </form> <?php function update_basic_user_meta() { $user_id = current_user_id(); update_user_meta( $user_id, 'gender', $_POST['gender'] ); update_user_meta( $user_id, 'specialty', $_POST['specialty'] ); } add_filter('init', 'update_basic_user_meta'); ?> ``` The "Gender" "Specialty" user metadata field is existed and work well on backend user profile page. Don't have a clue how this form didn’t affect any of the user metadata. Please help :) Thank you all.
There are 3 main issues in your code: 1. I see you're using `current_user_id()` which does not exist in WordPress, so I believe that should be [`get_current_user_id()`](https://developer.wordpress.org/reference/functions/get_current_user_id/). 2. Your `update_basic_user_meta()` function basically would work in updating the user's metadata, but you need to check whether the POST data (`gender` and `specialty`) are actually set before proceeding to update the metadata, and that the GET data named `update_basic_user_meta` is also set, which means the form was submitted. However, if I were you, I would use a [nonce field](https://developer.wordpress.org/reference/functions/wp_nonce_field/) than a simple GET query. 3. You need to highlight the current selection for the "Gender" and "Specialty" options, so that users know what have they selected and whether it was actually saved. So, * For the "Gender" option (which uses `select` menu), you can use [`selected()`](https://developer.wordpress.org/reference/functions/selected/). * For the "Specialty" option (which uses `radio` buttons), you can use [`checked()`](https://developer.wordpress.org/reference/functions/checked/). And despite `add_filter()` works, `init` is an action hook, so you should use `add_action()`: ```php add_action( 'init', 'update_basic_user_meta' ); // use this //add_filter( 'init', 'update_basic_user_meta' ); // not this ``` ### Sample snippets that would make your form works as expected 1. Highlight the current selection for the "Gender" option: ```html <?php $gender = get_user_meta( get_current_user_id(), 'gender', true ); ?> <select name="gender"> <option value="male"<?php selected( 'male', $gender ); ?>><?php _e( 'Male', 'text-domain' ); ?></option> <option value="female"<?php selected( 'female', $gender ); ?>><?php _e( 'Female', 'text-domain' ); ?></option> </select> ``` 2. Highlight the current selection for the "Specialty" option: ```html <?php $specialty = get_user_meta( get_current_user_id(), 'specialty', true ); ?> <div> <label><input type="radio" name="specialty" value="0"<?php checked( '0', $specialty ); ?>> <?php _e( 'Read', 'text-domain' ); ?></label><br> <label><input type="radio" name="specialty" value="1"<?php checked( '1', $specialty ); ?>> <?php _e( 'Write', 'text-domain' ); ?></label><br> <label><input type="radio" name="specialty" value="2"<?php checked( '2', $specialty ); ?>> <?php _e( 'Translate', 'text-domain' ); ?></label> </div> ``` 3. Function to update the user's metadata: ```php function update_basic_user_meta() { if ( ! empty( $_GET['update_basic_user_meta'] ) && isset( $_POST['gender'], $_POST['specialty'] ) && $user_id = get_current_user_id() ) { update_user_meta( $user_id, 'gender', sanitize_text_field( $_POST['gender'] ) ); update_user_meta( $user_id, 'specialty', sanitize_text_field( $_POST['specialty'] ) ); if ( ! empty( $_POST['redirect_to'] ) ) { wp_redirect( $_POST['redirect_to'] ); exit; } } } ```
376,317
<p>I'm being faced very often when I typically go into a saved draft, edit a post and then save it. I'm getting the error:</p> <blockquote> <p>Updating failed. The response is not a valid JSON response.</p> </blockquote> <p>I'm finding that I can often publish, but if I continue to save as a draft, I may or may not get what I was expecting. I'm seeing titles disappear and other pieces of content. I have reached out to Wordpress and was told to change the 'permalinks' settings and then change back again. This did not work. I was also told to roll back to classic editor, which seems to work, but I want to continue using blocks. How can I resolve this issue without having to downgrade wordpress for our writers?</p> <p>As was suggested here is the debug below</p> <pre><code>Exception { name: &quot;NS_ERROR_FAILURE&quot;, message: &quot;&quot;, result: 2147500037, filename: &quot;https://example.com/libby-heaney-bridges-the-gap-be…ormer-quantum-scientist-she-is-now-a-full-time-artist/embed/&quot;, lineNumber: 8, columnNumber: 0, data: null, stack: &quot;l@https://example.com/libby-heaney-bridges-the-gap-between-science-and-art-a-former-quantum-scientist-she-is-now-a-full-time-artist/embed/:8:385\n@https://example.com/libby-heaney-bridges-the-gap-between-science-and-art-a-former-quantum-scientist-she-is-now-a-full-time-artist/embed/:8:1110\n@https://example.com/libby-heaney-bridges-the-gap-between-science-and-art-a-former-quantum-scientist-she-is-now-a-full-time-artist/embed/:8:1788\n&quot; } </code></pre>
[ { "answer_id": 376322, "author": "Sally CJ", "author_id": 137402, "author_profile": "https://wordpress.stackexchange.com/users/137402", "pm_score": 3, "selected": true, "text": "<p>There are 3 main issues in your code:</p>\n<ol>\n<li><p>I see you're using <code>current_user_id()</code> w...
2020/10/12
[ "https://wordpress.stackexchange.com/questions/376317", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/194049/" ]
I'm being faced very often when I typically go into a saved draft, edit a post and then save it. I'm getting the error: > > Updating failed. The response is not a valid JSON response. > > > I'm finding that I can often publish, but if I continue to save as a draft, I may or may not get what I was expecting. I'm seeing titles disappear and other pieces of content. I have reached out to Wordpress and was told to change the 'permalinks' settings and then change back again. This did not work. I was also told to roll back to classic editor, which seems to work, but I want to continue using blocks. How can I resolve this issue without having to downgrade wordpress for our writers? As was suggested here is the debug below ``` Exception { name: "NS_ERROR_FAILURE", message: "", result: 2147500037, filename: "https://example.com/libby-heaney-bridges-the-gap-be…ormer-quantum-scientist-she-is-now-a-full-time-artist/embed/", lineNumber: 8, columnNumber: 0, data: null, stack: "l@https://example.com/libby-heaney-bridges-the-gap-between-science-and-art-a-former-quantum-scientist-she-is-now-a-full-time-artist/embed/:8:385\n@https://example.com/libby-heaney-bridges-the-gap-between-science-and-art-a-former-quantum-scientist-she-is-now-a-full-time-artist/embed/:8:1110\n@https://example.com/libby-heaney-bridges-the-gap-between-science-and-art-a-former-quantum-scientist-she-is-now-a-full-time-artist/embed/:8:1788\n" } ```
There are 3 main issues in your code: 1. I see you're using `current_user_id()` which does not exist in WordPress, so I believe that should be [`get_current_user_id()`](https://developer.wordpress.org/reference/functions/get_current_user_id/). 2. Your `update_basic_user_meta()` function basically would work in updating the user's metadata, but you need to check whether the POST data (`gender` and `specialty`) are actually set before proceeding to update the metadata, and that the GET data named `update_basic_user_meta` is also set, which means the form was submitted. However, if I were you, I would use a [nonce field](https://developer.wordpress.org/reference/functions/wp_nonce_field/) than a simple GET query. 3. You need to highlight the current selection for the "Gender" and "Specialty" options, so that users know what have they selected and whether it was actually saved. So, * For the "Gender" option (which uses `select` menu), you can use [`selected()`](https://developer.wordpress.org/reference/functions/selected/). * For the "Specialty" option (which uses `radio` buttons), you can use [`checked()`](https://developer.wordpress.org/reference/functions/checked/). And despite `add_filter()` works, `init` is an action hook, so you should use `add_action()`: ```php add_action( 'init', 'update_basic_user_meta' ); // use this //add_filter( 'init', 'update_basic_user_meta' ); // not this ``` ### Sample snippets that would make your form works as expected 1. Highlight the current selection for the "Gender" option: ```html <?php $gender = get_user_meta( get_current_user_id(), 'gender', true ); ?> <select name="gender"> <option value="male"<?php selected( 'male', $gender ); ?>><?php _e( 'Male', 'text-domain' ); ?></option> <option value="female"<?php selected( 'female', $gender ); ?>><?php _e( 'Female', 'text-domain' ); ?></option> </select> ``` 2. Highlight the current selection for the "Specialty" option: ```html <?php $specialty = get_user_meta( get_current_user_id(), 'specialty', true ); ?> <div> <label><input type="radio" name="specialty" value="0"<?php checked( '0', $specialty ); ?>> <?php _e( 'Read', 'text-domain' ); ?></label><br> <label><input type="radio" name="specialty" value="1"<?php checked( '1', $specialty ); ?>> <?php _e( 'Write', 'text-domain' ); ?></label><br> <label><input type="radio" name="specialty" value="2"<?php checked( '2', $specialty ); ?>> <?php _e( 'Translate', 'text-domain' ); ?></label> </div> ``` 3. Function to update the user's metadata: ```php function update_basic_user_meta() { if ( ! empty( $_GET['update_basic_user_meta'] ) && isset( $_POST['gender'], $_POST['specialty'] ) && $user_id = get_current_user_id() ) { update_user_meta( $user_id, 'gender', sanitize_text_field( $_POST['gender'] ) ); update_user_meta( $user_id, 'specialty', sanitize_text_field( $_POST['specialty'] ) ); if ( ! empty( $_POST['redirect_to'] ) ) { wp_redirect( $_POST['redirect_to'] ); exit; } } } ```
376,430
<p>After the recent update of WordPress, version 5.5.1.</p> <p>Whenever I enabled the debug mode, there is a 2em gap between WordPress admin menu and the bar.</p> <pre><code>.php-error #adminmenuback, .php-error #adminmenuwrap { margin-top: 2em; } </code></pre> <p>Found out that this is showing because there is a hidden error somewhere on the website?</p> <p>How I could show that error?</p>
[ { "answer_id": 376431, "author": "Mocsid", "author_id": 196053, "author_profile": "https://wordpress.stackexchange.com/users/196053", "pm_score": 1, "selected": true, "text": "<p>---Fix---</p>\n<p>That CSS gap will only show when there is a &quot;Hidden&quot; error.</p>\n<p>If these cond...
2020/10/14
[ "https://wordpress.stackexchange.com/questions/376430", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/196053/" ]
After the recent update of WordPress, version 5.5.1. Whenever I enabled the debug mode, there is a 2em gap between WordPress admin menu and the bar. ``` .php-error #adminmenuback, .php-error #adminmenuwrap { margin-top: 2em; } ``` Found out that this is showing because there is a hidden error somewhere on the website? How I could show that error?
---Fix--- That CSS gap will only show when there is a "Hidden" error. If these conditions are true, ``` if ( $error && WP_DEBUG && WP_DEBUG_DISPLAY && ini_get( 'display_errors' ) ``` the gap will show, it means that **$error** variable is not empty, we should show the value in a log file. To solve this issue, we need to show that hidden error by adding this code.. ``` wp-admin/admin-header.php on line 201 $error = error_get_last(); error_log('===================This is the hidden error=================='); error_log(print_r($error,true)); error_log('=================Error Setting display======================'); error_log('WP_DEBUG'); error_log(print_r(WP_DEBUG ,true)); error_log('WP_DEBUG_DISPLAY'); error_log(print_r(WP_DEBUG_DISPLAY,true)); error_log('display_errors ini setting'); error_log(print_r(ini_get( 'display_errors' ),true)); ``` After checking the **debug.log**, we can now see and fix the error. This is related to this issue [How to fix the admin menu margin-top bug in WordPress 5.5?](https://wordpress.stackexchange.com/questions/372897/how-to-fix-the-admin-menu-margin-top-bug-in-wordpress-5-5) and my answer also resolved it...
376,440
<p>I want to edit the <code>core/heading</code> block so it changes it's markup from <code>&lt;h1&gt;Hello world&lt;/h1&gt;</code> to <code>&lt;h1&gt;&lt;span&gt;Hello world&lt;/span&gt;&lt;/h1&gt;</code>. Note the <code>&lt;span&gt;</code> element in between.</p> <p>The code below does not work as it should. It adds the span outside the block, as a wrapper. <code>&lt;span&gt;&lt;h1&gt;Hello world&lt;/h1&gt;&lt;/span&gt;</code>. Is there a way to alter the <code>&lt;BlockEdit/&gt;</code> element? And goal should be to not add the span element into the content field.</p> <p>Thought, if altering the edit part, should I also mirror this on the save part?</p> <pre><code>const { createHigherOrderComponent } = wp.compose; const { Fragment } = wp.element; const { InspectorControls } = wp.blockEditor; const { PanelBody } = wp.components; const withInspectorControls = createHigherOrderComponent( ( BlockEdit ) =&gt; { return ( props ) =&gt; { if (props.name !== &quot;core/heading&quot;) { return &lt;BlockEdit { ...props } /&gt;; } return ( &lt;Fragment&gt; &lt;span&gt; &lt;BlockEdit { ...props } /&gt; &lt;/span&gt; &lt;/Fragment&gt; ); }; }, &quot;withInspectorControl&quot; ); wp.hooks.addFilter( 'editor.BlockEdit', 'my-plugin/with-inspector-controls', withInspectorControls ); </code></pre>
[ { "answer_id": 376444, "author": "kraftner", "author_id": 47733, "author_profile": "https://wordpress.stackexchange.com/users/47733", "pm_score": 3, "selected": true, "text": "<p>Unfortunately there is now way to alter the markup of an existing block apart from <em>wrapping</em> it in ad...
2020/10/14
[ "https://wordpress.stackexchange.com/questions/376440", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/152589/" ]
I want to edit the `core/heading` block so it changes it's markup from `<h1>Hello world</h1>` to `<h1><span>Hello world</span></h1>`. Note the `<span>` element in between. The code below does not work as it should. It adds the span outside the block, as a wrapper. `<span><h1>Hello world</h1></span>`. Is there a way to alter the `<BlockEdit/>` element? And goal should be to not add the span element into the content field. Thought, if altering the edit part, should I also mirror this on the save part? ``` const { createHigherOrderComponent } = wp.compose; const { Fragment } = wp.element; const { InspectorControls } = wp.blockEditor; const { PanelBody } = wp.components; const withInspectorControls = createHigherOrderComponent( ( BlockEdit ) => { return ( props ) => { if (props.name !== "core/heading") { return <BlockEdit { ...props } />; } return ( <Fragment> <span> <BlockEdit { ...props } /> </span> </Fragment> ); }; }, "withInspectorControl" ); wp.hooks.addFilter( 'editor.BlockEdit', 'my-plugin/with-inspector-controls', withInspectorControls ); ```
Unfortunately there is now way to alter the markup of an existing block apart from *wrapping* it in additional markup: > > It receives the original block BlockEdit component and returns a new wrapped component. > Source: <https://developer.wordpress.org/block-editor/developers/filters/block-filters/#editor-blockedit> > > > To achieve what you want in the editor currently the only way would be to create your own version of the heading block replacing the core one. But what you can do, and probably is the better way to do it anyway since you leave the default markup in the DB in place, is change the markup on render using the [`render_block`](https://developer.wordpress.org/reference/hooks/render_block/) filter. You can then either use regular expressions or something more solid like a DOM Parser (e.g. <https://github.com/wasinger/htmlpagedom>) to alter the markup on output any way you like. ``` <?php add_filter('render_block', function ($blockContent, $block) { if ($block['blockName'] !== 'core/heading') { return $blockContent; } $pattern = '/(<h[^>]*>)(.*)(<\/h[1-7]{1}>)/i'; $replacement = '$1<span>$2</span>$3'; return preg_replace($pattern, $replacement, $blockContent); }, 10, 2); ``` I've also written [a blog post](https://kraftner.com/en/blog/the-taming-of-the-block-part-ii-the-practical-part/#post-processing-with-render-filters) on various ways to configure Gutenberg that also covers the `render_block` filter and some reasoning around it in case you want to dig deeper.
376,531
<p>I am workin on a plugin (for use on my own site). I recently added a button to the admin page that generates some text, and it works fine. This is what I use (pilfered from examples):</p> <pre><code>if (!current_user_can('manage_options')) { wp_die( __('You do not have sufficient galooph to access this page.') ); } if ($_POST['plugin_button'] == 'thing' &amp;&amp; check_admin_referer('thing_button_clicked')) { plugin_thing_button(); } echo '&lt;form action=&quot;options-general.php?page=plugin-list&quot; method=&quot;post&quot;&gt;'; wp_nonce_field('thing_button_clicked'); echo '&lt;input type=&quot;hidden&quot; value=&quot;thing&quot; name=&quot;plugin_button&quot; /&gt;'; submit_button('Generate new thing'); echo '&lt;/form&gt;'; </code></pre> <p>This works fine and calls the function as it should.</p> <p>Now I want a second button to do something completely unrelated.</p> <p>Here is what I tried, basically copying from above:</p> <pre><code>if (!current_user_can('manage_options')) { wp_die( __('You do not have sufficient galooph to access this page.') ); } if ($_POST['plugin_button'] == 'thing' &amp;&amp; check_admin_referer('thing_button_clicked')) { plugin_thing_button(); } if ($_POST['plugin_button2'] == 'thing2' &amp;&amp; check_admin_referer('thing2_button_clicked')) { plugin_thing2_button(); } echo '&lt;form action=&quot;options-general.php?page=plugin-list&quot; method=&quot;post&quot;&gt;'; wp_nonce_field('thing_button_clicked'); echo '&lt;input type=&quot;hidden&quot; value=&quot;thing&quot; name=&quot;plugin_button&quot; /&gt;'; submit_button('Generate new thing'); wp_nonce_field('thing2_button_clicked'); echo '&lt;input type=&quot;hidden&quot; value=&quot;thing2&quot; name=&quot;plugin_button2&quot; /&gt;'; submit_button('Generate new new thing'); echo '&lt;/form&gt;'; </code></pre> <p>The code for 2 buttons returns &quot;The link you followed has expired.&quot; for both buttons, i.e. the one that worked alone does not work either now.</p> <p>Where is my mistake? Thank you in advance!</p>
[ { "answer_id": 376444, "author": "kraftner", "author_id": 47733, "author_profile": "https://wordpress.stackexchange.com/users/47733", "pm_score": 3, "selected": true, "text": "<p>Unfortunately there is now way to alter the markup of an existing block apart from <em>wrapping</em> it in ad...
2020/10/15
[ "https://wordpress.stackexchange.com/questions/376531", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/196127/" ]
I am workin on a plugin (for use on my own site). I recently added a button to the admin page that generates some text, and it works fine. This is what I use (pilfered from examples): ``` if (!current_user_can('manage_options')) { wp_die( __('You do not have sufficient galooph to access this page.') ); } if ($_POST['plugin_button'] == 'thing' && check_admin_referer('thing_button_clicked')) { plugin_thing_button(); } echo '<form action="options-general.php?page=plugin-list" method="post">'; wp_nonce_field('thing_button_clicked'); echo '<input type="hidden" value="thing" name="plugin_button" />'; submit_button('Generate new thing'); echo '</form>'; ``` This works fine and calls the function as it should. Now I want a second button to do something completely unrelated. Here is what I tried, basically copying from above: ``` if (!current_user_can('manage_options')) { wp_die( __('You do not have sufficient galooph to access this page.') ); } if ($_POST['plugin_button'] == 'thing' && check_admin_referer('thing_button_clicked')) { plugin_thing_button(); } if ($_POST['plugin_button2'] == 'thing2' && check_admin_referer('thing2_button_clicked')) { plugin_thing2_button(); } echo '<form action="options-general.php?page=plugin-list" method="post">'; wp_nonce_field('thing_button_clicked'); echo '<input type="hidden" value="thing" name="plugin_button" />'; submit_button('Generate new thing'); wp_nonce_field('thing2_button_clicked'); echo '<input type="hidden" value="thing2" name="plugin_button2" />'; submit_button('Generate new new thing'); echo '</form>'; ``` The code for 2 buttons returns "The link you followed has expired." for both buttons, i.e. the one that worked alone does not work either now. Where is my mistake? Thank you in advance!
Unfortunately there is now way to alter the markup of an existing block apart from *wrapping* it in additional markup: > > It receives the original block BlockEdit component and returns a new wrapped component. > Source: <https://developer.wordpress.org/block-editor/developers/filters/block-filters/#editor-blockedit> > > > To achieve what you want in the editor currently the only way would be to create your own version of the heading block replacing the core one. But what you can do, and probably is the better way to do it anyway since you leave the default markup in the DB in place, is change the markup on render using the [`render_block`](https://developer.wordpress.org/reference/hooks/render_block/) filter. You can then either use regular expressions or something more solid like a DOM Parser (e.g. <https://github.com/wasinger/htmlpagedom>) to alter the markup on output any way you like. ``` <?php add_filter('render_block', function ($blockContent, $block) { if ($block['blockName'] !== 'core/heading') { return $blockContent; } $pattern = '/(<h[^>]*>)(.*)(<\/h[1-7]{1}>)/i'; $replacement = '$1<span>$2</span>$3'; return preg_replace($pattern, $replacement, $blockContent); }, 10, 2); ``` I've also written [a blog post](https://kraftner.com/en/blog/the-taming-of-the-block-part-ii-the-practical-part/#post-processing-with-render-filters) on various ways to configure Gutenberg that also covers the `render_block` filter and some reasoning around it in case you want to dig deeper.
376,539
<p>I am writing a plugin that will allow simple comment upvoting.</p> <p>I am trying to sort comments by the number of upvotes. But anything I do on the comments_array Hook gets somehow reset. My question is where and how?</p> <p>Here is my code:</p> <pre><code>add_filter( 'comments_array', 'biiird_order_comments_by_likes' ); function biiird_order_comments_by_likes( $array ) { $arraya = $array; usort($arraya, function($a, $b) { $likes_a = get_comment_meta( $a-&gt;comment_ID, 'likes', true ); $likes_b = get_comment_meta( $b-&gt;comment_ID, 'likes', true ); return ($likes_a &gt; $likes_b) ? -1 : 1; }); foreach ( $arraya as $comment ) { $comment-&gt;comment_content .= 'something'; } var_dump($arraya); var_dump($array); return $arraya; } </code></pre> <p>The <code>var_dump($arraya)</code> outputs a modified array in the proper order, but the comments show on a page as if the filter was not run.</p>
[ { "answer_id": 376444, "author": "kraftner", "author_id": 47733, "author_profile": "https://wordpress.stackexchange.com/users/47733", "pm_score": 3, "selected": true, "text": "<p>Unfortunately there is now way to alter the markup of an existing block apart from <em>wrapping</em> it in ad...
2020/10/15
[ "https://wordpress.stackexchange.com/questions/376539", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/194463/" ]
I am writing a plugin that will allow simple comment upvoting. I am trying to sort comments by the number of upvotes. But anything I do on the comments\_array Hook gets somehow reset. My question is where and how? Here is my code: ``` add_filter( 'comments_array', 'biiird_order_comments_by_likes' ); function biiird_order_comments_by_likes( $array ) { $arraya = $array; usort($arraya, function($a, $b) { $likes_a = get_comment_meta( $a->comment_ID, 'likes', true ); $likes_b = get_comment_meta( $b->comment_ID, 'likes', true ); return ($likes_a > $likes_b) ? -1 : 1; }); foreach ( $arraya as $comment ) { $comment->comment_content .= 'something'; } var_dump($arraya); var_dump($array); return $arraya; } ``` The `var_dump($arraya)` outputs a modified array in the proper order, but the comments show on a page as if the filter was not run.
Unfortunately there is now way to alter the markup of an existing block apart from *wrapping* it in additional markup: > > It receives the original block BlockEdit component and returns a new wrapped component. > Source: <https://developer.wordpress.org/block-editor/developers/filters/block-filters/#editor-blockedit> > > > To achieve what you want in the editor currently the only way would be to create your own version of the heading block replacing the core one. But what you can do, and probably is the better way to do it anyway since you leave the default markup in the DB in place, is change the markup on render using the [`render_block`](https://developer.wordpress.org/reference/hooks/render_block/) filter. You can then either use regular expressions or something more solid like a DOM Parser (e.g. <https://github.com/wasinger/htmlpagedom>) to alter the markup on output any way you like. ``` <?php add_filter('render_block', function ($blockContent, $block) { if ($block['blockName'] !== 'core/heading') { return $blockContent; } $pattern = '/(<h[^>]*>)(.*)(<\/h[1-7]{1}>)/i'; $replacement = '$1<span>$2</span>$3'; return preg_replace($pattern, $replacement, $blockContent); }, 10, 2); ``` I've also written [a blog post](https://kraftner.com/en/blog/the-taming-of-the-block-part-ii-the-practical-part/#post-processing-with-render-filters) on various ways to configure Gutenberg that also covers the `render_block` filter and some reasoning around it in case you want to dig deeper.
376,553
<p>I addes this code to allow SVG Uploads to the Media Library of wordpress:</p> <pre><code>function upload_svg ( $svg_mime ){ $svg_mime['svg'] = 'image/svg+xml'; return $svg_mime; } add_filter( 'upload_mimes', 'upload_svg' ); define('ALLOW_UNFILTERED_UPLOADS', true); </code></pre> <p>Than I added some SVGs to the Media Library. Using them works perfectly fine. The only Issue I have is that they will not be displayed in the Media Library. On other Pages in the Backend they display fine.</p> <p>Is there anything I can do to display them in the Media Tab aswell? I couln't find anything online on how to fix this issue.</p>
[ { "answer_id": 376444, "author": "kraftner", "author_id": 47733, "author_profile": "https://wordpress.stackexchange.com/users/47733", "pm_score": 3, "selected": true, "text": "<p>Unfortunately there is now way to alter the markup of an existing block apart from <em>wrapping</em> it in ad...
2020/10/15
[ "https://wordpress.stackexchange.com/questions/376553", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/112177/" ]
I addes this code to allow SVG Uploads to the Media Library of wordpress: ``` function upload_svg ( $svg_mime ){ $svg_mime['svg'] = 'image/svg+xml'; return $svg_mime; } add_filter( 'upload_mimes', 'upload_svg' ); define('ALLOW_UNFILTERED_UPLOADS', true); ``` Than I added some SVGs to the Media Library. Using them works perfectly fine. The only Issue I have is that they will not be displayed in the Media Library. On other Pages in the Backend they display fine. Is there anything I can do to display them in the Media Tab aswell? I couln't find anything online on how to fix this issue.
Unfortunately there is now way to alter the markup of an existing block apart from *wrapping* it in additional markup: > > It receives the original block BlockEdit component and returns a new wrapped component. > Source: <https://developer.wordpress.org/block-editor/developers/filters/block-filters/#editor-blockedit> > > > To achieve what you want in the editor currently the only way would be to create your own version of the heading block replacing the core one. But what you can do, and probably is the better way to do it anyway since you leave the default markup in the DB in place, is change the markup on render using the [`render_block`](https://developer.wordpress.org/reference/hooks/render_block/) filter. You can then either use regular expressions or something more solid like a DOM Parser (e.g. <https://github.com/wasinger/htmlpagedom>) to alter the markup on output any way you like. ``` <?php add_filter('render_block', function ($blockContent, $block) { if ($block['blockName'] !== 'core/heading') { return $blockContent; } $pattern = '/(<h[^>]*>)(.*)(<\/h[1-7]{1}>)/i'; $replacement = '$1<span>$2</span>$3'; return preg_replace($pattern, $replacement, $blockContent); }, 10, 2); ``` I've also written [a blog post](https://kraftner.com/en/blog/the-taming-of-the-block-part-ii-the-practical-part/#post-processing-with-render-filters) on various ways to configure Gutenberg that also covers the `render_block` filter and some reasoning around it in case you want to dig deeper.
376,616
<p>I've been developing a website using WP and to display some database information in the front-end of the site i've created a plugin. Right now i want to include a filtering function for that same information using the plugin, but it does not work.</p> <p>This is the file where i've created the filters, called <strong>show.php</strong></p> <pre><code>&lt;div class=&quot;container&quot;&gt; &lt;div class=&quot;row&quot;&gt; &lt;br /&gt; &lt;div class=&quot;col-md-3&quot;&gt; &lt;div class=&quot;list-group&quot;&gt; &lt;h6&gt;Modo de Confeção&lt;/h6&gt; &lt;div style=&quot;height: 180px; overflow-y: auto; overflow-x: hidden;&quot;&gt; &lt;?php $query = &quot;SELECT * FROM win_gab_modo_confecao ORDER BY designacaoModoConfecao&quot;; $result = $wpdb-&gt;get_results($query); foreach($result as $row) { ?&gt; &lt;div class=&quot;list-group-item checkbox&quot; style=&quot;font-size: 14;&quot;&gt; &lt;label&gt;&lt;input type=&quot;checkbox&quot; class=&quot;common_selector modoconf&quot; value=&quot;&lt;?php echo $row-&gt;idModoConfecao ?&gt;&quot; &gt; &lt;?php echo $row-&gt;designacaoModoConfecao ?&gt;&lt;/label&gt; &lt;/div&gt; &lt;?php } ?&gt; &lt;/div&gt; &lt;/div&gt;&lt;br&gt; &lt;div class=&quot;list-group&quot;&gt; &lt;h6&gt;Modo de Serviço&lt;/h6&gt; &lt;div style=&quot;overflow-y: auto; overflow-x: hidden;&quot;&gt; &lt;?php $query2 = &quot;SELECT * FROM win_gab_modo_servico ORDER BY designacaoModoServico&quot;; $result2 = $wpdb-&gt;get_results($query2); foreach($result2 as $row2) { ?&gt; &lt;div class=&quot;list-group-item checkbox&quot; style=&quot;font-size: 14;&quot;&gt; &lt;label&gt;&lt;input type=&quot;checkbox&quot; class=&quot;common_selector modoserv&quot; value=&quot;&lt;?php echo $row2-&gt;idModoServico ?&gt;&quot; &gt; &lt;?php echo $row2-&gt;designacaoModoServico ?&gt;&lt;/label&gt; &lt;/div&gt; &lt;?php } ?&gt; &lt;/div&gt; &lt;/div&gt;&lt;br&gt; &lt;div class=&quot;list-group&quot;&gt; &lt;h6&gt;Sub Categoria 1&lt;/h6&gt; &lt;div style=&quot;height: 180px; overflow-y: auto; overflow-x: hidden;&quot;&gt; &lt;?php $query3 = &quot;SELECT * FROM win_gab_sub_categorias WHERE subCategoria1 = '1' ORDER BY designacaoSubCategoria&quot;; $result3 = $wpdb-&gt;get_results($query3); foreach($result3 as $row3) { ?&gt; &lt;div class=&quot;list-group-item checkbox&quot; style=&quot;font-size: 14;&quot;&gt; &lt;label&gt;&lt;input type=&quot;checkbox&quot; class=&quot;common_selector sub1&quot; value=&quot;&lt;?php echo $row3-&gt;idSubCategoria ?&gt;&quot; &gt; &lt;?php echo $row3-&gt;designacaoSubCategoria ?&gt;&lt;/label&gt; &lt;/div&gt; &lt;?php } ?&gt; &lt;/div&gt; &lt;/div&gt;&lt;br&gt; &lt;div class=&quot;list-group&quot;&gt; &lt;h6&gt;Sub Categoria 2&lt;/h6&gt; &lt;div style=&quot;height: 180px; overflow-y: auto; overflow-x: hidden;&quot;&gt; &lt;?php $query3 = &quot;SELECT * FROM win_gab_sub_categorias WHERE subCategoria2 = '1' ORDER BY designacaoSubCategoria&quot;; $result3 = $wpdb-&gt;get_results($query3); foreach($result3 as $row3) { ?&gt; &lt;div class=&quot;list-group-item checkbox&quot; style=&quot;font-size: 14;&quot;&gt; &lt;label&gt;&lt;input type=&quot;checkbox&quot; class=&quot;common_selector sub2&quot; value=&quot;&lt;?php echo $row3-&gt;idSubCategoria ?&gt;&quot; &gt; &lt;?php echo $row3-&gt;designacaoSubCategoria ?&gt;&lt;/label&gt; &lt;/div&gt; &lt;?php } ?&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class=&quot;col-md-9&quot;&gt; &lt;br /&gt; &lt;div class=&quot;row filter_data&quot;&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>Right after this is where the problem is i believe. We begin the JS instructions that will call a file in the plugin's directory called <strong>fetch_data.php</strong>.</p> <pre><code> $(document).ready(function(){ filter_data(); function filter_data() { $('.filter_data').html('&lt;div id=&quot;loading&quot; style=&quot;&quot; &gt;&lt;/div&gt;'); var action = 'fetch_data'; var minimum_price = $('#hidden_minimum_price').val(); var maximum_price = $('#hidden_maximum_price').val(); var modoconf = get_filter('modoconf'); var modoserv = get_filter('modoserv'); var sub1 = get_filter('sub1'); var sub2 = get_filter('sub2'); $.ajax({ url:&quot;fetch_data.php&quot;, method:&quot;POST&quot;, data:{action:action, minimum_price:minimum_price, maximum_price:maximum_price, modoconf:modoconf, modoserv:modoserv, sub1:sub1, sub2:sub2}, success:function(data){ $('.filter_data').html(data); } }); } function get_filter(class_name) { var filter = []; $('.'+class_name+':checked').each(function(){ filter.push($(this).val()); }); return filter; } $('.common_selector').click(function(){ filter_data(); }); $('#price_range').slider({ range:true, min:1000, max:65000, values:[1000, 65000], step:500, stop:function(event, ui) { $('#price_show').html(ui.values[0] + ' - ' + ui.values[1]); $('#hidden_minimum_price').val(ui.values[0]); $('#hidden_maximum_price').val(ui.values[1]); filter_data(); } }); </code></pre> <p>});</p> <p>Following this code, it calls the <strong>fetch_data.php</strong> like i mentioned above:</p> <pre><code>global $wpdb; if(isset($_POST[&quot;action&quot;])) { $query = &quot; SELECT * FROM win_gab_ficha_tecnica WHERE idFichaTecnica != '0' &quot;; if(isset($_POST[&quot;modoconf&quot;])) { $conf_filter = implode(&quot;','&quot;, $_POST[&quot;modoconf&quot;]); $query .= &quot; AND modoConfecaoFichaTecnica IN('&quot;.$conf_filter.&quot;') &quot;; } if(isset($_POST[&quot;modoserv&quot;])) { $serv_filter = implode(&quot;','&quot;, $_POST[&quot;modoserv&quot;]); $query .= &quot; AND modoServicoFichaTecnica IN('&quot;.$serv_filter.&quot;') &quot;; } if(isset($_POST[&quot;subcat1&quot;])) { $subcat1_filter = implode(&quot;','&quot;, $_POST[&quot;subcat1&quot;]); $query .= &quot; AND subCategoria1 IN('&quot;.$subcat1_filter.&quot;') &quot;; } if(isset($_POST[&quot;subcat2&quot;])) { $subcat2_filter = implode(&quot;','&quot;, $_POST[&quot;subcat2&quot;]); $query .= &quot; AND subCategoria2 IN('&quot;.$subcat2_filter.&quot;') &quot;; } $result = $wpdb-&gt;get_results($query); $total_row = $wpdb-&gt;rowCount(); $output = ''; if($total_row &gt; 0) { foreach($result as $row) { $output .= ' &lt;div class=&quot;col-sm-4 col-lg-3 col-md-3&quot;&gt; &lt;div style=&quot;border:1px solid #ccc; border-radius:5px; padding:16px; margin-bottom:16px; height:450px;&quot;&gt; &lt;img src=&quot;image/'. $row['fotografiaFichaTecnica'] .'&quot; alt=&quot;&quot; class=&quot;img-responsive&quot; &gt; &lt;p align=&quot;center&quot;&gt;&lt;strong&gt;&lt;a href=&quot;#&quot;&gt;'. $row['nomeFichaTecnica'] .'&lt;/a&gt;&lt;/strong&gt;&lt;/p&gt; &lt;p&gt;Modo Confeção: '. $row['modoConfecaoFichaTecnica'].' MP&lt;br /&gt; Modo Serviço: '. $row['modoServicoFichaTecnica'] .' &lt;br /&gt; Sub-Categoria 1: '. $row['subCategoria1'] .' GB&lt;br /&gt; Sub-Categoria 2: '. $row['subCategoria2'] .' GB &lt;/p&gt; &lt;/div&gt; &lt;/div&gt; '; } } else { $output = '&lt;h3&gt;No Data Found&lt;/h3&gt;'; } echo $output; } </code></pre> <p>We've all the right calls in our plugin file for enqueuing scripts and all that stuff. When we load the wordpress page where this info is supposed to be displayed, the filtering simply does not work, and we get this console error:</p> <pre><code>jquery-1.10.2.min.js?ver=1.0:4 POST http://itamgabalgarve.pt/page-comidas/fetch_data.php 404 (Not Found) </code></pre> <p>Also, like i previosuly mentioned this is a plugin that displays the info in our custom-made theme. The page (in the theme) contains a function that calls the plugin and displays our info:</p> <pre><code>if (function_exists(get_comidas())) </code></pre>
[ { "answer_id": 376444, "author": "kraftner", "author_id": 47733, "author_profile": "https://wordpress.stackexchange.com/users/47733", "pm_score": 3, "selected": true, "text": "<p>Unfortunately there is now way to alter the markup of an existing block apart from <em>wrapping</em> it in ad...
2020/10/16
[ "https://wordpress.stackexchange.com/questions/376616", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/196195/" ]
I've been developing a website using WP and to display some database information in the front-end of the site i've created a plugin. Right now i want to include a filtering function for that same information using the plugin, but it does not work. This is the file where i've created the filters, called **show.php** ``` <div class="container"> <div class="row"> <br /> <div class="col-md-3"> <div class="list-group"> <h6>Modo de Confeção</h6> <div style="height: 180px; overflow-y: auto; overflow-x: hidden;"> <?php $query = "SELECT * FROM win_gab_modo_confecao ORDER BY designacaoModoConfecao"; $result = $wpdb->get_results($query); foreach($result as $row) { ?> <div class="list-group-item checkbox" style="font-size: 14;"> <label><input type="checkbox" class="common_selector modoconf" value="<?php echo $row->idModoConfecao ?>" > <?php echo $row->designacaoModoConfecao ?></label> </div> <?php } ?> </div> </div><br> <div class="list-group"> <h6>Modo de Serviço</h6> <div style="overflow-y: auto; overflow-x: hidden;"> <?php $query2 = "SELECT * FROM win_gab_modo_servico ORDER BY designacaoModoServico"; $result2 = $wpdb->get_results($query2); foreach($result2 as $row2) { ?> <div class="list-group-item checkbox" style="font-size: 14;"> <label><input type="checkbox" class="common_selector modoserv" value="<?php echo $row2->idModoServico ?>" > <?php echo $row2->designacaoModoServico ?></label> </div> <?php } ?> </div> </div><br> <div class="list-group"> <h6>Sub Categoria 1</h6> <div style="height: 180px; overflow-y: auto; overflow-x: hidden;"> <?php $query3 = "SELECT * FROM win_gab_sub_categorias WHERE subCategoria1 = '1' ORDER BY designacaoSubCategoria"; $result3 = $wpdb->get_results($query3); foreach($result3 as $row3) { ?> <div class="list-group-item checkbox" style="font-size: 14;"> <label><input type="checkbox" class="common_selector sub1" value="<?php echo $row3->idSubCategoria ?>" > <?php echo $row3->designacaoSubCategoria ?></label> </div> <?php } ?> </div> </div><br> <div class="list-group"> <h6>Sub Categoria 2</h6> <div style="height: 180px; overflow-y: auto; overflow-x: hidden;"> <?php $query3 = "SELECT * FROM win_gab_sub_categorias WHERE subCategoria2 = '1' ORDER BY designacaoSubCategoria"; $result3 = $wpdb->get_results($query3); foreach($result3 as $row3) { ?> <div class="list-group-item checkbox" style="font-size: 14;"> <label><input type="checkbox" class="common_selector sub2" value="<?php echo $row3->idSubCategoria ?>" > <?php echo $row3->designacaoSubCategoria ?></label> </div> <?php } ?> </div> </div> <div class="col-md-9"> <br /> <div class="row filter_data"> </div> </div> </div> </div> ``` Right after this is where the problem is i believe. We begin the JS instructions that will call a file in the plugin's directory called **fetch\_data.php**. ``` $(document).ready(function(){ filter_data(); function filter_data() { $('.filter_data').html('<div id="loading" style="" ></div>'); var action = 'fetch_data'; var minimum_price = $('#hidden_minimum_price').val(); var maximum_price = $('#hidden_maximum_price').val(); var modoconf = get_filter('modoconf'); var modoserv = get_filter('modoserv'); var sub1 = get_filter('sub1'); var sub2 = get_filter('sub2'); $.ajax({ url:"fetch_data.php", method:"POST", data:{action:action, minimum_price:minimum_price, maximum_price:maximum_price, modoconf:modoconf, modoserv:modoserv, sub1:sub1, sub2:sub2}, success:function(data){ $('.filter_data').html(data); } }); } function get_filter(class_name) { var filter = []; $('.'+class_name+':checked').each(function(){ filter.push($(this).val()); }); return filter; } $('.common_selector').click(function(){ filter_data(); }); $('#price_range').slider({ range:true, min:1000, max:65000, values:[1000, 65000], step:500, stop:function(event, ui) { $('#price_show').html(ui.values[0] + ' - ' + ui.values[1]); $('#hidden_minimum_price').val(ui.values[0]); $('#hidden_maximum_price').val(ui.values[1]); filter_data(); } }); ``` }); Following this code, it calls the **fetch\_data.php** like i mentioned above: ``` global $wpdb; if(isset($_POST["action"])) { $query = " SELECT * FROM win_gab_ficha_tecnica WHERE idFichaTecnica != '0' "; if(isset($_POST["modoconf"])) { $conf_filter = implode("','", $_POST["modoconf"]); $query .= " AND modoConfecaoFichaTecnica IN('".$conf_filter."') "; } if(isset($_POST["modoserv"])) { $serv_filter = implode("','", $_POST["modoserv"]); $query .= " AND modoServicoFichaTecnica IN('".$serv_filter."') "; } if(isset($_POST["subcat1"])) { $subcat1_filter = implode("','", $_POST["subcat1"]); $query .= " AND subCategoria1 IN('".$subcat1_filter."') "; } if(isset($_POST["subcat2"])) { $subcat2_filter = implode("','", $_POST["subcat2"]); $query .= " AND subCategoria2 IN('".$subcat2_filter."') "; } $result = $wpdb->get_results($query); $total_row = $wpdb->rowCount(); $output = ''; if($total_row > 0) { foreach($result as $row) { $output .= ' <div class="col-sm-4 col-lg-3 col-md-3"> <div style="border:1px solid #ccc; border-radius:5px; padding:16px; margin-bottom:16px; height:450px;"> <img src="image/'. $row['fotografiaFichaTecnica'] .'" alt="" class="img-responsive" > <p align="center"><strong><a href="#">'. $row['nomeFichaTecnica'] .'</a></strong></p> <p>Modo Confeção: '. $row['modoConfecaoFichaTecnica'].' MP<br /> Modo Serviço: '. $row['modoServicoFichaTecnica'] .' <br /> Sub-Categoria 1: '. $row['subCategoria1'] .' GB<br /> Sub-Categoria 2: '. $row['subCategoria2'] .' GB </p> </div> </div> '; } } else { $output = '<h3>No Data Found</h3>'; } echo $output; } ``` We've all the right calls in our plugin file for enqueuing scripts and all that stuff. When we load the wordpress page where this info is supposed to be displayed, the filtering simply does not work, and we get this console error: ``` jquery-1.10.2.min.js?ver=1.0:4 POST http://itamgabalgarve.pt/page-comidas/fetch_data.php 404 (Not Found) ``` Also, like i previosuly mentioned this is a plugin that displays the info in our custom-made theme. The page (in the theme) contains a function that calls the plugin and displays our info: ``` if (function_exists(get_comidas())) ```
Unfortunately there is now way to alter the markup of an existing block apart from *wrapping* it in additional markup: > > It receives the original block BlockEdit component and returns a new wrapped component. > Source: <https://developer.wordpress.org/block-editor/developers/filters/block-filters/#editor-blockedit> > > > To achieve what you want in the editor currently the only way would be to create your own version of the heading block replacing the core one. But what you can do, and probably is the better way to do it anyway since you leave the default markup in the DB in place, is change the markup on render using the [`render_block`](https://developer.wordpress.org/reference/hooks/render_block/) filter. You can then either use regular expressions or something more solid like a DOM Parser (e.g. <https://github.com/wasinger/htmlpagedom>) to alter the markup on output any way you like. ``` <?php add_filter('render_block', function ($blockContent, $block) { if ($block['blockName'] !== 'core/heading') { return $blockContent; } $pattern = '/(<h[^>]*>)(.*)(<\/h[1-7]{1}>)/i'; $replacement = '$1<span>$2</span>$3'; return preg_replace($pattern, $replacement, $blockContent); }, 10, 2); ``` I've also written [a blog post](https://kraftner.com/en/blog/the-taming-of-the-block-part-ii-the-practical-part/#post-processing-with-render-filters) on various ways to configure Gutenberg that also covers the `render_block` filter and some reasoning around it in case you want to dig deeper.
376,630
<p>The main Issues is that I am entering the email address &amp; password that I used in creating my WordPress site in digital but It shows that the email address &amp; username doesn’t exist even I checked in my PhpMyAdmin “WordPress” “wp-user” and I am using the right email, username and password but still shows that user doesn’t exist. However, I tried changing password by using “lost password” section but in that whenever enter my username or email to get a password reset link it shows user doesn’t exist, so what should I do to fix, please help…</p> <p>I appreciate any answer, please help, if need any other pieces of information with this issue I can give.</p> <p>Thank you...</p>
[ { "answer_id": 376444, "author": "kraftner", "author_id": 47733, "author_profile": "https://wordpress.stackexchange.com/users/47733", "pm_score": 3, "selected": true, "text": "<p>Unfortunately there is now way to alter the markup of an existing block apart from <em>wrapping</em> it in ad...
2020/10/16
[ "https://wordpress.stackexchange.com/questions/376630", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/196211/" ]
The main Issues is that I am entering the email address & password that I used in creating my WordPress site in digital but It shows that the email address & username doesn’t exist even I checked in my PhpMyAdmin “WordPress” “wp-user” and I am using the right email, username and password but still shows that user doesn’t exist. However, I tried changing password by using “lost password” section but in that whenever enter my username or email to get a password reset link it shows user doesn’t exist, so what should I do to fix, please help… I appreciate any answer, please help, if need any other pieces of information with this issue I can give. Thank you...
Unfortunately there is now way to alter the markup of an existing block apart from *wrapping* it in additional markup: > > It receives the original block BlockEdit component and returns a new wrapped component. > Source: <https://developer.wordpress.org/block-editor/developers/filters/block-filters/#editor-blockedit> > > > To achieve what you want in the editor currently the only way would be to create your own version of the heading block replacing the core one. But what you can do, and probably is the better way to do it anyway since you leave the default markup in the DB in place, is change the markup on render using the [`render_block`](https://developer.wordpress.org/reference/hooks/render_block/) filter. You can then either use regular expressions or something more solid like a DOM Parser (e.g. <https://github.com/wasinger/htmlpagedom>) to alter the markup on output any way you like. ``` <?php add_filter('render_block', function ($blockContent, $block) { if ($block['blockName'] !== 'core/heading') { return $blockContent; } $pattern = '/(<h[^>]*>)(.*)(<\/h[1-7]{1}>)/i'; $replacement = '$1<span>$2</span>$3'; return preg_replace($pattern, $replacement, $blockContent); }, 10, 2); ``` I've also written [a blog post](https://kraftner.com/en/blog/the-taming-of-the-block-part-ii-the-practical-part/#post-processing-with-render-filters) on various ways to configure Gutenberg that also covers the `render_block` filter and some reasoning around it in case you want to dig deeper.
376,643
<p>Here's what I'm trying to do:</p> <p>Page URL: <code>https://example.com/the-page/</code></p> <p>What it should load: <code>https://example.com/content/oct2020/index.html</code></p> <p>When visitors go to the permalink /the-page/, I'd like that permalink to stay exactly the same. But instead of loading content &amp; template files from the WordPress database, it would just display the index.html file instead.</p> <p>I do <em>not</em> want someone to visit &quot;/the-page/&quot; permalink, and then be 301'd to <a href="https://example.com/content/oct2020/index.html" rel="nofollow noreferrer">https://example.com/content/oct2020/index.html</a>.</p> <p>I know this can be done with a Page Template, but then I'd need all the files to be inside my WP themes directory. Instead I want to host these HTML files in a separate directory, totally theme-agnostic. Is there a plugin offering this kind of functionality, or would it be easy to code up as a functions.php addon? Or would the easiest solution be adding a line into my .htaccess file?</p>
[ { "answer_id": 376644, "author": "Montassar Billeh Hazgui", "author_id": 104567, "author_profile": "https://wordpress.stackexchange.com/users/104567", "pm_score": 1, "selected": false, "text": "<p>First of all, you need to create a new empty folder in the root folder of your WordPress we...
2020/10/16
[ "https://wordpress.stackexchange.com/questions/376643", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/8922/" ]
Here's what I'm trying to do: Page URL: `https://example.com/the-page/` What it should load: `https://example.com/content/oct2020/index.html` When visitors go to the permalink /the-page/, I'd like that permalink to stay exactly the same. But instead of loading content & template files from the WordPress database, it would just display the index.html file instead. I do *not* want someone to visit "/the-page/" permalink, and then be 301'd to <https://example.com/content/oct2020/index.html>. I know this can be done with a Page Template, but then I'd need all the files to be inside my WP themes directory. Instead I want to host these HTML files in a separate directory, totally theme-agnostic. Is there a plugin offering this kind of functionality, or would it be easy to code up as a functions.php addon? Or would the easiest solution be adding a line into my .htaccess file?
You can use the [`template_include` hook](https://developer.wordpress.org/reference/hooks/template_include/) to accomplish this. Add this to your active theme's `functions.php` file (or [create a plugin](https://developer.wordpress.org/plugins/)). ``` add_filter( 'template_include', 'wpse376643_load_html_page' ); function wpse376643_load_html_page( $template ) { if ( is_page( 'the-page' ) ) { // You'll have to use the server path to your index.html file. $template = '/path/to/your/content/oct2020/index.html'; } return $template; } ```
376,649
<p>This message occurs whenever I attempt to upload a file greater than 2M in wordpress. I have made the follow changes in order to increase the allowed file upload sizes:</p> <p>In nginx.conf, I added</p> <pre><code>client_max_body_size 200M; </code></pre> <p>In php.ini, I modified</p> <pre><code>upload_max_filesize = 200M max_file_uploads = 20 Post_max_size = 256M </code></pre> <p>In wp-config.php, I added</p> <pre><code>@ini_set( 'upload_max_filesize' , '200M' ); @ini_set( 'post_max_size' , '256M' ); @ini_set( 'memory_limit' , 256M' ); </code></pre> <p>Even with these parameters set in the three configuration files I am still getting the message <strong>413 Request Entity Too Large nginx/1.18.0 (Ubuntu)</strong></p> <p>Can anyone help?</p>
[ { "answer_id": 376644, "author": "Montassar Billeh Hazgui", "author_id": 104567, "author_profile": "https://wordpress.stackexchange.com/users/104567", "pm_score": 1, "selected": false, "text": "<p>First of all, you need to create a new empty folder in the root folder of your WordPress we...
2020/10/16
[ "https://wordpress.stackexchange.com/questions/376649", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/196179/" ]
This message occurs whenever I attempt to upload a file greater than 2M in wordpress. I have made the follow changes in order to increase the allowed file upload sizes: In nginx.conf, I added ``` client_max_body_size 200M; ``` In php.ini, I modified ``` upload_max_filesize = 200M max_file_uploads = 20 Post_max_size = 256M ``` In wp-config.php, I added ``` @ini_set( 'upload_max_filesize' , '200M' ); @ini_set( 'post_max_size' , '256M' ); @ini_set( 'memory_limit' , 256M' ); ``` Even with these parameters set in the three configuration files I am still getting the message **413 Request Entity Too Large nginx/1.18.0 (Ubuntu)** Can anyone help?
You can use the [`template_include` hook](https://developer.wordpress.org/reference/hooks/template_include/) to accomplish this. Add this to your active theme's `functions.php` file (or [create a plugin](https://developer.wordpress.org/plugins/)). ``` add_filter( 'template_include', 'wpse376643_load_html_page' ); function wpse376643_load_html_page( $template ) { if ( is_page( 'the-page' ) ) { // You'll have to use the server path to your index.html file. $template = '/path/to/your/content/oct2020/index.html'; } return $template; } ```
376,692
<p>The problem I'm having is the custom logo, site title, and description won't appear at the same time. In image 1 below, you can see that with no custom logo, the site title, and description appears just fine.</p> <pre class="lang-php prettyprint-override"><code>&lt;div id=&quot;hotwp-logo&quot;&gt; &lt;?php if ( has_custom_logo() ) : ?&gt; &lt;div class=&quot;site-branding&quot;&gt; &lt;a href=&quot;&lt;?php echo esc_url( home_url( '/' ) ); ?&gt;&quot; rel=&quot;home&quot; class=&quot;hotwp-logo-img-link&quot;&gt; &lt;img src=&quot;&lt;?php echo esc_url( hotwp_custom_logo() ); ?&gt;&quot; alt=&quot;&quot; class=&quot;hotwp-logo-img&quot;/&gt; &lt;/a&gt; &lt;/div&gt; &lt;?php else: ?&gt; &lt;div class=&quot;site-branding&quot;&gt; &lt;h1 class=&quot;hotwp-site-title&quot;&gt;&lt;a href=&quot;&lt;?php echo esc_url( home_url( '/' ) ); ?&gt;&quot; rel=&quot;home&quot;&gt;&lt;?php bloginfo( 'name' ); ?&gt;&lt;/a&gt;&lt;/h1&gt; &lt;p class=&quot;hotwp-site-description&quot;&gt;&lt;?php bloginfo( 'description' ); ?&gt;&lt;/p&gt; &lt;/div&gt; &lt;?php endif; ?&gt; &lt;/div&gt;&lt;!--/#hotwp-logo --&gt; </code></pre> <p><strong>When I don’t have a logo, the tag line and the description is shown.</strong></p> <p><strong>Image 1</strong> <img src="https://hosting.photobucket.com/images/w361/EZingers/Screenshot_at_2019_07_16_14_37_49.png?width=1920&amp;height=1080&amp;fit=bounds" alt="Image 1" /></p> <p><strong>When I add a custom logo, the tag line and the description disappears.</strong></p> <p><strong>Image 2</strong> <img src="https://hosting.photobucket.com/images/w361/EZingers/Screenshot_at_2019_07_16_14_39_15.png?width=1920&amp;height=1080&amp;fit=bounds" alt="Image 2 @" /></p> <p><strong>This was edited to show what I need. The tag line and the description need to show, shifting to the right of the logo.</strong></p> <p><strong>Image 3</strong> <img src="https://hosting.photobucket.com/images/w361/EZingers/Screenshot_at_2019_07_16_14_39_16.png?width=1920&amp;height=1080&amp;fit=bounds" alt="Image 3" /></p>
[ { "answer_id": 376700, "author": "Jim Worrall", "author_id": 195306, "author_profile": "https://wordpress.stackexchange.com/users/195306", "pm_score": 2, "selected": false, "text": "<p>Maybe I'm missing something here, but it looks like you have an if-else. If there is a logo, it shows....
2020/10/17
[ "https://wordpress.stackexchange.com/questions/376692", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/196266/" ]
The problem I'm having is the custom logo, site title, and description won't appear at the same time. In image 1 below, you can see that with no custom logo, the site title, and description appears just fine. ```php <div id="hotwp-logo"> <?php if ( has_custom_logo() ) : ?> <div class="site-branding"> <a href="<?php echo esc_url( home_url( '/' ) ); ?>" rel="home" class="hotwp-logo-img-link"> <img src="<?php echo esc_url( hotwp_custom_logo() ); ?>" alt="" class="hotwp-logo-img"/> </a> </div> <?php else: ?> <div class="site-branding"> <h1 class="hotwp-site-title"><a href="<?php echo esc_url( home_url( '/' ) ); ?>" rel="home"><?php bloginfo( 'name' ); ?></a></h1> <p class="hotwp-site-description"><?php bloginfo( 'description' ); ?></p> </div> <?php endif; ?> </div><!--/#hotwp-logo --> ``` **When I don’t have a logo, the tag line and the description is shown.** **Image 1** ![Image 1](https://hosting.photobucket.com/images/w361/EZingers/Screenshot_at_2019_07_16_14_37_49.png?width=1920&height=1080&fit=bounds) **When I add a custom logo, the tag line and the description disappears.** **Image 2** ![Image 2 @](https://hosting.photobucket.com/images/w361/EZingers/Screenshot_at_2019_07_16_14_39_15.png?width=1920&height=1080&fit=bounds) **This was edited to show what I need. The tag line and the description need to show, shifting to the right of the logo.** **Image 3** ![Image 3](https://hosting.photobucket.com/images/w361/EZingers/Screenshot_at_2019_07_16_14_39_16.png?width=1920&height=1080&fit=bounds)
Maybe I'm missing something here, but it looks like you have an if-else. If there is a logo, it shows. Else the title and description show. Try removing the if-else stuff.
376,697
<p>I know this should be easy. BBpress creates user profiles at /forums/users/.</p> <p>I'd like to make them unavailable to anyone, and not be indexed by Google. I've tried the following (in .htaccess) and more, but nothing seems to work. Is it because these are not real directories, just a page hierarchy created by BBpress? What's the solution?</p> <pre><code># RedirectMatch 404 ^/fora/users/.*$ # RedirectMatch 404 ^.*/users/.*$ # this give internal server error throughout site: # &lt;Files ~ &quot;/users/&quot;&gt; # Header set X-Robots-Tag &quot;noindex, nofollow&quot; # &lt;/FilesMatch&gt; # RewriteEngine on # RewriteRule ^.*/users/.*$ - [F] </code></pre>
[ { "answer_id": 376699, "author": "GeorgeP", "author_id": 160985, "author_profile": "https://wordpress.stackexchange.com/users/160985", "pm_score": 2, "selected": false, "text": "<p>Yes that's a pretty permalink created with rewrite rules for your posts/pages/CPT's and not a real director...
2020/10/17
[ "https://wordpress.stackexchange.com/questions/376697", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/195306/" ]
I know this should be easy. BBpress creates user profiles at /forums/users/. I'd like to make them unavailable to anyone, and not be indexed by Google. I've tried the following (in .htaccess) and more, but nothing seems to work. Is it because these are not real directories, just a page hierarchy created by BBpress? What's the solution? ``` # RedirectMatch 404 ^/fora/users/.*$ # RedirectMatch 404 ^.*/users/.*$ # this give internal server error throughout site: # <Files ~ "/users/"> # Header set X-Robots-Tag "noindex, nofollow" # </FilesMatch> # RewriteEngine on # RewriteRule ^.*/users/.*$ - [F] ```
> > > ``` > # this give internal server error throughout site: > <Files ~ "/users/"> > Header set X-Robots-Tag "noindex, nofollow" > </FilesMatch> > > ``` > > This would give an "internal server error" (500 response) because you've used `</FilesMatch>` to close the `<Files>` section. It should be `</Files>`. But as you suggested, this won't work anyway, as the `<Files>` directive matches real files only, not virtual URL-paths. But you don't need to set the `X-Robots-Tag` if you simply want to block (403 Forbidden) the request. > > > ``` > RewriteEngine on > RewriteRule ^.*/users/.*$ - [F] > > ``` > > This should work, in order to send a "403 Forbidden" response for any URL that contains `/users/` as part of the URL-path, providing you place this at the *top* of your `.htaccess`, *before* the WordPress code block (ie. before the `# BEGIN WordPress` section). However, you do not need to repeat the `RewriteEngine On` directive. And the `RewriteRule` *pattern* should be modified to avoid matching `/users/` *anywhere* in the URL-path, otherwise, it could potentially block valid URLs. Try the following instead at the top of your `.htaccess` file: ``` RewriteRule ^forums/users/ - [F] ``` This blocks any request that simply starts `/forums/users/`. Note there is no slash prefix on the `RewriteRule` *pattern*. --- **UPDATE:** If this fails to work then make sure you don't have a custom 403 `ErrorDocument` defined. If not then this could still be configured in your server config (by your web host), which is out of your control. However, you can still reset this to the default Apache error response in your `.htaccess` file: ``` ErrorDocument 403 default ``` > > a way to make it go 404 instead, ...? I don't find such a flag for RewriteRule. > > > You can use the `R=404` flag instead of `F` to trigger a "404 Not Found" response. Whilst this might look like a "redirect", since it's using the `R` (`redirect`) flag, it's not an external redirect (which is only triggered for 3xx response codes). In fact, you can use `R=403` instead of `F` if you wanted to. `F` is simply a shortcut.
376,730
<p>This is my first post, I tried searching for similar problems, didn't find any that would fit my situation. Anyway.</p> <p>Recently my cousins website got hacked, I decided to take a look and try to fix it as an exercise. I have little to none experience with web dev, so I hope to get some helpful feedback here. Whenever I type the URL in the address bar (or search for it on search engines) I get redirected to some blog site or one of those you won the iphone scam sites. It is also true for all subpages of the website.</p> <p>What's weird to me is that it only happens on PC. URL works fine when using mobile or trying it in private mode. Also I can only access WP dashboard by typing url/wp-login.php using private mode. Whenever I try to do it in normal it also redirects me to that blog site login window.</p> <p>In dashboard I noticed that bunch of plugins and WP version is outdated. I updated those relating to security and antispam, haven't updated WP version yet. As I didn't make this website and don't yet have FTP access I decided to wait with the update until I can make a full backup of the website.</p> <p>Wordfence <a href="https://paste.pics/6534f5cbd81e4130c2abee97ff5bbc1f" rel="nofollow noreferrer">scan results</a> did mark bunch of files as potentially malicious. They also have weird names that are just strings of characters which also raises red flags.</p> <p>I installed WP file manager plugin and managed to download .htaccess file.</p> <pre><code>&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; # BEGIN MainWP # END MainWP # 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>I'm not sure what to make of it as it looks similar to default basic WP htaccess, but written twice, with some weird additions. index.php was also flagged as malicious so I suspect here is a part of the problem. Help understanding it will be appreciated.</p> <p>My question would be how do I proceed from here and how do I find the source of redirect? I've read that it's not worth the hassle of cleaning up hacked websites and it's much easier to just setup new server and migrate whole website there. But if I create full backup of the site and then reupload everything won't I also be migrating those malicious files with me? I also have no idea how to do it. I didn't make the website so it's not so obvious to me which files weren't there from the getgo.</p> <p>I don't know what more to add as this post is pretty lengthy. If needed I can provide additional info.</p>
[ { "answer_id": 376699, "author": "GeorgeP", "author_id": 160985, "author_profile": "https://wordpress.stackexchange.com/users/160985", "pm_score": 2, "selected": false, "text": "<p>Yes that's a pretty permalink created with rewrite rules for your posts/pages/CPT's and not a real director...
2020/10/18
[ "https://wordpress.stackexchange.com/questions/376730", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/196288/" ]
This is my first post, I tried searching for similar problems, didn't find any that would fit my situation. Anyway. Recently my cousins website got hacked, I decided to take a look and try to fix it as an exercise. I have little to none experience with web dev, so I hope to get some helpful feedback here. Whenever I type the URL in the address bar (or search for it on search engines) I get redirected to some blog site or one of those you won the iphone scam sites. It is also true for all subpages of the website. What's weird to me is that it only happens on PC. URL works fine when using mobile or trying it in private mode. Also I can only access WP dashboard by typing url/wp-login.php using private mode. Whenever I try to do it in normal it also redirects me to that blog site login window. In dashboard I noticed that bunch of plugins and WP version is outdated. I updated those relating to security and antispam, haven't updated WP version yet. As I didn't make this website and don't yet have FTP access I decided to wait with the update until I can make a full backup of the website. Wordfence [scan results](https://paste.pics/6534f5cbd81e4130c2abee97ff5bbc1f) did mark bunch of files as potentially malicious. They also have weird names that are just strings of characters which also raises red flags. I installed WP file manager plugin and managed to download .htaccess file. ``` <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] </IfModule> # BEGIN MainWP # END MainWP # 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 ``` I'm not sure what to make of it as it looks similar to default basic WP htaccess, but written twice, with some weird additions. index.php was also flagged as malicious so I suspect here is a part of the problem. Help understanding it will be appreciated. My question would be how do I proceed from here and how do I find the source of redirect? I've read that it's not worth the hassle of cleaning up hacked websites and it's much easier to just setup new server and migrate whole website there. But if I create full backup of the site and then reupload everything won't I also be migrating those malicious files with me? I also have no idea how to do it. I didn't make the website so it's not so obvious to me which files weren't there from the getgo. I don't know what more to add as this post is pretty lengthy. If needed I can provide additional info.
> > > ``` > # this give internal server error throughout site: > <Files ~ "/users/"> > Header set X-Robots-Tag "noindex, nofollow" > </FilesMatch> > > ``` > > This would give an "internal server error" (500 response) because you've used `</FilesMatch>` to close the `<Files>` section. It should be `</Files>`. But as you suggested, this won't work anyway, as the `<Files>` directive matches real files only, not virtual URL-paths. But you don't need to set the `X-Robots-Tag` if you simply want to block (403 Forbidden) the request. > > > ``` > RewriteEngine on > RewriteRule ^.*/users/.*$ - [F] > > ``` > > This should work, in order to send a "403 Forbidden" response for any URL that contains `/users/` as part of the URL-path, providing you place this at the *top* of your `.htaccess`, *before* the WordPress code block (ie. before the `# BEGIN WordPress` section). However, you do not need to repeat the `RewriteEngine On` directive. And the `RewriteRule` *pattern* should be modified to avoid matching `/users/` *anywhere* in the URL-path, otherwise, it could potentially block valid URLs. Try the following instead at the top of your `.htaccess` file: ``` RewriteRule ^forums/users/ - [F] ``` This blocks any request that simply starts `/forums/users/`. Note there is no slash prefix on the `RewriteRule` *pattern*. --- **UPDATE:** If this fails to work then make sure you don't have a custom 403 `ErrorDocument` defined. If not then this could still be configured in your server config (by your web host), which is out of your control. However, you can still reset this to the default Apache error response in your `.htaccess` file: ``` ErrorDocument 403 default ``` > > a way to make it go 404 instead, ...? I don't find such a flag for RewriteRule. > > > You can use the `R=404` flag instead of `F` to trigger a "404 Not Found" response. Whilst this might look like a "redirect", since it's using the `R` (`redirect`) flag, it's not an external redirect (which is only triggered for 3xx response codes). In fact, you can use `R=403` instead of `F` if you wanted to. `F` is simply a shortcut.
376,734
<p>I've recently started paying greater attention to my 404 errors in order to clean up what I can and improve my site's SEO and ranking, and have noticed something that I don't understand.</p> <p>In my 404 error log, I'm seeing quite a few searches conducted by user agents that look like this:</p> <blockquote> <p>python-requests/2.23.0python-requests 2.23.0</p> </blockquote> <p>And several that are similar.....but they are all requesting files that don't exist.</p> <p>What are the python searches? Are they like bad bots? How do I block or prevent them?</p> <p>I have a lot of bad bots too, and I found an older (2017) resource with some code to block them by User-Agent in my .htaccess file, which I implemented but it does not seem to be working - I still see logs of those bad bots also requesting mostly non-existent resources as well as a lot of posts with the /email or /print appended..... is there any truly effective way to block bad user-agents?</p>
[ { "answer_id": 376737, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 2, "selected": false, "text": "<p>User agents can be anything, it's the client that sets them, so I could make a curl request to your site and...
2020/10/18
[ "https://wordpress.stackexchange.com/questions/376734", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/56458/" ]
I've recently started paying greater attention to my 404 errors in order to clean up what I can and improve my site's SEO and ranking, and have noticed something that I don't understand. In my 404 error log, I'm seeing quite a few searches conducted by user agents that look like this: > > python-requests/2.23.0python-requests 2.23.0 > > > And several that are similar.....but they are all requesting files that don't exist. What are the python searches? Are they like bad bots? How do I block or prevent them? I have a lot of bad bots too, and I found an older (2017) resource with some code to block them by User-Agent in my .htaccess file, which I implemented but it does not seem to be working - I still see logs of those bad bots also requesting mostly non-existent resources as well as a lot of posts with the /email or /print appended..... is there any truly effective way to block bad user-agents?
> > What are the python searches? Are they like bad bots? > > > Most probably just "bad bots" searching for potential vulnerabilities. > > How do I block or prevent them? > > > Well, you are already serving a 404 by the sounds of it, so it's really a non-issue. However, you can prevent the request from going through WordPress by blocking the request early in `.htaccess`, as you are already probably doing. For example, at the top of your `.htaccess` file: ``` RewriteCond %{HTTP_USER_AGENT} python [NC] RewriteRule ^ - [R=404] ``` The above sends a 404 Not Found for any request from a user-agent that contains "python" (not case-sensitive). However, blocking by user-agent isn't necessarily that reliable since many "bad bots" pretend to be regular users. > > I found an older (2017) resource with some code to block them by User-Agent in my .htaccess file, which I implemented but it does not seem to be working - I still see logs of those bad bots > > > If you block the "bad bot" in `.htaccess` you will still see the request in your server's access log. However, the log entry should show the HTTP status as 403 or 404 if it is blocked. The only way to block the request entirely from hitting your server (and appearing in your server's logs) is if you have a frontend proxy-server / firewall that "screens" all your requests.
376,765
<p>I am working on a legacy code where part of the website uses WP and other part ASP.net etc. Is there an easy way to tell me what content is coming from WP vs Non-WordPress? Since the codebase is large this can help me understand the flow of information.</p>
[ { "answer_id": 376768, "author": "cjbj", "author_id": 75495, "author_profile": "https://wordpress.stackexchange.com/users/75495", "pm_score": 3, "selected": true, "text": "<p>This depends very much on you setup and how you want to be able to see this.</p>\n<p>If you look in the source co...
2020/10/19
[ "https://wordpress.stackexchange.com/questions/376765", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/196314/" ]
I am working on a legacy code where part of the website uses WP and other part ASP.net etc. Is there an easy way to tell me what content is coming from WP vs Non-WordPress? Since the codebase is large this can help me understand the flow of information.
This depends very much on you setup and how you want to be able to see this. If you look in the source code of a page, you are very likely to be able to see which page is WP generated, because there will be strings like `wp-content` and `wp-includes` present (for instance because `jquery` is loaded by default). You could also add a specific code to the head of your site like this: ``` add_action ('wp_head','wpse376765_add_code'); function wpse376765_add_code () { echo '<meta name="wpmademe">'; } ``` If you want it to be visible in the page itself, the easiest way would be to attach a little marker for admins only by including this in the `functions.php` of your theme: ``` add_action ('wp_footer','wpse376765_add_code_to_footer'); function wpse376765_add_code_to_footer () { if (is_admin()) echo '<span>WP made me</span>'; } ```
376,827
<p>I tried creating the tables in different ways and I always get the same error: <em>&quot;Error You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '( ...... at line 1 of the WordPress database for the CREATE TABLE IF NOT query EXISTS&quot;</em></p> <pre><code> require_once( ABSPATH . 'wp-admin/includes/upgrade.php' ); global $wpdb, $rs_plugin_db_version, $table_name_clientes, $table_name_promociones; $charset_collate = $wpdb-&gt;get_charset_collate(); $wpdb-&gt;query( &quot;CREATE TABLE IF NOT EXISTS $table_name_clientes ( id int(11) NOT NULL, logo text NOT NULL, name text NOT NULL, whatsapp text DEFAULT '' NOT NULL, instagram text DEFAULT '' NOT NULL, facebook text DEFAULT '' NOT NULL, PRIMARY KEY (id) ) $charset_collate ENGINE = InnoDB&quot; ); dbDelta(); $wpdb-&gt;query( &quot;CREATE TABLE IF NOT EXISTS $table_name_promociones ( id int(11) NOT NULL, img text NOT NULL, title text NOT NULL, content text NOT NULL, owner int(11) NOT NULL, contact int(11) NOT NULL, PRIMARY KEY (id), FOREIGN KEY (owner) REFERENCES $table_name_clientes(id) ON DELETE CASCADE ON UPDATE CASCADE ) $charset_collate ENGINE = InnoDB&quot; ); dbDelta(); </code></pre> <p>In one of the tables I need to create a foreign key, if I didn't misunderstood dbDelta() does not support them and therefore my last attempt was with $wpdb-&gt;query, but with or without foreign key the result is the same.</p> <p>maybe my mistake is obvious, but honestly I can't find it</p>
[ { "answer_id": 376830, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 1, "selected": false, "text": "<p>That's not how you create tables with <code>dbDelta</code>. <code>dbDelta</code> expects an SQL statement as...
2020/10/20
[ "https://wordpress.stackexchange.com/questions/376827", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/196358/" ]
I tried creating the tables in different ways and I always get the same error: *"Error You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '( ...... at line 1 of the WordPress database for the CREATE TABLE IF NOT query EXISTS"* ``` require_once( ABSPATH . 'wp-admin/includes/upgrade.php' ); global $wpdb, $rs_plugin_db_version, $table_name_clientes, $table_name_promociones; $charset_collate = $wpdb->get_charset_collate(); $wpdb->query( "CREATE TABLE IF NOT EXISTS $table_name_clientes ( id int(11) NOT NULL, logo text NOT NULL, name text NOT NULL, whatsapp text DEFAULT '' NOT NULL, instagram text DEFAULT '' NOT NULL, facebook text DEFAULT '' NOT NULL, PRIMARY KEY (id) ) $charset_collate ENGINE = InnoDB" ); dbDelta(); $wpdb->query( "CREATE TABLE IF NOT EXISTS $table_name_promociones ( id int(11) NOT NULL, img text NOT NULL, title text NOT NULL, content text NOT NULL, owner int(11) NOT NULL, contact int(11) NOT NULL, PRIMARY KEY (id), FOREIGN KEY (owner) REFERENCES $table_name_clientes(id) ON DELETE CASCADE ON UPDATE CASCADE ) $charset_collate ENGINE = InnoDB" ); dbDelta(); ``` In one of the tables I need to create a foreign key, if I didn't misunderstood dbDelta() does not support them and therefore my last attempt was with $wpdb->query, but with or without foreign key the result is the same. maybe my mistake is obvious, but honestly I can't find it
Finally I found the solution, and as I expected, the error was stupid, simply for some reason that I unknow, the names of the tables must be defined obligatorily within the function, even if you use global $ ... it won't work, you have to define them inside. The correct function was something like this: ``` $table_name_clientes = $wpdb->prefix . 'clientes'; $table_name_promociones = $wpdb->prefix . 'promociones'; $charset_collate = $wpdb->get_charset_collate(); $sql_clientes = "CREATE TABLE IF NOT EXISTS $table_name_clientes ( id tinyint NOT NULL, logo text NOT NULL, name text NOT NULL, whatsapp text DEFAULT '' NOT NULL, instagram text DEFAULT '' NOT NULL, facebook text DEFAULT '' NOT NULL, PRIMARY KEY (id) ) $charset_collate ENGINE = InnoDB;"; $sql_promociones = "CREATE TABLE IF NOT EXISTS $table_name_promociones ( id tinyint NOT NULL, img text NOT NULL, title text NOT NULL, content text NOT NULL, owner tinyint NOT NULL, contact tinyint NOT NULL, PRIMARY KEY (id), FOREIGN KEY (owner) REFERENCES $table_name_clientes(id) ON DELETE CASCADE ON UPDATE CASCADE ) $charset_collate ENGINE = InnoDB;"; require_once( ABSPATH . 'wp-admin/includes/upgrade.php' ); dbDelta( $sql_clientes ); dbDelta( $sql_promociones ); ```
376,919
<p>We want to move a CRON job from being triggered in WordPress to a server-based job. Right now the code lives in the <em>functions.php</em> file in our WP theme, and we use the WPCrontrol plugin for scheduling. It runs fine, no problem there. The issue is the code has WooCommerce hooks in it. A server-based job has no idea what to do with <code>WC_Orders</code>, for example. How can we resolve this?</p>
[ { "answer_id": 376830, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 1, "selected": false, "text": "<p>That's not how you create tables with <code>dbDelta</code>. <code>dbDelta</code> expects an SQL statement as...
2020/10/21
[ "https://wordpress.stackexchange.com/questions/376919", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/196430/" ]
We want to move a CRON job from being triggered in WordPress to a server-based job. Right now the code lives in the *functions.php* file in our WP theme, and we use the WPCrontrol plugin for scheduling. It runs fine, no problem there. The issue is the code has WooCommerce hooks in it. A server-based job has no idea what to do with `WC_Orders`, for example. How can we resolve this?
Finally I found the solution, and as I expected, the error was stupid, simply for some reason that I unknow, the names of the tables must be defined obligatorily within the function, even if you use global $ ... it won't work, you have to define them inside. The correct function was something like this: ``` $table_name_clientes = $wpdb->prefix . 'clientes'; $table_name_promociones = $wpdb->prefix . 'promociones'; $charset_collate = $wpdb->get_charset_collate(); $sql_clientes = "CREATE TABLE IF NOT EXISTS $table_name_clientes ( id tinyint NOT NULL, logo text NOT NULL, name text NOT NULL, whatsapp text DEFAULT '' NOT NULL, instagram text DEFAULT '' NOT NULL, facebook text DEFAULT '' NOT NULL, PRIMARY KEY (id) ) $charset_collate ENGINE = InnoDB;"; $sql_promociones = "CREATE TABLE IF NOT EXISTS $table_name_promociones ( id tinyint NOT NULL, img text NOT NULL, title text NOT NULL, content text NOT NULL, owner tinyint NOT NULL, contact tinyint NOT NULL, PRIMARY KEY (id), FOREIGN KEY (owner) REFERENCES $table_name_clientes(id) ON DELETE CASCADE ON UPDATE CASCADE ) $charset_collate ENGINE = InnoDB;"; require_once( ABSPATH . 'wp-admin/includes/upgrade.php' ); dbDelta( $sql_clientes ); dbDelta( $sql_promociones ); ```
376,992
<p>I am using below function to display product information in Shop Page.</p> <pre><code>function woocommerce_template_loop_product_title() { echo '&lt;h5 class=&quot;' . esc_attr( apply_filters( 'woocommerce_product_loop_title_classes', 'woocommerce-loop-product__title' ) ) . '&quot;&gt;' . get_the_title() . ' &lt;/h5&gt;'; echo '&lt;p&gt;' . get_the_excerpt() . '&lt;/p&gt;'; } </code></pre> <p>I can fetch product <strong>shot description</strong> using <code>get_the_excerpt()</code>. But I would like to fetch all product information like size, price, color.</p> <p>I can see below information in Product page.</p> <p><a href="https://i.stack.imgur.com/pKSoz.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/pKSoz.png" alt="enter image description here" /></a></p> <p>I would like to fetch these information in Shop page with all products.</p> <p>How can I fetch all product information ?</p>
[ { "answer_id": 376993, "author": "HK89", "author_id": 179278, "author_profile": "https://wordpress.stackexchange.com/users/179278", "pm_score": 0, "selected": false, "text": "<p>The Complete woocommerce Product Description add in shop page.</p>\n<pre><code> add_action( 'woocommerce_afte...
2020/10/23
[ "https://wordpress.stackexchange.com/questions/376992", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/104698/" ]
I am using below function to display product information in Shop Page. ``` function woocommerce_template_loop_product_title() { echo '<h5 class="' . esc_attr( apply_filters( 'woocommerce_product_loop_title_classes', 'woocommerce-loop-product__title' ) ) . '">' . get_the_title() . ' </h5>'; echo '<p>' . get_the_excerpt() . '</p>'; } ``` I can fetch product **shot description** using `get_the_excerpt()`. But I would like to fetch all product information like size, price, color. I can see below information in Product page. [![enter image description here](https://i.stack.imgur.com/pKSoz.png)](https://i.stack.imgur.com/pKSoz.png) I would like to fetch these information in Shop page with all products. How can I fetch all product information ?
Product Attributes without Variation Don't Display in Shop page & Product Page Add Attribute and Variations in Product ( [Refer blog](https://docs.woocommerce.com/document/variable-product/) ) > > Note : Product variations is Used Only Variable Product. > > > And Then after put this code in function.php ``` add_action( 'woocommerce_after_shop_loop_item_title', 'bbloomer_echo_stock_variations_loop' ); function bbloomer_echo_stock_variations_loop(){ global $product; if ( $product->get_type() == 'variable' ) { foreach ( $product->get_available_variations() as $key ) { $attr_string = array(); foreach ( $key['attributes'] as $attr_name => $attr_value ) { $attr_string[] = $attr_value; $arr_names[] = $attr_name; } $attr_color = $arr_names[0]; $attr_size = $arr_names[1]; $strle = 'attribute_pa_'; $attr_name_a = substr($attr_color, strlen($strle)); $attr_name_a2 = substr($attr_size, strlen($strle)); if ( $key['max_qty'] > 0 ) { echo '<div><p>' .$attr_name_a.' : '.$attr_string[0].' , '.$attr_name_a2.' : '.$attr_string[1].' , ' . $key['max_qty'] . ' in stock</p></div>'; } else { echo '<div><p>' .$attr_name_a.' : '. $attr_string[0].',' .$attr_name_a2.' : '.$attr_string[1].' out of stock</p></div>'; } } } } ``` Look Like Below image : [![enter image description here](https://i.stack.imgur.com/slgec.png)](https://i.stack.imgur.com/slgec.png)
377,027
<p>I know it´s not clearly a technical question, I did not find on the Web (maybe my location makes the job harder).</p> <p>I have to develop a private member space.</p> <p>It´s easier for me to use the wordpress backup (wp-admin folder) with reduced rights(capabilities) for subscribers (eg. access to his invoices ) but I´m little scary to make problems of security (like from subscriber, create a door to enter in administration and hack the website finding easier the admin login/password).</p> <p>Most of plugins of membership use a custom private space only on front-end for members.</p> <p>Is it safe to use the default wordpress back-end for members or make a private member space only on front-end is a better way to do that ( excluding the question of user interface customizing ) ?</p>
[ { "answer_id": 376993, "author": "HK89", "author_id": 179278, "author_profile": "https://wordpress.stackexchange.com/users/179278", "pm_score": 0, "selected": false, "text": "<p>The Complete woocommerce Product Description add in shop page.</p>\n<pre><code> add_action( 'woocommerce_afte...
2020/10/23
[ "https://wordpress.stackexchange.com/questions/377027", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/128094/" ]
I know it´s not clearly a technical question, I did not find on the Web (maybe my location makes the job harder). I have to develop a private member space. It´s easier for me to use the wordpress backup (wp-admin folder) with reduced rights(capabilities) for subscribers (eg. access to his invoices ) but I´m little scary to make problems of security (like from subscriber, create a door to enter in administration and hack the website finding easier the admin login/password). Most of plugins of membership use a custom private space only on front-end for members. Is it safe to use the default wordpress back-end for members or make a private member space only on front-end is a better way to do that ( excluding the question of user interface customizing ) ?
Product Attributes without Variation Don't Display in Shop page & Product Page Add Attribute and Variations in Product ( [Refer blog](https://docs.woocommerce.com/document/variable-product/) ) > > Note : Product variations is Used Only Variable Product. > > > And Then after put this code in function.php ``` add_action( 'woocommerce_after_shop_loop_item_title', 'bbloomer_echo_stock_variations_loop' ); function bbloomer_echo_stock_variations_loop(){ global $product; if ( $product->get_type() == 'variable' ) { foreach ( $product->get_available_variations() as $key ) { $attr_string = array(); foreach ( $key['attributes'] as $attr_name => $attr_value ) { $attr_string[] = $attr_value; $arr_names[] = $attr_name; } $attr_color = $arr_names[0]; $attr_size = $arr_names[1]; $strle = 'attribute_pa_'; $attr_name_a = substr($attr_color, strlen($strle)); $attr_name_a2 = substr($attr_size, strlen($strle)); if ( $key['max_qty'] > 0 ) { echo '<div><p>' .$attr_name_a.' : '.$attr_string[0].' , '.$attr_name_a2.' : '.$attr_string[1].' , ' . $key['max_qty'] . ' in stock</p></div>'; } else { echo '<div><p>' .$attr_name_a.' : '. $attr_string[0].',' .$attr_name_a2.' : '.$attr_string[1].' out of stock</p></div>'; } } } } ``` Look Like Below image : [![enter image description here](https://i.stack.imgur.com/slgec.png)](https://i.stack.imgur.com/slgec.png)
377,040
<p>I have this apply filter in my plugin.</p> <pre><code>$pre_html = apply_filters( 'events_views_html', null, $view_slug, $query, $context ); </code></pre> <p>I want to change <code>$view_slug</code> value dynamically from child theme using <code>add_filter</code> because I do not want to modify plugin files. But this code is not working. It is displaying value of <code>$view_slug</code> instead of displaying complete page content.</p> <pre><code>function add_extra_val( $view_slug, $query, $context ){ if (is_singular('tribe_events')) { $view_slug = 'single-event'; } return $view_slug; } add_filter('events_views_html', 'add_extra_val', 10, 3); </code></pre> <p>It is a basic question but I have limited knowledge of WordPress filters and hooks. Some guidelines regarding this will be appreciated.</p>
[ { "answer_id": 377157, "author": "Yash Tiwari", "author_id": 185348, "author_profile": "https://wordpress.stackexchange.com/users/185348", "pm_score": 0, "selected": false, "text": "<pre><code>Below is an example to modified the value using the add_filter hook:\n\n// Accepting two argume...
2020/10/23
[ "https://wordpress.stackexchange.com/questions/377040", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/120693/" ]
I have this apply filter in my plugin. ``` $pre_html = apply_filters( 'events_views_html', null, $view_slug, $query, $context ); ``` I want to change `$view_slug` value dynamically from child theme using `add_filter` because I do not want to modify plugin files. But this code is not working. It is displaying value of `$view_slug` instead of displaying complete page content. ``` function add_extra_val( $view_slug, $query, $context ){ if (is_singular('tribe_events')) { $view_slug = 'single-event'; } return $view_slug; } add_filter('events_views_html', 'add_extra_val', 10, 3); ``` It is a basic question but I have limited knowledge of WordPress filters and hooks. Some guidelines regarding this will be appreciated.
Filters only allow you to directly modify the **first** value passed to them. In your case, that's `null`. If you shifted `view_slug` up a place, it would be available to filters using your `events_view_html` tag. ``` add_filter( 'events_view_html', 'my_callback', 10, 3); // passing 3 args to the callback, assuming you need them for something. function my_callback( $view_slug, $query, $context ) { // Do whatever you need to do to $view_slug // $query and $context can be read but not changed return $view_slug; } ```
377,074
<p>I'm trying to do an SQL query and I don't understand something. I get a value with <code>$ _POST</code>, this value is equal to 'définition'. I made this request: <code>$sql = &quot;SELECT DISTINCT * FROM&quot;. $ wpdb-&gt; prefix. &quot;posts WHERE post_title LIKE '%&quot;. $ _POST ['value']. &quot;% '&quot;;</code>.</p> <p>A <code>var_dump($sql)</code> gives <code>&quot;SELECT DISTINCT * FROM datatablename.posts WHERE post_title LIKE '% definition%'&quot;;</code>.</p> <p>If I do <code>$res = $wpdb-&gt;get_results($sql);</code>, I get an empty array</p> <p>But, if in my code I put directly <code>$sql = &quot;SELECT DISTINCT * FROM datatablename.posts WHERE post_title LIKE '% definition%'&quot;;</code> (I immediately replace <code>$_POST</code> with my value), <code>$res</code> is an array with a post.</p> <p>The problem stems from the accent, because if <code>$_POST['value'] = 'finition'</code> it's okay</p> <p>My data table is in <code>utf8mb4_unicode_ci</code>.</p> <p>What can be done to solve this problem?</p>
[ { "answer_id": 377659, "author": "Sally CJ", "author_id": 137402, "author_profile": "https://wordpress.stackexchange.com/users/137402", "pm_score": 2, "selected": true, "text": "<p>Your SQL command is highly <strong>insecure</strong> and open to security issues like SQL injection, so eve...
2020/10/24
[ "https://wordpress.stackexchange.com/questions/377074", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/195214/" ]
I'm trying to do an SQL query and I don't understand something. I get a value with `$ _POST`, this value is equal to 'définition'. I made this request: `$sql = "SELECT DISTINCT * FROM". $ wpdb-> prefix. "posts WHERE post_title LIKE '%". $ _POST ['value']. "% '";`. A `var_dump($sql)` gives `"SELECT DISTINCT * FROM datatablename.posts WHERE post_title LIKE '% definition%'";`. If I do `$res = $wpdb->get_results($sql);`, I get an empty array But, if in my code I put directly `$sql = "SELECT DISTINCT * FROM datatablename.posts WHERE post_title LIKE '% definition%'";` (I immediately replace `$_POST` with my value), `$res` is an array with a post. The problem stems from the accent, because if `$_POST['value'] = 'finition'` it's okay My data table is in `utf8mb4_unicode_ci`. What can be done to solve this problem?
Your SQL command is highly **insecure** and open to security issues like SQL injection, so even if this may not answer the question, I strongly suggest you to use [`$wpdb->prepare()`](https://developer.wordpress.org/reference/classes/wpdb/prepare/) and [`$wpdb->esc_like()`](https://developer.wordpress.org/reference/classes/wpdb/esc_like/) — the latter is used to escape the `%` character in SQL. Additionally, you can simply use `$wpdb->posts` to output the table name for WordPress posts such as `wp_posts`. And I noticed that in your SQL command: * The table name is incorrect because the `FROM` and `$wpdb->prefix` is concatenated as one word like `FROMwp_posts`. * There's a whitespace after the second `%` in the `LIKE` clause: `%". $_POST['value']. "% '` — so that whitespace is probably not needed? Or that it could be the reason why the query did not return any results. * The `var_dump()` actually contains no accent — you used `definition` and not `définition`. Same goes with the direct one. Now here's how your query or SQL command should be generated: ```php $value = $_POST['value'] ?? ''; // wrapped for brevity $sql = $wpdb->prepare( " SELECT DISTINCT * FROM {$wpdb->posts} WHERE post_title LIKE %s ", '%' . $wpdb->esc_like( $value ) . '%' ); $res = $wpdb->get_results( $sql ); ``` And I actually tested the above code with a post with the title containing the word `définition`, and the query returned one result (which is a test post). If my code doesn't work for you, you can try [`sanitize_text_field()`](https://developer.wordpress.org/reference/functions/sanitize_text_field/), but that will strip HTML tags, among other things.
377,083
<p>I'm trying to understand why whitespace appears between the main product image and the product gallery on this page: <a href="http://etica.co.nz/product/mini-icosidodecahedron-ring-bearer-box/" rel="nofollow noreferrer">http://etica.co.nz/product/mini-icosidodecahedron-ring-bearer-box/</a></p> <p>Clicking on the middle image will remove the whitespace.</p> <p>Why would it be doing this?</p> <p>Cheers</p>
[ { "answer_id": 377095, "author": "HK89", "author_id": 179278, "author_profile": "https://wordpress.stackexchange.com/users/179278", "pm_score": 0, "selected": false, "text": "<p>Your issue is flex slider in This page.</p>\n<p>Put This script in footer.php</p>\n<pre><code>&lt;script type=...
2020/10/24
[ "https://wordpress.stackexchange.com/questions/377083", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/196586/" ]
I'm trying to understand why whitespace appears between the main product image and the product gallery on this page: <http://etica.co.nz/product/mini-icosidodecahedron-ring-bearer-box/> Clicking on the middle image will remove the whitespace. Why would it be doing this? Cheers
Ok, so eventually managed to figure out that it was due to a couple of optimization plugins that were interfering with WooCommerce's image slider: JetPack's lazy loading and SG Optimizer. Deactivated SG Optimizer and added the following to my child theme's functions.php: ``` function is_lazyload_activated() { $condition = is_product(); if ($condition) { return false; } return true; } add_filter('lazyload_is_enabled', 'is_lazyload_activated'); ``` Now things are working again. Shame that can't have the optimization plugins working at the same time. At least the code above allows lazy loading on all pages except for the product pages though.
377,143
<p>I have a page like mysite.com/contacts/ If I enter non-existent urls like:</p> <pre><code>mysite.com/contacts--/ mysite.com/contacts%20/ </code></pre> <p>i get status 200 and the page opens mysite.com/contacts/ although if I enter:</p> <pre><code>mysite.com/contacts1/ </code></pre> <p>As expected, I am getting a 404 error.</p> <p>How can I implement error handling at the CMS level so that non-existent pages return a page with a 404 error template? There may be some plugin that implements URL management?</p>
[ { "answer_id": 377145, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 3, "selected": true, "text": "<p><strong>That's not what's happening</strong>, when you visit <code>/contacts--/</code> it doesn't return a 20...
2020/10/26
[ "https://wordpress.stackexchange.com/questions/377143", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/136775/" ]
I have a page like mysite.com/contacts/ If I enter non-existent urls like: ``` mysite.com/contacts--/ mysite.com/contacts%20/ ``` i get status 200 and the page opens mysite.com/contacts/ although if I enter: ``` mysite.com/contacts1/ ``` As expected, I am getting a 404 error. How can I implement error handling at the CMS level so that non-existent pages return a page with a 404 error template? There may be some plugin that implements URL management?
**That's not what's happening**, when you visit `/contacts--/` it doesn't return a 200 code, but instead it returns a `301` redirect code. The browser then follows this redirect and heads to `/contact` and it's `/contact` that returns `200` code. This is because `/contact` is the canonical URL of that page, and WordPress redirects to canonical pages out of the box for improved SEO. It should also be adding a meta tag to the header containing the canonical URL to avoid duplicate content penalties.
377,268
<p>I'm trying to display every key and value from WooCommerce <code>get_formatted_meta_data</code> order meta details. This is my code to generate the array:</p> <pre><code>$order = new WC_Order( $order_id ); foreach ( $order-&gt;get_items() as $item_id =&gt; $item ) { $item_data = $item-&gt;get_data(); $item_meta_data = $item-&gt;get_meta_data(); $formatted_meta_data = $item-&gt;get_formatted_meta_data( ' ', true ); $array = json_decode(json_encode($formatted_meta_data), true); $arrayx = array_values($array); foreach($arrayx as $value) { $result[]=array($value[&quot;display_key&quot;], wp_strip_all_tags($value[&quot;display_value&quot;])); foreach ($result as $key =&gt; $value) { $var_label = $key; $var_value = $value; } } } </code></pre> <p>And this is the array I managed to print using above function:</p> <pre><code>Array ( [0] =&gt; Array ( [0] =&gt; Color [1] =&gt; Black ) [1] =&gt; Array ( [0] =&gt; Size [1] =&gt; M ) [2] =&gt; Array ( [0] =&gt; Gift [1] =&gt; Tes 2 ) ) </code></pre> <p>Now I want to get each value in the array and want to display them like this (displayed in new line):</p> <pre><code>Color: Black Size: M Gift: Tes 2 etc etc etc (dynamically inserted by WooCommerce if any or added by other plugins) </code></pre> <p>This is what I have already tried:</p> <pre><code>$order = new WC_Order( $order_id ); foreach ( $order-&gt;get_items() as $item_id =&gt; $item ) { $product_id = $item-&gt;get_product_id(); $quantity = $item-&gt;get_quantity(); $product_name = $item-&gt;get_name(); $item_data = $item-&gt;get_data(); $item_meta_data = $item-&gt;get_meta_data(); $formatted_meta_data = $item-&gt;get_formatted_meta_data( ' ', true ); $array = json_decode(json_encode($formatted_meta_data), true); $arrayx = array_values($array); $count=0; foreach($arrayx as $value) { $result[]=array($value[&quot;display_key&quot;], wp_strip_all_tags($value[&quot;display_value&quot;])); foreach ($result as $key =&gt; $value) { $var_label = $key; $var_value = $value; $metadata['count'] = &quot;\r\n&quot;.$var_label[0].&quot;: &quot;.$var_value[0].&quot;&quot;; $count++; } } $formatted_product_name = wp_strip_all_tags(&quot; *&quot;.$product_name.&quot;*&quot;); $product_plus_meta = &quot;*&quot;.$formatted_product_name.&quot;* &quot;.$metadata['count'].&quot;&quot;; $quantity = $item-&gt;get_quantity(); $output_content.= urlencode(&quot;&quot;.$quantity.&quot;x - &quot;.$product_plus_meta.&quot;\r\n&quot;); } } $output_content.=&quot;&quot;.$price.&quot;&quot;; </code></pre> <p>Using the above code, I could only fetch one value and key from the array (only the latest in the array) which is <code>Gift =&gt; Tes 2</code>. And the output is something like this:</p> <pre><code>1x - **Sample Product** Gift: Tes 2 Price: $12.00 </code></pre> <p>Instead of this:</p> <pre><code>1x - **Sample Product** Color: Black Size: M Gift: Tes 2 Price: $12.00 </code></pre> <p>How to get the full list of each existed array key and value and display all of them in new line like above sample?</p> <p>Thank you very much in advance. Any help would be much appreciated.</p>
[ { "answer_id": 377282, "author": "Djilan MOUHOUS", "author_id": 196754, "author_profile": "https://wordpress.stackexchange.com/users/196754", "pm_score": 1, "selected": false, "text": "<p>if you can print your array why cant' you just do a loop on this array and adding each line into you...
2020/10/28
[ "https://wordpress.stackexchange.com/questions/377268", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/65317/" ]
I'm trying to display every key and value from WooCommerce `get_formatted_meta_data` order meta details. This is my code to generate the array: ``` $order = new WC_Order( $order_id ); foreach ( $order->get_items() as $item_id => $item ) { $item_data = $item->get_data(); $item_meta_data = $item->get_meta_data(); $formatted_meta_data = $item->get_formatted_meta_data( ' ', true ); $array = json_decode(json_encode($formatted_meta_data), true); $arrayx = array_values($array); foreach($arrayx as $value) { $result[]=array($value["display_key"], wp_strip_all_tags($value["display_value"])); foreach ($result as $key => $value) { $var_label = $key; $var_value = $value; } } } ``` And this is the array I managed to print using above function: ``` Array ( [0] => Array ( [0] => Color [1] => Black ) [1] => Array ( [0] => Size [1] => M ) [2] => Array ( [0] => Gift [1] => Tes 2 ) ) ``` Now I want to get each value in the array and want to display them like this (displayed in new line): ``` Color: Black Size: M Gift: Tes 2 etc etc etc (dynamically inserted by WooCommerce if any or added by other plugins) ``` This is what I have already tried: ``` $order = new WC_Order( $order_id ); foreach ( $order->get_items() as $item_id => $item ) { $product_id = $item->get_product_id(); $quantity = $item->get_quantity(); $product_name = $item->get_name(); $item_data = $item->get_data(); $item_meta_data = $item->get_meta_data(); $formatted_meta_data = $item->get_formatted_meta_data( ' ', true ); $array = json_decode(json_encode($formatted_meta_data), true); $arrayx = array_values($array); $count=0; foreach($arrayx as $value) { $result[]=array($value["display_key"], wp_strip_all_tags($value["display_value"])); foreach ($result as $key => $value) { $var_label = $key; $var_value = $value; $metadata['count'] = "\r\n".$var_label[0].": ".$var_value[0].""; $count++; } } $formatted_product_name = wp_strip_all_tags(" *".$product_name."*"); $product_plus_meta = "*".$formatted_product_name."* ".$metadata['count'].""; $quantity = $item->get_quantity(); $output_content.= urlencode("".$quantity."x - ".$product_plus_meta."\r\n"); } } $output_content.="".$price.""; ``` Using the above code, I could only fetch one value and key from the array (only the latest in the array) which is `Gift => Tes 2`. And the output is something like this: ``` 1x - **Sample Product** Gift: Tes 2 Price: $12.00 ``` Instead of this: ``` 1x - **Sample Product** Color: Black Size: M Gift: Tes 2 Price: $12.00 ``` How to get the full list of each existed array key and value and display all of them in new line like above sample? Thank you very much in advance. Any help would be much appreciated.
if you can print your array why cant' you just do a loop on this array and adding each line into your output\_content. It will look like this ``` <?php $myArray = Array ( 0 => Array ( 0 => "Color", 1 => "Black", ), 1 => Array ( 0 => "Size", 1 => "M", ), 2 => Array ( 0 => "Gift", 1 => "Tes 2" ), ); $output_content = ""; foreach($myArray as $key){ $output_content .= $key[0]." : ".$key[1]."\r"; } echo $output_content; ?> ``` And this code prints : ``` Color : Black Size : M Gift : Tes 2 ```
377,289
<p>In my plugin I try to login a user and redirect them to a specific page, but when I redirect the user, they are not logged in :-/</p> <p>I have tried multiple variations of code that looks like this:</p> <pre><code>$wp_user = get_user_by( 'email', 'johndoe@example.com'); wp_clear_auth_cookie(); do_action('wp_login', $wp_user-&gt;user_login, $wp_user); wp_set_current_user($wp_user-&gt;ID); wp_set_auth_cookie($wp_user-&gt;ID, true); $redirect_to = '/' . $redirectUrl; if ( wp_safe_redirect($redirect_to ) ) { exit; } </code></pre> <p>How can I programmatically login the user and redirect them to a specific page?</p>
[ { "answer_id": 377282, "author": "Djilan MOUHOUS", "author_id": 196754, "author_profile": "https://wordpress.stackexchange.com/users/196754", "pm_score": 1, "selected": false, "text": "<p>if you can print your array why cant' you just do a loop on this array and adding each line into you...
2020/10/28
[ "https://wordpress.stackexchange.com/questions/377289", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/153529/" ]
In my plugin I try to login a user and redirect them to a specific page, but when I redirect the user, they are not logged in :-/ I have tried multiple variations of code that looks like this: ``` $wp_user = get_user_by( 'email', 'johndoe@example.com'); wp_clear_auth_cookie(); do_action('wp_login', $wp_user->user_login, $wp_user); wp_set_current_user($wp_user->ID); wp_set_auth_cookie($wp_user->ID, true); $redirect_to = '/' . $redirectUrl; if ( wp_safe_redirect($redirect_to ) ) { exit; } ``` How can I programmatically login the user and redirect them to a specific page?
if you can print your array why cant' you just do a loop on this array and adding each line into your output\_content. It will look like this ``` <?php $myArray = Array ( 0 => Array ( 0 => "Color", 1 => "Black", ), 1 => Array ( 0 => "Size", 1 => "M", ), 2 => Array ( 0 => "Gift", 1 => "Tes 2" ), ); $output_content = ""; foreach($myArray as $key){ $output_content .= $key[0]." : ".$key[1]."\r"; } echo $output_content; ?> ``` And this code prints : ``` Color : Black Size : M Gift : Tes 2 ```
377,340
<p>Is it possible to move paypal checkout button to another place on the screen?</p> <p><a href="https://i.stack.imgur.com/xjiVJ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xjiVJ.png" alt="enter image description here" /></a></p> <p>Right now the paypal button is on regular gateway form, I would like to move it to <code>woocommerce_checkout_before_customer_details</code> action.</p> <p>I was at first using the filter below, but it refers only to placing order button and not paypal button.</p> <pre><code>&lt;?php echo apply_filters( 'woocommerce_order_button_html', '&lt;button type=&quot;submit&quot; class=&quot;button alt&quot; name=&quot;woocommerce_checkout_place_order&quot; id=&quot;place_order&quot; &gt;test&lt;/button&gt;' ); // @codingStandardsIgnoreLine ?&gt; </code></pre> <p>How to relocate paypal button gateway on checkout page in woocommerce?</p>
[ { "answer_id": 377343, "author": "Walter P.", "author_id": 65317, "author_profile": "https://wordpress.stackexchange.com/users/65317", "pm_score": 2, "selected": true, "text": "<p>Have you tried this?</p>\n<p>E.g. the paypal button function name is <code>woo_custom_paypal_button</code>.<...
2020/10/29
[ "https://wordpress.stackexchange.com/questions/377340", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/191084/" ]
Is it possible to move paypal checkout button to another place on the screen? [![enter image description here](https://i.stack.imgur.com/xjiVJ.png)](https://i.stack.imgur.com/xjiVJ.png) Right now the paypal button is on regular gateway form, I would like to move it to `woocommerce_checkout_before_customer_details` action. I was at first using the filter below, but it refers only to placing order button and not paypal button. ``` <?php echo apply_filters( 'woocommerce_order_button_html', '<button type="submit" class="button alt" name="woocommerce_checkout_place_order" id="place_order" >test</button>' ); // @codingStandardsIgnoreLine ?> ``` How to relocate paypal button gateway on checkout page in woocommerce?
Have you tried this? E.g. the paypal button function name is `woo_custom_paypal_button`. Then add action like this into your `function.php` or specific plugin: ``` add_action( 'woocommerce_checkout_before_customer_details', 'woo_custom_paypal_button' ); ``` Or if there's something that's already displayed there, and you might want to remove it, first find the function name and then try like this: ``` remove_action( 'woocommerce_checkout_before_customer_details', 'woo_function_to_remove' ); add_action( 'woocommerce_checkout_before_customer_details', 'woo_custom_paypal_button'); ``` **Update** I tried this code and worked in my case: ``` add_action( 'wp_loaded', 'x_relocate_paypal_button' ); function x_relocate_paypal_button() { $cls = new WC_Gateway_PPEC_With_SPB; add_action( 'woocommerce_checkout_before_customer_details', array( $cls, 'display_paypal_button' ), 20 ); } ``` Just replace the `woocommerce_checkout_before_customer_details` hook to relocate to another position. You can find more visual hook guide on checkout page on [this article](https://www.businessbloomer.com/woocommerce-visual-hook-guide-checkout-page/).
377,379
<p>I'd like to completely disable RSS feeds on my WP website. Can someone please guide me on how to throw a 404.php page and set the headers to 404, when someone types in <code>https://example.com/feed/</code></p> <p>here is the code in functions.php:</p> <pre><code>function disable_feeds() { global $wp_query; $wp_query-&gt;is_feed = false; $wp_query-&gt;set_404(); status_header( 404 ); nocache_headers(); wp_die( __('No feed available,please visit our &lt;a href=&quot;'. get_bloginfo('url') .'&quot;&gt;homepage&lt;/a&gt;!') ); } add_action( 'do_feed', 'disable_feeds', 1 ); add_action( 'do_feed_rdf', 'disable_feeds', 1 ); add_action( 'do_feed_rss', 'disable_feeds', 1 ); add_action( 'do_feed_rss2', 'disable_feeds', 1 ); add_action( 'do_feed_atom', 'disable_feeds', 1 ); add_action( 'do_feed_rss2_comments', 'disable_feeds', 1 ); add_action( 'do_feed_atom_comments', 'disable_feeds', 1 ); add_action( 'feed_links_show_posts_feed', '__return_false', 1 ); add_action( 'feed_links_show_comments_feed', '__return_false', 1 ); </code></pre> <p>Strangely, I get a 500 Internal Server Error when typing <code>https://example.com/feed/</code></p> <p>no corresponding rules are set in <code>.htaccess</code> file Thanks in advance.</p>
[ { "answer_id": 377395, "author": "chris_blues", "author_id": 196810, "author_profile": "https://wordpress.stackexchange.com/users/196810", "pm_score": 1, "selected": false, "text": "<p>If I want to bail out of my WP, I do it like this:</p>\n<pre><code> $wp_query-&gt;set_404();\n st...
2020/10/30
[ "https://wordpress.stackexchange.com/questions/377379", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/196827/" ]
I'd like to completely disable RSS feeds on my WP website. Can someone please guide me on how to throw a 404.php page and set the headers to 404, when someone types in `https://example.com/feed/` here is the code in functions.php: ``` function disable_feeds() { global $wp_query; $wp_query->is_feed = false; $wp_query->set_404(); status_header( 404 ); nocache_headers(); wp_die( __('No feed available,please visit our <a href="'. get_bloginfo('url') .'">homepage</a>!') ); } add_action( 'do_feed', 'disable_feeds', 1 ); add_action( 'do_feed_rdf', 'disable_feeds', 1 ); add_action( 'do_feed_rss', 'disable_feeds', 1 ); add_action( 'do_feed_rss2', 'disable_feeds', 1 ); add_action( 'do_feed_atom', 'disable_feeds', 1 ); add_action( 'do_feed_rss2_comments', 'disable_feeds', 1 ); add_action( 'do_feed_atom_comments', 'disable_feeds', 1 ); add_action( 'feed_links_show_posts_feed', '__return_false', 1 ); add_action( 'feed_links_show_comments_feed', '__return_false', 1 ); ``` Strangely, I get a 500 Internal Server Error when typing `https://example.com/feed/` no corresponding rules are set in `.htaccess` file Thanks in advance.
You need to define the HTTP Response code in `wp_die` function. ```php wp_die( __('No feed available,please visit our <a href="'. get_bloginfo('url') .'">homepage</a>!'), '', 404 ); ```
377,382
<p>By adding a new post, we have access to all core blocks from the very beginning. I would like to limit this and prevent some core blocks from being used on the main level. They should only be available inside my custom inner block.</p> <p>I have been given some advice about:</p> <ul> <li>using the <code>template</code> with <code>init</code> action</li> <li>using the <code>parent</code> attribute in custom block</li> </ul> <p>but all this does not limit the availability of blocks at the main level</p> <p>I figured maybe hiding blocks, depending on where the inserter is in the <code>DOM</code> structure might be an idea but I'm not sure it's a good direction.</p>
[ { "answer_id": 377394, "author": "Towhidul Islam", "author_id": 196377, "author_profile": "https://wordpress.stackexchange.com/users/196377", "pm_score": 0, "selected": false, "text": "<p>If I understand your post correctly, I believe you are looking for <code>ALLOWED_BLOCKS </code> prop...
2020/10/30
[ "https://wordpress.stackexchange.com/questions/377382", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/133615/" ]
By adding a new post, we have access to all core blocks from the very beginning. I would like to limit this and prevent some core blocks from being used on the main level. They should only be available inside my custom inner block. I have been given some advice about: * using the `template` with `init` action * using the `parent` attribute in custom block but all this does not limit the availability of blocks at the main level I figured maybe hiding blocks, depending on where the inserter is in the `DOM` structure might be an idea but I'm not sure it's a good direction.
You will need to filter the template for the post type: ``` add_action( 'init', 'setup_template' ); function setup_template() { $post_object = get_post_type_object( 'post' ); $post_object->template = [ [ 'your/custom/block' ] ]; $post_object->template_lock = 'all'; } ``` This will pre-populate the post with a single instance of your custom block and lock it from being changed. By locking it, they cannot insert any top-level blocks but can still insert items into your custom block. There is more [info in the docs](https://developer.wordpress.org/block-editor/developers/block-api/block-templates/#locking) about locking, you may need `insert` instead of `all` depending on your intent. Hope it helps.
377,483
<p>I'm new in WordPress development and I just created my first theme.</p> <p>In my wp-admin, the <code>&quot;Site Health&quot;</code> tells me that a PHP session has been detected (critical error), here is the message :</p> <blockquote> <p>A PHP session was created by a session_start() function call. This interferes with REST API and loopback requests. The session should be closed by session_write_close() before making any HTTP requests.</p> </blockquote> <p>I need PHP's <code>$_SESSION</code> for a theme script, and I added this to my functions.php file for sessions to be properly initialized:</p> <pre><code>&lt;?php if (!session_id()) { session_start(); } </code></pre> <p>If I delete these lines, the message disappears, but my PHP sessions don’t work anymore.</p> <p>If I keep these lines, everything seems to be working properly but this message is worrying...</p> <p>Does anyone have an idea to solve this problem while keeping the ability to use the <code>$_SESSION</code>?</p> <p>My WP version is <code>5.5.3</code> and the PHP version is <code>7.4.8</code>.</p> <p>Thank you in advance for your help!</p>
[ { "answer_id": 380509, "author": "Francesco Mantovani", "author_id": 157101, "author_profile": "https://wordpress.stackexchange.com/users/157101", "pm_score": 0, "selected": false, "text": "<p>In my case this was caused by the plugin &quot;Contact Form by BestWebSoft&quot;.</p>\n<p>If yo...
2020/11/01
[ "https://wordpress.stackexchange.com/questions/377483", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/196921/" ]
I'm new in WordPress development and I just created my first theme. In my wp-admin, the `"Site Health"` tells me that a PHP session has been detected (critical error), here is the message : > > A PHP session was created by a session\_start() function call. This > interferes with REST API and loopback requests. The session should be > closed by session\_write\_close() before making any HTTP requests. > > > I need PHP's `$_SESSION` for a theme script, and I added this to my functions.php file for sessions to be properly initialized: ``` <?php if (!session_id()) { session_start(); } ``` If I delete these lines, the message disappears, but my PHP sessions don’t work anymore. If I keep these lines, everything seems to be working properly but this message is worrying... Does anyone have an idea to solve this problem while keeping the ability to use the `$_SESSION`? My WP version is `5.5.3` and the PHP version is `7.4.8`. Thank you in advance for your help!
I was facing same issue. I replaced the code ``` session_start(); ``` with ``` if (!isset($_SESSION)) { session_start(['read_and_close' => true]); } ``` and it worked for me.
377,597
<p>I'm trying to diagnose a similar problem to <a href="https://wordpress.stackexchange.com/questions/320483/uncaught-typeerror-wp-apifetch-is-not-a-function">this question</a>, but in that case he wasn't depending on <code>wp-api-fetch</code>, and ... I'm pretty sure I am.</p> <p>I'm getting the following error:</p> <pre><code>[Error] Unhandled Promise Rejection: TypeError: Object is not a function. (In 'Object(_wordpress_api_fetch__WEBPACK_IMPORTED_MODULE_5__[&quot;apiFetch&quot;])', 'Object' is an instance of Object) </code></pre> <p>(full backtrace, below)</p> <p>I should note that I'm new to both the REST API and ESNext/Gutenberg plugin development, so ... I may be missing something really obvious, like a comma :)</p> <p>Here's the code:</p> <pre><code>import { __ } from '@wordpress/i18n'; import { Fragment } from '@wordpress/element'; import { TextControl } from '@wordpress/components'; import { apiFetch } from '@wordpress/api-fetch'; export default function Edit( props ) { const { attributes: { cwraggDataSourceType, cwraggDataSource, cwraggLocalFile }, setAttributes, } = props; const post_id = wp.data.select(&quot;core/editor&quot;).getCurrentPostId(); const onChangeContent = async ( newUrl ) =&gt; { let localFileName = await apiFetch( { path: '/cwraggb/v1/setremotedatasrc', method: 'POST', data: { 'url': newUrl, 'type': 'json', 'postId': post_id } } ); ... }; ... } </code></pre> <p>I looked at the output of <code>npm run start</code>, and it seems to be including the dependencies in the build:</p> <p><code>&lt;?php return array('dependencies' =&gt; array('wp-api-fetch', 'wp-blocks', 'wp-components', 'wp-element', 'wp-i18n', 'wp-polyfill'), 'version' =&gt; '566e4b7cb2f100542103b2b0e25aefae');</code></p> <p>This is being built, and docker run, on MacOS 10.15.7.</p> <pre><code>~ % npm --version 6.14.8 ~ % wp-env --version 2.1.0 </code></pre> <p>Any ideas what's causing that error, and/or how I can further diagnose?</p> <p>Full error message:</p> <pre><code>[Error] Unhandled Promise Rejection: TypeError: Object is not a function. (In 'Object(_wordpress_api_fetch__WEBPACK_IMPORTED_MODULE_5__[&quot;apiFetch&quot;])', 'Object' is an instance of Object) dispatchException (wp-polyfill.js:7017) invoke (wp-polyfill.js:6738) asyncGeneratorStep (cwra-google-graph-block-admin.js:250) _next (cwra-google-graph-block-admin.js:272) (anonymous function) (cwra-google-graph-block-admin.js:279) Promise (anonymous function) (cwra-google-graph-block-admin.js:268) callCallback (react-dom.js:341) dispatchEvent invokeGuardedCallbackDev (react-dom.js:391) invokeGuardedCallback (react-dom.js:448) invokeGuardedCallbackAndCatchFirstError (react-dom.js:462) executeDispatch (react-dom.js:594) executeDispatchesInOrder (react-dom.js:616) executeDispatchesAndRelease (react-dom.js:719) forEach forEachAccumulated (react-dom.js:699) runEventsInBatch (react-dom.js:744) runExtractedPluginEventsInBatch (react-dom.js:875) handleTopLevel (react-dom.js:6026) dispatchEventForPluginEventSystem (react-dom.js:6121) dispatchEvent (react-dom.js:6150) dispatchEvent unstable_runWithPriority (react.js:2820) discreteUpdates$1 (react-dom.js:21810) discreteUpdates (react-dom.js:2357) dispatchDiscreteEvent (react-dom.js:6104) dispatchDiscreteEvent </code></pre>
[ { "answer_id": 380509, "author": "Francesco Mantovani", "author_id": 157101, "author_profile": "https://wordpress.stackexchange.com/users/157101", "pm_score": 0, "selected": false, "text": "<p>In my case this was caused by the plugin &quot;Contact Form by BestWebSoft&quot;.</p>\n<p>If yo...
2020/11/03
[ "https://wordpress.stackexchange.com/questions/377597", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/194028/" ]
I'm trying to diagnose a similar problem to [this question](https://wordpress.stackexchange.com/questions/320483/uncaught-typeerror-wp-apifetch-is-not-a-function), but in that case he wasn't depending on `wp-api-fetch`, and ... I'm pretty sure I am. I'm getting the following error: ``` [Error] Unhandled Promise Rejection: TypeError: Object is not a function. (In 'Object(_wordpress_api_fetch__WEBPACK_IMPORTED_MODULE_5__["apiFetch"])', 'Object' is an instance of Object) ``` (full backtrace, below) I should note that I'm new to both the REST API and ESNext/Gutenberg plugin development, so ... I may be missing something really obvious, like a comma :) Here's the code: ``` import { __ } from '@wordpress/i18n'; import { Fragment } from '@wordpress/element'; import { TextControl } from '@wordpress/components'; import { apiFetch } from '@wordpress/api-fetch'; export default function Edit( props ) { const { attributes: { cwraggDataSourceType, cwraggDataSource, cwraggLocalFile }, setAttributes, } = props; const post_id = wp.data.select("core/editor").getCurrentPostId(); const onChangeContent = async ( newUrl ) => { let localFileName = await apiFetch( { path: '/cwraggb/v1/setremotedatasrc', method: 'POST', data: { 'url': newUrl, 'type': 'json', 'postId': post_id } } ); ... }; ... } ``` I looked at the output of `npm run start`, and it seems to be including the dependencies in the build: `<?php return array('dependencies' => array('wp-api-fetch', 'wp-blocks', 'wp-components', 'wp-element', 'wp-i18n', 'wp-polyfill'), 'version' => '566e4b7cb2f100542103b2b0e25aefae');` This is being built, and docker run, on MacOS 10.15.7. ``` ~ % npm --version 6.14.8 ~ % wp-env --version 2.1.0 ``` Any ideas what's causing that error, and/or how I can further diagnose? Full error message: ``` [Error] Unhandled Promise Rejection: TypeError: Object is not a function. (In 'Object(_wordpress_api_fetch__WEBPACK_IMPORTED_MODULE_5__["apiFetch"])', 'Object' is an instance of Object) dispatchException (wp-polyfill.js:7017) invoke (wp-polyfill.js:6738) asyncGeneratorStep (cwra-google-graph-block-admin.js:250) _next (cwra-google-graph-block-admin.js:272) (anonymous function) (cwra-google-graph-block-admin.js:279) Promise (anonymous function) (cwra-google-graph-block-admin.js:268) callCallback (react-dom.js:341) dispatchEvent invokeGuardedCallbackDev (react-dom.js:391) invokeGuardedCallback (react-dom.js:448) invokeGuardedCallbackAndCatchFirstError (react-dom.js:462) executeDispatch (react-dom.js:594) executeDispatchesInOrder (react-dom.js:616) executeDispatchesAndRelease (react-dom.js:719) forEach forEachAccumulated (react-dom.js:699) runEventsInBatch (react-dom.js:744) runExtractedPluginEventsInBatch (react-dom.js:875) handleTopLevel (react-dom.js:6026) dispatchEventForPluginEventSystem (react-dom.js:6121) dispatchEvent (react-dom.js:6150) dispatchEvent unstable_runWithPriority (react.js:2820) discreteUpdates$1 (react-dom.js:21810) discreteUpdates (react-dom.js:2357) dispatchDiscreteEvent (react-dom.js:6104) dispatchDiscreteEvent ```
I was facing same issue. I replaced the code ``` session_start(); ``` with ``` if (!isset($_SESSION)) { session_start(['read_and_close' => true]); } ``` and it worked for me.
377,614
<p>I can't find any useful information in Gutenberg Handbook. <a href="https://developer.wordpress.org/block-editor/developers/themes/theme-support/#block-gradient-presets" rel="nofollow noreferrer">Here</a> is information about adding gradients, but it only works for some core blocks.</p> <p>I use <code>ColorPalette</code> to create colors (or to use the color picker) but still don't know how to use gradients. I also found <code>PanelColorSettings</code> but still without success.</p> <p>I am looking for instructions/documentation on how to add this component:</p> <p><a href="https://i.stack.imgur.com/FTos8.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FTos8.png" alt="enter image description here" /></a></p>
[ { "answer_id": 377619, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 3, "selected": true, "text": "<p><strong>The documentation for that control does not exist at this time. Instructions have not been written ye...
2020/11/03
[ "https://wordpress.stackexchange.com/questions/377614", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/133615/" ]
I can't find any useful information in Gutenberg Handbook. [Here](https://developer.wordpress.org/block-editor/developers/themes/theme-support/#block-gradient-presets) is information about adding gradients, but it only works for some core blocks. I use `ColorPalette` to create colors (or to use the color picker) but still don't know how to use gradients. I also found `PanelColorSettings` but still without success. I am looking for instructions/documentation on how to add this component: [![enter image description here](https://i.stack.imgur.com/FTos8.png)](https://i.stack.imgur.com/FTos8.png)
**The documentation for that control does not exist at this time. Instructions have not been written yet. It is an experimental component.** --- You need to use an appropriate control in your blocks Edit component. Note that these are very new components, their design will likely change, *it should be considered experimental and unstable*. There is the `GradientPicker` component, <https://github.com/WordPress/gutenberg/blob/master/packages/components/src/gradient-picker/index.js> And `ColorGradientControl` <https://github.com/WordPress/gutenberg/blob/26e4d59e6fd3ed78d0213d60abca31c6dc1fa9cb/packages/block-editor/src/components/colors-gradients/control.js> ``` <ColorGradientControl { ...otherProps } onColorChange={ onChange } colorValue={ value } gradients={ [] } disableCustomGradients={ true } /> ```
377,620
<p>I running an instance of Wordpress on my web server but I'm getting this error in the logs</p> <pre><code>PHP Warning: chmod(): Operation not permitted in /home/webserver/html/wp-admin/includes/class-wp-filesystem-direct.php on line 173, referer: http:// mysite.com/ </code></pre> <p>I check the <code>class-wp-filesystem-direct.php</code> file on 173</p> <p>here is the line:</p> <pre><code>if ( ! $recursive || ! $this-&gt;is_dir( $file ) ) { return chmod( $file, $mode ); } </code></pre> <p>This are the permissions of this file:</p> <pre><code>-rwxrwxr-x 1 root apache 17K Oct 20 20:24 /home/webserver/html/wp-admin/includes/class-wp-filesystem-direct.php </code></pre> <p>Any of you knows what is wrong with my instance of Wordpress?</p> <p>I'll really appreciated your help.</p>
[ { "answer_id": 377619, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 3, "selected": true, "text": "<p><strong>The documentation for that control does not exist at this time. Instructions have not been written ye...
2020/11/03
[ "https://wordpress.stackexchange.com/questions/377620", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/197023/" ]
I running an instance of Wordpress on my web server but I'm getting this error in the logs ``` PHP Warning: chmod(): Operation not permitted in /home/webserver/html/wp-admin/includes/class-wp-filesystem-direct.php on line 173, referer: http:// mysite.com/ ``` I check the `class-wp-filesystem-direct.php` file on 173 here is the line: ``` if ( ! $recursive || ! $this->is_dir( $file ) ) { return chmod( $file, $mode ); } ``` This are the permissions of this file: ``` -rwxrwxr-x 1 root apache 17K Oct 20 20:24 /home/webserver/html/wp-admin/includes/class-wp-filesystem-direct.php ``` Any of you knows what is wrong with my instance of Wordpress? I'll really appreciated your help.
**The documentation for that control does not exist at this time. Instructions have not been written yet. It is an experimental component.** --- You need to use an appropriate control in your blocks Edit component. Note that these are very new components, their design will likely change, *it should be considered experimental and unstable*. There is the `GradientPicker` component, <https://github.com/WordPress/gutenberg/blob/master/packages/components/src/gradient-picker/index.js> And `ColorGradientControl` <https://github.com/WordPress/gutenberg/blob/26e4d59e6fd3ed78d0213d60abca31c6dc1fa9cb/packages/block-editor/src/components/colors-gradients/control.js> ``` <ColorGradientControl { ...otherProps } onColorChange={ onChange } colorValue={ value } gradients={ [] } disableCustomGradients={ true } /> ```
377,712
<p>In WooCommerce I create orders and users by code and on the 'order-pay' endpoint a user is created by form + ajax. The 'proceed to checkout' button is disabled by jQuery until the user is created. Now I want to create a server side check. So trying to run a function after submit but before the redirect to the payment gateway.</p> <p>I've tried these hooks but they all don't work for me in this case (do nothing).</p> <pre><code>add_action( 'woocommerce_before_checkout_process', 'is_user_created' , 1, 1 ); add_action( 'woocommerce_new_order', 'is_user_created' , 1, 1 ); add_action( 'woocommerce_checkout_process', 'is_user_created' , 1, 1 ); add_action( 'woocommerce_checkout_order_processed', 'is_user_created' , 1, 1 ); add_action( 'woocommerce_check_cart_items', 'is_user_created' , 1, 1 ); add_action( 'woocommerce_review_order_after_submit', 'is_user_created' , 1, 1 ); </code></pre> <p>The function used to test is:</p> <pre><code>function is_user_created( $order_id ){ die ('No account created'); } </code></pre> <p>Any ideas?</p>
[ { "answer_id": 377728, "author": "Peps", "author_id": 188144, "author_profile": "https://wordpress.stackexchange.com/users/188144", "pm_score": 3, "selected": true, "text": "<p>Why is it so hard to find a list of woocommerce hooks per page or sequence of execution or order &gt; payment f...
2020/11/05
[ "https://wordpress.stackexchange.com/questions/377712", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/188144/" ]
In WooCommerce I create orders and users by code and on the 'order-pay' endpoint a user is created by form + ajax. The 'proceed to checkout' button is disabled by jQuery until the user is created. Now I want to create a server side check. So trying to run a function after submit but before the redirect to the payment gateway. I've tried these hooks but they all don't work for me in this case (do nothing). ``` add_action( 'woocommerce_before_checkout_process', 'is_user_created' , 1, 1 ); add_action( 'woocommerce_new_order', 'is_user_created' , 1, 1 ); add_action( 'woocommerce_checkout_process', 'is_user_created' , 1, 1 ); add_action( 'woocommerce_checkout_order_processed', 'is_user_created' , 1, 1 ); add_action( 'woocommerce_check_cart_items', 'is_user_created' , 1, 1 ); add_action( 'woocommerce_review_order_after_submit', 'is_user_created' , 1, 1 ); ``` The function used to test is: ``` function is_user_created( $order_id ){ die ('No account created'); } ``` Any ideas?
Why is it so hard to find a list of woocommerce hooks per page or sequence of execution or order > payment flow? Anyway, after hours and hours of searching: ``` add_action( 'woocommerce_before_pay_action', 'Your Function', 1, 1 ); ```
377,752
<p>My Wordpress site has been hacked and every post has had</p> <p><code>&lt;script src='https://crow.lowerthenskyactive.ga/m.js?n=ns1' type='text/javascript'&gt;&lt;/script&gt;</code></p> <p>added to the end of each post which I need to remove. I have 375 posts I need this removing from I have tried</p> <p><code>UPDATE wp_posts SET post_content = REPLACE (post_content, '&lt;p style=&quot;text-align: center;&quot;&gt;&lt;img src=&quot;http://i.imgur.com/picture.jpg&quot; alt=&quot;&quot; /&gt;&lt;/p&gt;', '');</code></p> <p>from the <a href="https://wordpress.stackexchange.com/questions/188384/how-to-mass-delete-one-line-from-all-posts">How to mass delete one line from all posts</a></p> <p>and substituted it with the following query I'm thinking it has something to do with the ' in the query</p> <p><code>UPDATE wp_posts SET post_content = REPLACE (post_content, '&lt;script src='https://crow.lowerthenskyactive.ga/m.js?n=ns1' type='text/javascript'&gt;&lt;/script&gt;', '');</code></p> <p>but I get the following error</p> <p><code>#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'https://crow.lowerthenskyactive.ga/m.js?n=ns1' type='text/javascript'&gt;&lt;/script&gt;'' at line 1</code></p> <p>when I run the query I think it has something to do with the <code>'</code> inside the script tags but I don't know how to remove them.</p>
[ { "answer_id": 377775, "author": "uPrompt", "author_id": 155077, "author_profile": "https://wordpress.stackexchange.com/users/155077", "pm_score": 4, "selected": true, "text": "<p>Try this:</p>\n<pre><code>UPDATE wp_posts SET post_content = REPLACE (post_content, &quot;&lt;script src='ht...
2020/11/06
[ "https://wordpress.stackexchange.com/questions/377752", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/197148/" ]
My Wordpress site has been hacked and every post has had `<script src='https://crow.lowerthenskyactive.ga/m.js?n=ns1' type='text/javascript'></script>` added to the end of each post which I need to remove. I have 375 posts I need this removing from I have tried `UPDATE wp_posts SET post_content = REPLACE (post_content, '<p style="text-align: center;"><img src="http://i.imgur.com/picture.jpg" alt="" /></p>', '');` from the [How to mass delete one line from all posts](https://wordpress.stackexchange.com/questions/188384/how-to-mass-delete-one-line-from-all-posts) and substituted it with the following query I'm thinking it has something to do with the ' in the query `UPDATE wp_posts SET post_content = REPLACE (post_content, '<script src='https://crow.lowerthenskyactive.ga/m.js?n=ns1' type='text/javascript'></script>', '');` but I get the following error `#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'https://crow.lowerthenskyactive.ga/m.js?n=ns1' type='text/javascript'></script>'' at line 1` when I run the query I think it has something to do with the `'` inside the script tags but I don't know how to remove them.
Try this: ``` UPDATE wp_posts SET post_content = REPLACE (post_content, "<script src='https://crow.lowerthenskyactive.ga/m.js?n=ns1' type='text/javascript'></script>",""); ```
377,848
<p>I tried several plugins posted by Weston Ruter for jQuery created controls for the WP Customizer. They work but are different from those created via PHP. For example, controls created with PHP (<code>customizer.php</code>) respond normally to code in <code>customize-controls.js</code> or in <code>customize-previews.js</code>:</p> <pre class="lang-js prettyprint-override"><code>api( 'tzkmx_test_control', function( value ){ value.bind( function( to ) { var answer = to; }); }); </code></pre> <p>Controls created with jQuery do not respond to binding! Does anyone know how <strong>to bind</strong> them?</p>
[ { "answer_id": 377775, "author": "uPrompt", "author_id": 155077, "author_profile": "https://wordpress.stackexchange.com/users/155077", "pm_score": 4, "selected": true, "text": "<p>Try this:</p>\n<pre><code>UPDATE wp_posts SET post_content = REPLACE (post_content, &quot;&lt;script src='ht...
2020/11/09
[ "https://wordpress.stackexchange.com/questions/377848", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/197244/" ]
I tried several plugins posted by Weston Ruter for jQuery created controls for the WP Customizer. They work but are different from those created via PHP. For example, controls created with PHP (`customizer.php`) respond normally to code in `customize-controls.js` or in `customize-previews.js`: ```js api( 'tzkmx_test_control', function( value ){ value.bind( function( to ) { var answer = to; }); }); ``` Controls created with jQuery do not respond to binding! Does anyone know how **to bind** them?
Try this: ``` UPDATE wp_posts SET post_content = REPLACE (post_content, "<script src='https://crow.lowerthenskyactive.ga/m.js?n=ns1' type='text/javascript'></script>",""); ```
377,910
<p>I'm saving some pdfs into a folder with mpdf, the urls of pdfs are like this:</p> <pre><code>https://example.com/wp-content/themes/mysitetheme/invoices/invoice_8937.pdf </code></pre> <p>I want that if someone open this url it will show a shorter version like this:</p> <pre><code>https://example.com/invoice_8937.pdf </code></pre> <p>how can I obtain this result using add_rewrite_rule() and apache web server?</p> <p><strong>UPDATE</strong> as suggested I changed the code that generates pdfs in a way that are not stored in a local folder, but are generated everytime when visiting the url with a specified id parameter like this</p> <pre><code>https://example.com/wp-content/themes/mysitetheme/includes/mpdf/invoice?id=8937.pdf </code></pre> <p>so now the correct rewrite rule is</p> <pre><code>/** * Rewrite rules */ add_action( 'init', function() { add_rewrite_rule( '^example.com/invoice_([0-9]+).pdf$', '/wp-content/themes/mysitetheme/includes/mpdf/invoice.php?id=$1', 'top' ); } ); </code></pre>
[ { "answer_id": 377912, "author": "silvered.dragon", "author_id": 152290, "author_profile": "https://wordpress.stackexchange.com/users/152290", "pm_score": 2, "selected": true, "text": "<p>ok it was easy, the problem was that to match the left side pattern you have to use $1 not $matches[...
2020/11/09
[ "https://wordpress.stackexchange.com/questions/377910", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/152290/" ]
I'm saving some pdfs into a folder with mpdf, the urls of pdfs are like this: ``` https://example.com/wp-content/themes/mysitetheme/invoices/invoice_8937.pdf ``` I want that if someone open this url it will show a shorter version like this: ``` https://example.com/invoice_8937.pdf ``` how can I obtain this result using add\_rewrite\_rule() and apache web server? **UPDATE** as suggested I changed the code that generates pdfs in a way that are not stored in a local folder, but are generated everytime when visiting the url with a specified id parameter like this ``` https://example.com/wp-content/themes/mysitetheme/includes/mpdf/invoice?id=8937.pdf ``` so now the correct rewrite rule is ``` /** * Rewrite rules */ add_action( 'init', function() { add_rewrite_rule( '^example.com/invoice_([0-9]+).pdf$', '/wp-content/themes/mysitetheme/includes/mpdf/invoice.php?id=$1', 'top' ); } ); ```
ok it was easy, the problem was that to match the left side pattern you have to use $1 not $matches[1], this is the solution ``` /** * Rewrite rules */ add_action( 'init', function() { add_rewrite_rule( '^invoice_([0-9]+).pdf$', '/wp-content/themes/mysitetheme/invoices/invoice_$1.pdf', 'top' ); } ); ``` **UPDATE** From the suggestions received in the comments, it is now clear to me that it is not convenient to use rewrite rules for pages inserted in the wordpress folder without being part of the wordpress core itself, so the suitable solution is to generate virtual pages through the use of add\_query\_var and include a virtual template to be called when this new query variable is requested through index.php. So the correct code is this: ``` // Here I define my new query var and the related rewrite rules add_action( 'init', 'virtual_pages_rewrite', 99 ); function virtual_pages_rewrite() { global $wp; $wp->add_query_var( 'invoice' ); add_rewrite_rule( '^invoice_([0-9]+).pdf$', 'index.php?invoice=$matches[1]', 'top' ); } // This part is just to prevent slashes at the end of the url add_filter( 'redirect_canonical', 'virtual_pages_prevent_slash' ); function virtual_pages_prevent_slash( $redirect ) { if ( get_query_var( 'invoice' ) ) { return false; } return $redirect; } // Here I call my content when the new query var is called add_action( 'template_include', 'virtual_pages_content'); function virtual_pages_content( $template ) { $fattura = get_query_var( 'fattura' ); if ( !empty( $fattura) ) { include get_template_directory().'/includes/mpdf/invoice.php'; die; } return $template; } ```
377,920
<p>I have just made a WordPress plugin and I would like to scan it for <a href="https://owasp.org/www-project-top-ten/" rel="nofollow noreferrer">OWASP Top 10</a> vulnerabilities, any resources on how to get started here?</p> <p>Thanks</p>
[ { "answer_id": 377912, "author": "silvered.dragon", "author_id": 152290, "author_profile": "https://wordpress.stackexchange.com/users/152290", "pm_score": 2, "selected": true, "text": "<p>ok it was easy, the problem was that to match the left side pattern you have to use $1 not $matches[...
2020/11/10
[ "https://wordpress.stackexchange.com/questions/377920", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/26393/" ]
I have just made a WordPress plugin and I would like to scan it for [OWASP Top 10](https://owasp.org/www-project-top-ten/) vulnerabilities, any resources on how to get started here? Thanks
ok it was easy, the problem was that to match the left side pattern you have to use $1 not $matches[1], this is the solution ``` /** * Rewrite rules */ add_action( 'init', function() { add_rewrite_rule( '^invoice_([0-9]+).pdf$', '/wp-content/themes/mysitetheme/invoices/invoice_$1.pdf', 'top' ); } ); ``` **UPDATE** From the suggestions received in the comments, it is now clear to me that it is not convenient to use rewrite rules for pages inserted in the wordpress folder without being part of the wordpress core itself, so the suitable solution is to generate virtual pages through the use of add\_query\_var and include a virtual template to be called when this new query variable is requested through index.php. So the correct code is this: ``` // Here I define my new query var and the related rewrite rules add_action( 'init', 'virtual_pages_rewrite', 99 ); function virtual_pages_rewrite() { global $wp; $wp->add_query_var( 'invoice' ); add_rewrite_rule( '^invoice_([0-9]+).pdf$', 'index.php?invoice=$matches[1]', 'top' ); } // This part is just to prevent slashes at the end of the url add_filter( 'redirect_canonical', 'virtual_pages_prevent_slash' ); function virtual_pages_prevent_slash( $redirect ) { if ( get_query_var( 'invoice' ) ) { return false; } return $redirect; } // Here I call my content when the new query var is called add_action( 'template_include', 'virtual_pages_content'); function virtual_pages_content( $template ) { $fattura = get_query_var( 'fattura' ); if ( !empty( $fattura) ) { include get_template_directory().'/includes/mpdf/invoice.php'; die; } return $template; } ```
377,955
<p>I have an ACF field 'date_of_birth' which stores the user's birthday, examples: 20201226, 20151225, 19980701</p> <p><strong>Goal</strong>: get all users which have their birthday this month, or next month.</p> <p>I currently have this:</p> <pre><code> $users_start_date_boundary = gmdate( 'Ymd', strtotime( '-1 month' ) ); $users_end_date_boundary = gmdate( 'Ymd', strtotime( '+2 month' ) ); $wp_user_query = new WP_User_Query( [ 'fields' =&gt; 'all_with_meta', 'orderby' =&gt; 'date_of_birth', 'order' =&gt; 'ASC', 'meta_query' =&gt; [ [ 'key' =&gt; 'date_of_birth', 'value' =&gt; [ $users_start_date_boundary, $users_end_date_boundary ], 'compare' =&gt; 'BETWEEN', 'type' =&gt; 'DATE', ], ], ] ); return $wp_user_query-&gt;get_results(); </code></pre> <p>The problem with this however, that it only gets users with a birthyear of 2020.</p> <p>How do I get all users, based on the given month boundaries, while ignoring the year/day the person is born in?</p>
[ { "answer_id": 377956, "author": "kero", "author_id": 108180, "author_profile": "https://wordpress.stackexchange.com/users/108180", "pm_score": 0, "selected": false, "text": "<p>I believe since ACF stores the values as <code>Ymd</code> you have to write some kind of workaround. One possi...
2020/11/10
[ "https://wordpress.stackexchange.com/questions/377955", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/197337/" ]
I have an ACF field 'date\_of\_birth' which stores the user's birthday, examples: 20201226, 20151225, 19980701 **Goal**: get all users which have their birthday this month, or next month. I currently have this: ``` $users_start_date_boundary = gmdate( 'Ymd', strtotime( '-1 month' ) ); $users_end_date_boundary = gmdate( 'Ymd', strtotime( '+2 month' ) ); $wp_user_query = new WP_User_Query( [ 'fields' => 'all_with_meta', 'orderby' => 'date_of_birth', 'order' => 'ASC', 'meta_query' => [ [ 'key' => 'date_of_birth', 'value' => [ $users_start_date_boundary, $users_end_date_boundary ], 'compare' => 'BETWEEN', 'type' => 'DATE', ], ], ] ); return $wp_user_query->get_results(); ``` The problem with this however, that it only gets users with a birthyear of 2020. How do I get all users, based on the given month boundaries, while ignoring the year/day the person is born in?
Here is the code based on custom SQL query as suggested by @Rup that should work for you: ```php // get '-1 month' and '+2 month' dates as an array('YYYY', 'MMDD') $before = str_split( gmdate( 'Ymd', strtotime( '-1 month' ) ), 4 ); $after = str_split( gmdate( 'Ymd', strtotime( '+2 month' ) ), 4 ); // if the before/after years are the same, should search for date >= before AND <= after // if the before/after years are different, should search for date >= before OR <= after $cmp = ( $before[0] == $after[0] ) ? 'AND' : 'OR'; // SQL query $users = $wpdb->get_col( $wpdb->prepare( "SELECT user_id FROM {$wpdb->usermeta} WHERE meta_key = %s AND (SUBSTRING(meta_value, 5, 4) >= '%s' %s SUBSTRING(meta_value, 5, 4) <= '%s')", 'date_of_birth', $before[1], $cmp, $after[1] )); ``` **Update** Maybe I misunderstand your question looking at your code. The above code would give the list of users whose birthday passed no more than month ago or will happen no more than two months after the current date. To get the list of all users which have their birthday this month or next month, use the following code: ``` $current = gmdate( 'm' ); $next = sprintf( "%02d", $current % 12 + 1 ); $users = $wpdb->get_col( $wpdb->prepare( "SELECT user_id FROM {$wpdb->usermeta} WHERE meta_key = %s AND (SUBSTRING(meta_value, 5, 2) = '%s' OR SUBSTRING(meta_value, 5, 2) = '%s')", 'date_of_birth', $current, $next )); ```
378,042
<p>Could not insert attachment into the database.</p> <p>When ever I try to upload new images from WordPress media it shows me above error.</p> <p>Please help me why wp database shows this error.</p>
[ { "answer_id": 378054, "author": "Walter P.", "author_id": 65317, "author_profile": "https://wordpress.stackexchange.com/users/65317", "pm_score": 1, "selected": true, "text": "<p>Try the following solutins:</p>\n<ol>\n<li><p>First of all check your WP database size and check whether the...
2020/11/12
[ "https://wordpress.stackexchange.com/questions/378042", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/145005/" ]
Could not insert attachment into the database. When ever I try to upload new images from WordPress media it shows me above error. Please help me why wp database shows this error.
Try the following solutins: 1. First of all check your WP database size and check whether the size is full according to your hosting provider's requirement/rule. 2. Second option, add this line into your **wp-config.php**: ``` define('WP_MEMORY_LIMIT', '256M'); ``` Also if you have access to **php.ini** (or php[version number].ini) file on your server, try to add this line: ``` memory_limit 512M ``` 3. By default, some database configs have a collation or charset that doesn't allow special character. Check whether the file name of the image you're trying to upload is having any special characters. If so, delete them and use only alphanumeric. Then retry. 4. Also, please check your folder permission. Read more about it on <https://www.wpbeginner.com/wp-tutorials/how-to-fix-image-upload-issue-in-wordpress/> Hope it helps.
378,187
<p>I am using this code as a custom signup form. Is there any chance to create a success message for it?</p> <pre class="lang-php prettyprint-override"><code>&lt;?php /* ** Template Name: Custom Register Page */ get_header(); global $wpdb, $user_ID; if (isset($_POST['user_registeration'])) { //registration_validation($_POST['username'], $_POST['useremail']); global $reg_errors; $reg_errors = new WP_Error; $username=$_POST['username']; $useremail=$_POST['useremail']; $password=$_POST['password']; if(empty( $username ) || empty( $useremail ) || empty($password)) { $reg_errors-&gt;add('field', 'Required form field is missing'); } if ( 6 &gt; strlen( $username ) ) { $reg_errors-&gt;add('username_length', 'Username too short. At least 6 characters is required' ); } if ( username_exists( $username ) ) { $reg_errors-&gt;add('user_name', 'The username you entered already exists!'); } if ( ! validate_username( $username ) ) { $reg_errors-&gt;add( 'username_invalid', 'The username you entered is not valid!' ); } if ( !is_email( $useremail ) ) { $reg_errors-&gt;add( 'email_invalid', 'Email id is not valid!' ); } if ( email_exists( $useremail ) ) { $reg_errors-&gt;add( 'email', 'Email Already exist!' ); } if ( 5 &gt; strlen( $password ) ) { $reg_errors-&gt;add( 'password', 'Password length must be greater than 5!' ); } if (is_wp_error( $reg_errors )) { foreach ( $reg_errors-&gt;get_error_messages() as $error ) { $signUpError='&lt;p style=&quot;color:#FF0000; text-aling:left;&quot;&gt;&lt;strong&gt;ERROR&lt;/strong&gt;: '.$error . '&lt;br /&gt;&lt;/p&gt;'; } } if ( 1 &gt; count( $reg_errors-&gt;get_error_messages() ) ) { // sanitize user form input global $username, $useremail; $username = sanitize_user( $_POST['username'] ); $useremail = sanitize_email( $_POST['useremail'] ); $password = esc_attr( $_POST['password'] ); $userdata = array( 'user_login' =&gt; $username, 'user_email' =&gt; $useremail, 'user_pass' =&gt; $password, ); $user = wp_insert_user( $userdata ); } } ?&gt; &lt;h3&gt;Create your account&lt;/h3&gt; &lt;form action=&quot;&quot; method=&quot;post&quot; name=&quot;user_registeration&quot;&gt; &lt;label&gt;Username &lt;span class=&quot;error&quot;&gt;*&lt;/span&gt;&lt;/label&gt; &lt;input type=&quot;text&quot; name=&quot;username&quot; placeholder=&quot;Enter Your Username&quot; class=&quot;text&quot; required /&gt;&lt;br /&gt; &lt;label&gt;Email address &lt;span class=&quot;error&quot;&gt;*&lt;/span&gt;&lt;/label&gt; &lt;input type=&quot;text&quot; name=&quot;useremail&quot; class=&quot;text&quot; placeholder=&quot;Enter Your Email&quot; required /&gt; &lt;br /&gt; &lt;label&gt;Password &lt;span class=&quot;error&quot;&gt;*&lt;/span&gt;&lt;/label&gt; &lt;input type=&quot;password&quot; name=&quot;password&quot; class=&quot;text&quot; placeholder=&quot;Enter Your password&quot; required /&gt; &lt;br /&gt; &lt;input type=&quot;submit&quot; name=&quot;user_registeration&quot; value=&quot;SignUp&quot; /&gt; &lt;/form&gt; &lt;?php if(isset($signUpError)){echo '&lt;div&gt;'.$signUpError.'&lt;/div&gt;';}?&gt; </code></pre>
[ { "answer_id": 378148, "author": "Chris Norman", "author_id": 188864, "author_profile": "https://wordpress.stackexchange.com/users/188864", "pm_score": 1, "selected": false, "text": "<p>That is a fairly open-ended question. There is a lot you will have to do. The first step is you will h...
2020/11/14
[ "https://wordpress.stackexchange.com/questions/378187", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/197559/" ]
I am using this code as a custom signup form. Is there any chance to create a success message for it? ```php <?php /* ** Template Name: Custom Register Page */ get_header(); global $wpdb, $user_ID; if (isset($_POST['user_registeration'])) { //registration_validation($_POST['username'], $_POST['useremail']); global $reg_errors; $reg_errors = new WP_Error; $username=$_POST['username']; $useremail=$_POST['useremail']; $password=$_POST['password']; if(empty( $username ) || empty( $useremail ) || empty($password)) { $reg_errors->add('field', 'Required form field is missing'); } if ( 6 > strlen( $username ) ) { $reg_errors->add('username_length', 'Username too short. At least 6 characters is required' ); } if ( username_exists( $username ) ) { $reg_errors->add('user_name', 'The username you entered already exists!'); } if ( ! validate_username( $username ) ) { $reg_errors->add( 'username_invalid', 'The username you entered is not valid!' ); } if ( !is_email( $useremail ) ) { $reg_errors->add( 'email_invalid', 'Email id is not valid!' ); } if ( email_exists( $useremail ) ) { $reg_errors->add( 'email', 'Email Already exist!' ); } if ( 5 > strlen( $password ) ) { $reg_errors->add( 'password', 'Password length must be greater than 5!' ); } if (is_wp_error( $reg_errors )) { foreach ( $reg_errors->get_error_messages() as $error ) { $signUpError='<p style="color:#FF0000; text-aling:left;"><strong>ERROR</strong>: '.$error . '<br /></p>'; } } if ( 1 > count( $reg_errors->get_error_messages() ) ) { // sanitize user form input global $username, $useremail; $username = sanitize_user( $_POST['username'] ); $useremail = sanitize_email( $_POST['useremail'] ); $password = esc_attr( $_POST['password'] ); $userdata = array( 'user_login' => $username, 'user_email' => $useremail, 'user_pass' => $password, ); $user = wp_insert_user( $userdata ); } } ?> <h3>Create your account</h3> <form action="" method="post" name="user_registeration"> <label>Username <span class="error">*</span></label> <input type="text" name="username" placeholder="Enter Your Username" class="text" required /><br /> <label>Email address <span class="error">*</span></label> <input type="text" name="useremail" class="text" placeholder="Enter Your Email" required /> <br /> <label>Password <span class="error">*</span></label> <input type="password" name="password" class="text" placeholder="Enter Your password" required /> <br /> <input type="submit" name="user_registeration" value="SignUp" /> </form> <?php if(isset($signUpError)){echo '<div>'.$signUpError.'</div>';}?> ```
Custom post types and taxonomies are the appropriate method of doing this. It sounds like you've already identified the appropriate taxonomies and CPT: * A `company` post type * A `company_type` taxonomy `register_post_type` and `register_taxonomy` can do this for you. Don't forget to re-save permalinks if you use those functions or change their parameters. After doing this, new sections will appear in the Admin sidemenu, as well as frontend listings, and theme templates. Further Reading * <https://developer.wordpress.org/reference/functions/register_post_type/> * <https://developer.wordpress.org/reference/functions/register_taxonomy/> * <https://developer.wordpress.org/plugins/post-types/> * <https://developer.wordpress.org/plugins/post-types/registering-custom-post-types/> * <https://developer.wordpress.org/plugins/taxonomies/working-with-custom-taxonomies/> Generators: * <https://generatewp.com/post-type/> * <https://generatewp.com/taxonomy/>
378,229
<p>Will someone guide why this code doesn't work. Even the data gets changed. Here is the ajax I use.</p> <pre><code>jQuery(document).ready(function($) { $(&quot;.ue_ajax_enabled&quot;).on('click', function(event) { event.preventDefault(); /* Act on the event */ $.ajax({ url: ue_ajax.ajax_url, type: 'POST', /*dataType: 'json',*/ data: { 'action' : 'ue_ajax_enabled', 'new_username' : $(&quot;#new_username&quot;).val(), 'nonce' : $(&quot;#new_username_nonce_check&quot;).val(), }, beforeSend: function () { $(&quot;.ue_ajax_enabled&quot;).text(ue_ajax.beforeMessage); }, success: function (data) { console.log('Success'); console.log(data); }, error: function (data) { console.log('Error'); console.log(data); } }) }); }); </code></pre> <p>Here is the ajax action hook I use.</p> <pre><code> add_action( &quot;wp_ajax_ue_ajax_enabled&quot;, 'ue_ajax_enabled' ); function ue_ajax_enabled() { global $wpdb; $currentUser = wp_get_current_user(); $user_id = $currentUser-&gt;ID; if ( is_user_logged_in() &amp;&amp; wp_verify_nonce( $_REQUEST['nonce'], 'new_username_nonce' ) &amp;&amp; ! empty($_REQUEST['new_username'])) { // Get name of our users table $tableName = $wpdb-&gt;prefix . 'users'; if ( !username_exists( $_REQUEST['new_username'] ) ) { // Stripslashes and trim any whitespace, also replace whitespace with underscore $newUsername = trim(str_replace(' ', '_', stripslashes($_REQUEST['new_username']))); } else { echo json_encode( array('username' =&gt; 'Username exists, try any other') ); die(); } // Data to change $dataToChange = array('user_login' =&gt; $newUsername); // Where to Change $whereToChange = array('ID' =&gt; $user_id); // Change the data inside the table $result = $wpdb-&gt;update($tableName, $dataToChange, $whereToChange, array('%s'), array('%d')); if ($result) { echo json_encode( array('update' =&gt; true) ); } else { echo json_encode( array('update' =&gt; false) ); die(); } if (ue_send_email_to_user()) { $subject = 'Username Changed Successfully ID:' . $user_id; $message = &quot;&lt;p&gt;You username has been successfully changed. Your new details are given below.&lt;/p&gt;&quot;; $message .= &quot;&lt;strong&gt;Previous Username:&lt;/strong&gt;&lt;span&gt;{$currentUser-&gt;user_login}&lt;/span&gt;&quot;; $message .= &quot;&lt;strong&gt;New Username&lt;/strong&gt;&lt;span&gt;{$newUsername}&lt;/span&gt;&quot;; $from = &quot;From: &quot; . get_bloginfo('name'); wp_mail( array(ue_get_administrators_email(), $currentUser-&gt;email), $subject, $message, $from ); } } die(); } </code></pre> <p>The code throws an error message in the console instead of the success message of the ajax set earlier. Any clue why this happens. Thanks in advance</p> <p><strong>UPDATE: by commenting datatype the problem solves. But still it shows undefined when i access json.</strong></p>
[ { "answer_id": 378148, "author": "Chris Norman", "author_id": 188864, "author_profile": "https://wordpress.stackexchange.com/users/188864", "pm_score": 1, "selected": false, "text": "<p>That is a fairly open-ended question. There is a lot you will have to do. The first step is you will h...
2020/11/16
[ "https://wordpress.stackexchange.com/questions/378229", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/140102/" ]
Will someone guide why this code doesn't work. Even the data gets changed. Here is the ajax I use. ``` jQuery(document).ready(function($) { $(".ue_ajax_enabled").on('click', function(event) { event.preventDefault(); /* Act on the event */ $.ajax({ url: ue_ajax.ajax_url, type: 'POST', /*dataType: 'json',*/ data: { 'action' : 'ue_ajax_enabled', 'new_username' : $("#new_username").val(), 'nonce' : $("#new_username_nonce_check").val(), }, beforeSend: function () { $(".ue_ajax_enabled").text(ue_ajax.beforeMessage); }, success: function (data) { console.log('Success'); console.log(data); }, error: function (data) { console.log('Error'); console.log(data); } }) }); }); ``` Here is the ajax action hook I use. ``` add_action( "wp_ajax_ue_ajax_enabled", 'ue_ajax_enabled' ); function ue_ajax_enabled() { global $wpdb; $currentUser = wp_get_current_user(); $user_id = $currentUser->ID; if ( is_user_logged_in() && wp_verify_nonce( $_REQUEST['nonce'], 'new_username_nonce' ) && ! empty($_REQUEST['new_username'])) { // Get name of our users table $tableName = $wpdb->prefix . 'users'; if ( !username_exists( $_REQUEST['new_username'] ) ) { // Stripslashes and trim any whitespace, also replace whitespace with underscore $newUsername = trim(str_replace(' ', '_', stripslashes($_REQUEST['new_username']))); } else { echo json_encode( array('username' => 'Username exists, try any other') ); die(); } // Data to change $dataToChange = array('user_login' => $newUsername); // Where to Change $whereToChange = array('ID' => $user_id); // Change the data inside the table $result = $wpdb->update($tableName, $dataToChange, $whereToChange, array('%s'), array('%d')); if ($result) { echo json_encode( array('update' => true) ); } else { echo json_encode( array('update' => false) ); die(); } if (ue_send_email_to_user()) { $subject = 'Username Changed Successfully ID:' . $user_id; $message = "<p>You username has been successfully changed. Your new details are given below.</p>"; $message .= "<strong>Previous Username:</strong><span>{$currentUser->user_login}</span>"; $message .= "<strong>New Username</strong><span>{$newUsername}</span>"; $from = "From: " . get_bloginfo('name'); wp_mail( array(ue_get_administrators_email(), $currentUser->email), $subject, $message, $from ); } } die(); } ``` The code throws an error message in the console instead of the success message of the ajax set earlier. Any clue why this happens. Thanks in advance **UPDATE: by commenting datatype the problem solves. But still it shows undefined when i access json.**
Custom post types and taxonomies are the appropriate method of doing this. It sounds like you've already identified the appropriate taxonomies and CPT: * A `company` post type * A `company_type` taxonomy `register_post_type` and `register_taxonomy` can do this for you. Don't forget to re-save permalinks if you use those functions or change their parameters. After doing this, new sections will appear in the Admin sidemenu, as well as frontend listings, and theme templates. Further Reading * <https://developer.wordpress.org/reference/functions/register_post_type/> * <https://developer.wordpress.org/reference/functions/register_taxonomy/> * <https://developer.wordpress.org/plugins/post-types/> * <https://developer.wordpress.org/plugins/post-types/registering-custom-post-types/> * <https://developer.wordpress.org/plugins/taxonomies/working-with-custom-taxonomies/> Generators: * <https://generatewp.com/post-type/> * <https://generatewp.com/taxonomy/>
378,280
<p>i want to update all my wordpress post modified date and time to a specific date and time, i have a code to update it base on the id, but i want one to update all the row at once without putting the id of the posts .</p> <pre class="lang-php prettyprint-override"><code>$sql = &quot;UPDATE Zulu_posts SET post_modified='2020-11-17 16:06:00' WHERE id=2&quot;; if ($conn-&gt;query($sql) === TRUE) { echo &quot;Record updated successfully&quot;; } else { echo &quot;Error updating record: &quot; . $conn-&gt;error; } $conn-&gt;close(); </code></pre>
[ { "answer_id": 378281, "author": "phatskat", "author_id": 20143, "author_profile": "https://wordpress.stackexchange.com/users/20143", "pm_score": 1, "selected": true, "text": "<p>You can use a generalized update query. As always, when dealing with databases <strong>take a backup first</s...
2020/11/17
[ "https://wordpress.stackexchange.com/questions/378280", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/197646/" ]
i want to update all my wordpress post modified date and time to a specific date and time, i have a code to update it base on the id, but i want one to update all the row at once without putting the id of the posts . ```php $sql = "UPDATE Zulu_posts SET post_modified='2020-11-17 16:06:00' WHERE id=2"; if ($conn->query($sql) === TRUE) { echo "Record updated successfully"; } else { echo "Error updating record: " . $conn->error; } $conn->close(); ```
You can use a generalized update query. As always, when dealing with databases **take a backup first**. With that out of the way, your query should look something like: ```sql BEGIN; -- Start a transaction UPDATE wp_posts SET post_modified = <Your new date> AND post_modified_gmt = <Your new date in GMT>; SELECT * FROM wp_posts LIMIT 10 ORDER BY post_date DESC; -- See the 10 most recently authored posts, make sure their post_modified and post_modified_gmt looks good COMMIT; -- Commit the changes to the database or ROLLBACK; -- If things don't look right. ``` **Edit**: in your case, if you do this in PHP, **definitely** take a backup, and then make `$sql` everything above except for the lines with `BEGIN`, `COMMIT`, and `ROLLBACK`, though I'd recommend doing this in the command line or a GUI/web interface.
378,343
<p>I'm trying to replace the &quot;thumb-w&quot; CSS class with &quot;thumb-w1&quot;, just the first time. This is the starting function:</p> <pre><code>function start_modify_html() { ob_start(); } function end_modify_html() { $html = ob_get_clean(); $html = str_replace( 'thumb-w', 'thumb-w 1', $html); echo $html; } add_action( 'wp_head', 'start_modify_html' ); add_action( 'wp_footer', 'end_modify_html' ); </code></pre> <p>I tried entering &quot;1&quot; in the str_replace in this way:</p> <pre><code>$html = str_replace( 'thumb-w', 'thumb-w 1', $html); </code></pre> <p>but it doesn't seem to work. Can you help me? Thanks</p>
[ { "answer_id": 378281, "author": "phatskat", "author_id": 20143, "author_profile": "https://wordpress.stackexchange.com/users/20143", "pm_score": 1, "selected": true, "text": "<p>You can use a generalized update query. As always, when dealing with databases <strong>take a backup first</s...
2020/11/17
[ "https://wordpress.stackexchange.com/questions/378343", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/192453/" ]
I'm trying to replace the "thumb-w" CSS class with "thumb-w1", just the first time. This is the starting function: ``` function start_modify_html() { ob_start(); } function end_modify_html() { $html = ob_get_clean(); $html = str_replace( 'thumb-w', 'thumb-w 1', $html); echo $html; } add_action( 'wp_head', 'start_modify_html' ); add_action( 'wp_footer', 'end_modify_html' ); ``` I tried entering "1" in the str\_replace in this way: ``` $html = str_replace( 'thumb-w', 'thumb-w 1', $html); ``` but it doesn't seem to work. Can you help me? Thanks
You can use a generalized update query. As always, when dealing with databases **take a backup first**. With that out of the way, your query should look something like: ```sql BEGIN; -- Start a transaction UPDATE wp_posts SET post_modified = <Your new date> AND post_modified_gmt = <Your new date in GMT>; SELECT * FROM wp_posts LIMIT 10 ORDER BY post_date DESC; -- See the 10 most recently authored posts, make sure their post_modified and post_modified_gmt looks good COMMIT; -- Commit the changes to the database or ROLLBACK; -- If things don't look right. ``` **Edit**: in your case, if you do this in PHP, **definitely** take a backup, and then make `$sql` everything above except for the lines with `BEGIN`, `COMMIT`, and `ROLLBACK`, though I'd recommend doing this in the command line or a GUI/web interface.
378,352
<p>I have a site with many product categories and subcategories. I need to show the same sidebar as the primary category in the subcategories as well.</p> <p>Example:</p> <p>Wine (sidebar 1) White Wine (sidebar 1) Red Wine (sidebar 1) ...and many others</p> <p>Distillates (sidebar 2) Whisky (sidebar 2) Brandy (sidebar 2) ...and many others</p> <p>So I need a system that is as automatic as possible.</p> <pre><code>if ( is_product_category( 'wine' ) ) { dynamic_sidebar('Wine Sidebar'); } elseif ( is_product_category( 'distillates' ) ) { dynamic_sidebar('Distillates Sidebar'); } </code></pre> <p>This code is only for primary categories.</p>
[ { "answer_id": 378360, "author": "Tony Djukic", "author_id": 60844, "author_profile": "https://wordpress.stackexchange.com/users/60844", "pm_score": 0, "selected": false, "text": "<p>Not sure how you're going to be calling these categories as you could do it programmatically using <code>...
2020/11/18
[ "https://wordpress.stackexchange.com/questions/378352", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/197709/" ]
I have a site with many product categories and subcategories. I need to show the same sidebar as the primary category in the subcategories as well. Example: Wine (sidebar 1) White Wine (sidebar 1) Red Wine (sidebar 1) ...and many others Distillates (sidebar 2) Whisky (sidebar 2) Brandy (sidebar 2) ...and many others So I need a system that is as automatic as possible. ``` if ( is_product_category( 'wine' ) ) { dynamic_sidebar('Wine Sidebar'); } elseif ( is_product_category( 'distillates' ) ) { dynamic_sidebar('Distillates Sidebar'); } ``` This code is only for primary categories.
``` $currentCat = get_queried_object(); if ( $currentCat->term_id == 64 || $currentCat->parent == 64 ) { dynamic_sidebar('Distillati Sidebar'); } ``` I solved in this way: it works!
378,552
<p>I have a wordpress page template, where I'm loading custom posts.</p> <p>The code for fetching these custom posts looks as follows:</p> <p><strong>template-parts/content-page.php</strong></p> <pre><code>&lt;article id=&quot;songs&quot;&gt; &lt;?php get_template_part( 'partials/content/custom', 'songs' ); ?&gt; &lt;/article&gt; </code></pre> <p><strong>partials/content/custom/songs.php</strong></p> <pre><code>$args = array( 'posts_per_page' =&gt; 0, 'offset' =&gt; 0, 'category' =&gt; '', 'category_name' =&gt; '', 'orderby' =&gt; $orderBy, 'order' =&gt; $order, 'include' =&gt; '', 'meta_key' =&gt; '', 'meta_value' =&gt; '', 'post_type' =&gt; 'custom_song', 'post_mime_type' =&gt; '', 'post_parent' =&gt; '', 'author' =&gt; '', 'post_status' =&gt; 'publish', 'suppress_filters' =&gt; true ); $songs_array = get_posts( $args ); if (count($songs_array) &gt; 0){ ?&gt; &lt;ul&gt; &lt;?php foreach ($songs_array as $mysong){ set_query_var( 'mysong', $mysong); get_template_part( 'partials/content/custom', 'normal' ); } ?&gt; &lt;/ul&gt; &lt;?php } ?&gt; </code></pre> <p>The problem is that there are over 2000 records. And I want all of them to be loaded at once without any pagination. The above code works and it does load all the posts, but the page is slow because of this query.</p> <p>Can you please help me how I can optimize this and make the load faster? Is there a way I can load this asynchronously? So that I can show a loading icon in this part of the page till the posts are loaded?</p>
[ { "answer_id": 378564, "author": "Veerji", "author_id": 197182, "author_profile": "https://wordpress.stackexchange.com/users/197182", "pm_score": 1, "selected": false, "text": "<p>In your case you can use ajax on page scroll ( Infinite Scroll ) to load more post. On first page load it w...
2020/11/21
[ "https://wordpress.stackexchange.com/questions/378552", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/197865/" ]
I have a wordpress page template, where I'm loading custom posts. The code for fetching these custom posts looks as follows: **template-parts/content-page.php** ``` <article id="songs"> <?php get_template_part( 'partials/content/custom', 'songs' ); ?> </article> ``` **partials/content/custom/songs.php** ``` $args = array( 'posts_per_page' => 0, 'offset' => 0, 'category' => '', 'category_name' => '', 'orderby' => $orderBy, 'order' => $order, 'include' => '', 'meta_key' => '', 'meta_value' => '', 'post_type' => 'custom_song', 'post_mime_type' => '', 'post_parent' => '', 'author' => '', 'post_status' => 'publish', 'suppress_filters' => true ); $songs_array = get_posts( $args ); if (count($songs_array) > 0){ ?> <ul> <?php foreach ($songs_array as $mysong){ set_query_var( 'mysong', $mysong); get_template_part( 'partials/content/custom', 'normal' ); } ?> </ul> <?php } ?> ``` The problem is that there are over 2000 records. And I want all of them to be loaded at once without any pagination. The above code works and it does load all the posts, but the page is slow because of this query. Can you please help me how I can optimize this and make the load faster? Is there a way I can load this asynchronously? So that I can show a loading icon in this part of the page till the posts are loaded?
Regardless if you are loading through AJAX or not, if you need to load 2000+ records on one page, at one single time or in one single request you are always going to be at the mercy of your server resources to do so. I would look at caching solutions first as that will be the simplest to set up quickly - then in the meantime query optimisation will be where you save time. Only getting the bare essential data you need to display will help a great deal. For example if you are only showing a link then only lookup the Title & Permalink. This could be done either via `WP_Query` and the `fields` parameter [here](https://wordpress.stackexchange.com/a/166034/47618) - or a custom MySQL query. If you want to go down the AJAX route then you will need to make sure that your script only outputs useful data - the *partials/content/custom/songs.php* template could have it's own url endpoint and you can then call it on page using jQuery - AJAX load() Method. Don't load the whole page and it's associated stylesheets and JS scripts and other resources - headers footers etc and then pick out the relevant DIV to load. Make that page a bare html page with just the data you need. I seem to also remember something called "chunking" that Nginx or Apache does (can't remember which). I since can't find much info on it either. From memory this returns part of the page to the end user before the end of script has finished loading. This could be worth looking at - if you want the user to see 'something' before the full page is processed / loaded. Finally - education - tell the client that if your server is slow when you have only 2000 records and they hope to grow their song catalogue you're heading in one direction. To an expensive server / CPU bill. It's usually cheaper to pay a developer to fix / optimise something once vs. paying monthly for higher usage and bigger server bills every month for 2+ years. If you get them to understand this one though please teach me how... AJAX lazy loading via query pagination is the sensible approach here you could even trigger the 1st lazy load on completion of the 1st page load and put the scroll offset trigger high up - you would probably never see the end of the list before the next bit is loaded.... Sorry - lot of text and not much code today... but be thankful at least. This started as a comment and no one wants to read a comment that long
378,672
<p>I want to create some custom fields that will be able to show to a default wordpress post. I don't want to use the ACF plugin. Is there anyway to do it programmatically?</p> <p>Thanks</p>
[ { "answer_id": 378676, "author": "Marcus Hohlbein", "author_id": 197957, "author_profile": "https://wordpress.stackexchange.com/users/197957", "pm_score": 2, "selected": false, "text": "<p>You can use the custom fields included in wordpress</p>\n<p>Add a new post and do the following ste...
2020/11/23
[ "https://wordpress.stackexchange.com/questions/378672", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/197094/" ]
I want to create some custom fields that will be able to show to a default wordpress post. I don't want to use the ACF plugin. Is there anyway to do it programmatically? Thanks
You can use the custom fields included in wordpress Add a new post and do the following steps: **1. Go to the Options page** [![select options page](https://i.stack.imgur.com/nqsqA.png)](https://i.stack.imgur.com/nqsqA.png) **2. Select "custom fields" and hit the reload button** [![select the custom field option and reload](https://i.stack.imgur.com/j7UOw.png)](https://i.stack.imgur.com/j7UOw.png) **3. you now have a custom field in your post edit page at the bottom.** [![custom field](https://i.stack.imgur.com/PZOxD.png)](https://i.stack.imgur.com/PZOxD.png) now you can use this custom field in your theme inside the `post-loop` ``` <?php while ( have_posts() ) : the post(); ?> <?php echo get_post_meta($post->ID, 'featured', true); ?> <?php endwhile; ?> ``` You have to replace 'featured' with the name of your custom field. Once you created a custom field, you can use it in your others post as well. Hope this is helpful.
378,725
<p>In the built category, we can use <code>has_category()</code> and <code>the_category()</code> to show if the post has category and the name of the category.</p> <p>Now, I am using my custom post type and custom taxonomy. The above two functions are invalid in this case. I wonder what's the API to use here? Thank you.</p>
[ { "answer_id": 378728, "author": "Tiyo", "author_id": 197579, "author_profile": "https://wordpress.stackexchange.com/users/197579", "pm_score": 1, "selected": false, "text": "<p>Usually I used <code>has_term()</code> and <code>the_terms()</code>.</p>\n<p>These are the examples</p>\n<pre>...
2020/11/24
[ "https://wordpress.stackexchange.com/questions/378725", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/193939/" ]
In the built category, we can use `has_category()` and `the_category()` to show if the post has category and the name of the category. Now, I am using my custom post type and custom taxonomy. The above two functions are invalid in this case. I wonder what's the API to use here? Thank you.
Usually I used `has_term()` and `the_terms()`. These are the examples ``` if( has_term('', 'genre') ){ // do something } ``` ``` the_terms( $post->ID, 'category', 'categories: ', ' / ' ); ``` OR, I used this to get a list `get_the_term_list()` for example ``` echo get_the_term_list($post->ID, 'category', '', ', '); ```
378,791
<p>I'm using <code>pre_get_posts</code> and looking for a way to exclude posts in the main query. I'm using <code>query_vars</code> to query posts from a specific category and looking for a solution to exclude those posts in the main query.</p> <p>My code:</p> <pre><code>// function to setup query_vars function ctrl_dly_podcast( $query_vars ){ $query_vars[] = 'ctrl_podcasts_status'; return $query_vars; } add_filter( 'query_vars', 'ctrl_dly_podcast' ); function index_first_post( $query_vars ){ $query_vars[] = 'index_first_post'; return $query_vars; } add_filter( 'query_vars', 'index_first_post' ); function first_video( $query_vars ){ $query_vars[] = '1st_video'; return $query_vars; } add_filter( 'query_vars', 'first_video' ); function rest_posts( $query_vars ){ $query_vars[] = 'posts_the_rest'; return $query_vars; } add_filter( 'query_vars', 'rest_posts' ); //the pre_get_posts function function opby_query( $query ) { if( isset( $query-&gt;query_vars['ctrl_podcasts_status'] )) { $query-&gt;set('tax_query', array(array('taxonomy' =&gt; 'category','field' =&gt; 'slug','terms' =&gt; array( 'podcast-control-daily' ),'operator'=&gt; 'IN'))); $query-&gt;set('posts_per_page', 1); } if( isset( $query-&gt;query_vars['index_first_post'] )) { $query-&gt;set('tax_query', array(array('taxonomy' =&gt; 'category','field' =&gt; 'slug','terms' =&gt; array( 'podcast-control-daily' ),'operator'=&gt; 'NOT IN'),array('taxonomy' =&gt; 'post_format','field' =&gt; 'slug','terms' =&gt; array( 'video' ),'operator'=&gt; 'NOT IN'))); $query-&gt;set('posts_per_page', 1); } if( isset( $query-&gt;query_vars['1st_video'] )) { $query-&gt;set('tax_query', array(array('taxonomy' =&gt; 'category','field' =&gt; 'slug','terms' =&gt; array( 'video' ),'operator'=&gt; 'IN'))); $query-&gt;set('posts_per_page', 1); }; // the part I'm having problems with if( isset( $query-&gt;query_vars['posts_the_rest'] )) { $query-&gt;set('offset', array($query-&gt;query_vars['1st_video'],$query-&gt;query_vars['index_first_post'],$query-&gt;query_vars['ctrl_podcasts_status']); $query-&gt;set('posts_per_page', 15); } return $query; } add_action( 'pre_get_posts', 'opby_query' ); </code></pre>
[ { "answer_id": 378794, "author": "Hims V", "author_id": 170356, "author_profile": "https://wordpress.stackexchange.com/users/170356", "pm_score": 0, "selected": false, "text": "<p>Did you try with this one?</p>\n<pre><code>$query-&gt;set( 'post__not_in', array( 1, 1 ) );\n</code></pre>\n...
2020/11/25
[ "https://wordpress.stackexchange.com/questions/378791", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/8049/" ]
I'm using `pre_get_posts` and looking for a way to exclude posts in the main query. I'm using `query_vars` to query posts from a specific category and looking for a solution to exclude those posts in the main query. My code: ``` // function to setup query_vars function ctrl_dly_podcast( $query_vars ){ $query_vars[] = 'ctrl_podcasts_status'; return $query_vars; } add_filter( 'query_vars', 'ctrl_dly_podcast' ); function index_first_post( $query_vars ){ $query_vars[] = 'index_first_post'; return $query_vars; } add_filter( 'query_vars', 'index_first_post' ); function first_video( $query_vars ){ $query_vars[] = '1st_video'; return $query_vars; } add_filter( 'query_vars', 'first_video' ); function rest_posts( $query_vars ){ $query_vars[] = 'posts_the_rest'; return $query_vars; } add_filter( 'query_vars', 'rest_posts' ); //the pre_get_posts function function opby_query( $query ) { if( isset( $query->query_vars['ctrl_podcasts_status'] )) { $query->set('tax_query', array(array('taxonomy' => 'category','field' => 'slug','terms' => array( 'podcast-control-daily' ),'operator'=> 'IN'))); $query->set('posts_per_page', 1); } if( isset( $query->query_vars['index_first_post'] )) { $query->set('tax_query', array(array('taxonomy' => 'category','field' => 'slug','terms' => array( 'podcast-control-daily' ),'operator'=> 'NOT IN'),array('taxonomy' => 'post_format','field' => 'slug','terms' => array( 'video' ),'operator'=> 'NOT IN'))); $query->set('posts_per_page', 1); } if( isset( $query->query_vars['1st_video'] )) { $query->set('tax_query', array(array('taxonomy' => 'category','field' => 'slug','terms' => array( 'video' ),'operator'=> 'IN'))); $query->set('posts_per_page', 1); }; // the part I'm having problems with if( isset( $query->query_vars['posts_the_rest'] )) { $query->set('offset', array($query->query_vars['1st_video'],$query->query_vars['index_first_post'],$query->query_vars['ctrl_podcasts_status']); $query->set('posts_per_page', 15); } return $query; } add_action( 'pre_get_posts', 'opby_query' ); ```
This should be better: So in `pre_get_posts`, I've setup a `get_posts` function to get IDs of posts and then pass them on to `post_not_in` and `offset` the first post from the loop. ``` function site_alerts( $query_vars ){ $query_vars[] = 'opby_alerts'; return $query_vars; } add_filter( 'query_vars', 'site_alerts' ); function opby_query( $query ) { if ( $query->is_home() && $query->is_main_query() ) { $exclude = get_posts( array( 'category_name' => 'candlestick-episode', 'posts_per_page' => 1, 'fields' => 'ids' ) ); $exclude2 = get_posts( array( 'category_name' => 'video', 'posts_per_page' => 1, 'fields' => 'ids' ) ); $query->set('posts_per_page', 15); $query->set( 'offset', '1' ); $query->set('post__not_in',array($exclude[0],$exclude2[0])); } if( isset( $query->query_vars['opby_alerts'] )) { $query->set('post_type', array( 'alerts' ) ); $query->set('meta_query', array('relation' => 'OR',array('key' => 'breaking_news_status','value' => 'active'),array('key' => 'developing_news_status','value' => 'active'),array('key' => 'alert_news_status','value' => 'active'),array('key' => 'notice_news_status','value' => 'active'))); $query->set('posts_per_page', -1); } return $query; } add_action( 'pre_get_posts', 'opby_query' ); ``` And then the posts that are in `post_not_in` have their own query: ``` // first loop to show the first post from the offset <?php $args = array('posts_per_page' => '1','tax_query' => array( array( 'taxonomy' => 'category', 'field' => 'slug', 'terms' => array('candlestick-episode','candlestick-special','video'), 'operator' => 'NOT IN' ) ) );$query = new WP_query ( $args ); if ( $query->have_posts() ) { ?> <?php while ( $query->have_posts() ) : $query->the_post(); /* start the loop */ ?> first - <?php the_title(); ?><br> <?php // End the loop. endwhile; rewind_posts(); } ?> // first post from a category that's in post__not_in <?php $args = array( 'posts_per_page' => '1','tax_query' => array( array( 'taxonomy' => 'category', 'field' => 'slug', 'terms' => array('candlestick-episode','candlestick-special'), 'operator' => 'IN' ) ) );$query = new WP_query ( $args ); if ( $query->have_posts() ) { ?> <?php while ( $query->have_posts() ) : $query->the_post(); /* start the loop */ ?> podcast - <?php the_title(); ?><br> <?php // End the loop. endwhile; rewind_posts(); } ?> // another post from category from post__not_in <?php $args = array( 'posts_per_page' => '1','tax_query' => array( array( 'taxonomy' => 'category', 'field' => 'slug', 'terms' => array('video'), 'operator' => 'IN' ) ) );$query = new WP_query ( $args ); if ( $query->have_posts() ) { ?> <?php while ( $query->have_posts() ) : $query->the_post(); /* start the loop */ ?> video - <?php the_title(); ?><br> <?php // End the loop. endwhile; rewind_posts(); } ?> // the loop from pre_get_posts <?php while ( have_posts() ) : the_post();?> <?php the_title(); ?><br> <?php // End the loop. endwhile; ?> ```
378,819
<p>I have a Wordpress site hosted on LightSail (which uses bitnami). The domain is <code>https://example.com</code> On a subdomain <code>https://sub.example.com</code> I have another server running. On this server, I want to embed a page from the main domain <code>https://example.com/a-page</code>. Currently, I am getting errors that permission is denied.</p> <p>I have updated the htaccess file like so:</p> <pre><code>Header set X-Frame-Options &quot;ALLOW-FROM https://*.example.com&quot; Header set Content-Security-Policy &quot;frame-ancestors 'self' https: *.example.com&quot; Header set Referrer-Policy &quot;strict-origin-when-cross-origin&quot; </code></pre> <p>But the headers don't seem to updating or allowing any iframe embeds. I'm not very well-versed on HTTP Headers so apologies if this is a rather silly question.</p> <p>Thanks!</p>
[ { "answer_id": 378840, "author": "xuan hung Nguyen", "author_id": 195040, "author_profile": "https://wordpress.stackexchange.com/users/195040", "pm_score": -1, "selected": false, "text": "<p>In your case, I think you should use this code in htaccess file to allow Iframe can load with the...
2020/11/25
[ "https://wordpress.stackexchange.com/questions/378819", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/198091/" ]
I have a Wordpress site hosted on LightSail (which uses bitnami). The domain is `https://example.com` On a subdomain `https://sub.example.com` I have another server running. On this server, I want to embed a page from the main domain `https://example.com/a-page`. Currently, I am getting errors that permission is denied. I have updated the htaccess file like so: ``` Header set X-Frame-Options "ALLOW-FROM https://*.example.com" Header set Content-Security-Policy "frame-ancestors 'self' https: *.example.com" Header set Referrer-Policy "strict-origin-when-cross-origin" ``` But the headers don't seem to updating or allowing any iframe embeds. I'm not very well-versed on HTTP Headers so apologies if this is a rather silly question. Thanks!
I was able to figure out that because Lightsail uses a Bitnami deployment of Wordpress, Bitnami overrides the `.htaccess` file. Instead you have to update the `/opt/bitnami/apache2/conf/httpd.conf` file by adding the following content: ``` <IfModule headers_module> <IfVersion >= 2.4.7 > Header always setifempty X-Frame-Options ALLOW-FROM https://*.example.com </IfVersion> <IfVersion < 2.4.7 > Header always merge X-Frame-Options ALLOW-FROM https://*example.com </IfVersion> </IfModule> ``` Reference: <https://docs.bitnami.com/bch/apps/livehelperchat/configuration/enable-framing/>
378,820
<p>I have a page that only users of my native iOS app will find, which should open the app. This works (on any other HTML page anyway) by linking to &quot;myapp://path/inside/app&quot;.</p> <p>Wordpress keeps &quot;fixing&quot; this to &quot;https://path/inside/app&quot;, which doesn't work of course. I didn't find a setting to stop it from doing this. Is this possible?</p>
[ { "answer_id": 378840, "author": "xuan hung Nguyen", "author_id": 195040, "author_profile": "https://wordpress.stackexchange.com/users/195040", "pm_score": -1, "selected": false, "text": "<p>In your case, I think you should use this code in htaccess file to allow Iframe can load with the...
2020/11/25
[ "https://wordpress.stackexchange.com/questions/378820", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/198093/" ]
I have a page that only users of my native iOS app will find, which should open the app. This works (on any other HTML page anyway) by linking to "myapp://path/inside/app". Wordpress keeps "fixing" this to "https://path/inside/app", which doesn't work of course. I didn't find a setting to stop it from doing this. Is this possible?
I was able to figure out that because Lightsail uses a Bitnami deployment of Wordpress, Bitnami overrides the `.htaccess` file. Instead you have to update the `/opt/bitnami/apache2/conf/httpd.conf` file by adding the following content: ``` <IfModule headers_module> <IfVersion >= 2.4.7 > Header always setifempty X-Frame-Options ALLOW-FROM https://*.example.com </IfVersion> <IfVersion < 2.4.7 > Header always merge X-Frame-Options ALLOW-FROM https://*example.com </IfVersion> </IfModule> ``` Reference: <https://docs.bitnami.com/bch/apps/livehelperchat/configuration/enable-framing/>