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
|
---|---|---|---|---|---|---|
272,021 | <p>I use wordpress theme in my website. Question is simple, i want to add inside my articles as an inline note, caution, warning quote like picture. How can i do that? Is there any plugin or way to do that? </p>
<p><a href="https://i.stack.imgur.com/KuF4z.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KuF4z.png" alt="enter image description here"></a></p>
| [
{
"answer_id": 272034,
"author": "BenB",
"author_id": 62909,
"author_profile": "https://wordpress.stackexchange.com/users/62909",
"pm_score": 0,
"selected": false,
"text": "<p>Run in your theme the CSS of admin dashboard. </p>\n\n<pre><code>wp_enqueue_style( 'wp-admin' );\n</code></pre>\n\n<p>Then you could use <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/admin_notices\" rel=\"nofollow noreferrer\">WordPress admin alerts</a> CSS </p>\n\n<p>Example from docs:</p>\n\n<pre><code><div class=\"notice notice-success is-dismissible\">\n <p><?php _e( 'Done!', 'sample-text-domain' ); ?></p>\n</div>\n</code></pre>\n\n<p>Another option could be done if you will have a <a href=\"https://wordpress.org/themes/search/bootstrap/\" rel=\"nofollow noreferrer\">bootstrap based theme</a>, then you could use <a href=\"https://v4-alpha.getbootstrap.com/components/alerts/\" rel=\"nofollow noreferrer\">bootstrap alerts css styles</a>, or include bootstrap css in your theme but this option would effect other elements in your site design.</p>\n\n<p>Example from docs similar to the screenshot in your question: </p>\n\n<pre><code><div class=\"alert alert-info\" role=\"alert\">\n <strong>Heads up!</strong> This alert needs your attention, but it's not super important.\n</div>\n</code></pre>\n"
},
{
"answer_id": 272038,
"author": "Johansson",
"author_id": 94498,
"author_profile": "https://wordpress.stackexchange.com/users/94498",
"pm_score": 1,
"selected": false,
"text": "<p>You can hook into <a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/the_content\" rel=\"nofollow noreferrer\"><code>the_content</code></a> filter and add your note after every post. Then you can style it to have a nice quote.</p>\n\n<pre><code>add_filter('the_content','add_my_note');\nfunction add_my_note($content){\n // Write your note here\n $note = '\n <div class=\"my-note\">\n <h3>Note Header</h3>\n <p>Note body</p>\n </div>';\n // Append the note to the content\n $content = $content . $note;\n // Return the modified content\n return $content;\n}\n</code></pre>\n\n<p>This will add the note to your post's content. Now time to style it.</p>\n\n<pre><code>.my-note {\n display:block;\n background:lightgray;\n border-width: 0 0 0 3px;\n border-color:grey;\n color:black;\n border-style:solid;\n padding: 1em;\n}\n.my-note h3 {\n display:block;\n font-size: 2em\n}\n.my-note p {\n display:block;\n font-size : 1em;\n}\n</code></pre>\n\n<p>I've done some basic styling for you, which you can change to fit your tastes,</p>\n"
}
]
| 2017/07/02 | [
"https://wordpress.stackexchange.com/questions/272021",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/122986/"
]
| I use wordpress theme in my website. Question is simple, i want to add inside my articles as an inline note, caution, warning quote like picture. How can i do that? Is there any plugin or way to do that?
[](https://i.stack.imgur.com/KuF4z.png) | You can hook into [`the_content`](https://codex.wordpress.org/Plugin_API/Filter_Reference/the_content) filter and add your note after every post. Then you can style it to have a nice quote.
```
add_filter('the_content','add_my_note');
function add_my_note($content){
// Write your note here
$note = '
<div class="my-note">
<h3>Note Header</h3>
<p>Note body</p>
</div>';
// Append the note to the content
$content = $content . $note;
// Return the modified content
return $content;
}
```
This will add the note to your post's content. Now time to style it.
```
.my-note {
display:block;
background:lightgray;
border-width: 0 0 0 3px;
border-color:grey;
color:black;
border-style:solid;
padding: 1em;
}
.my-note h3 {
display:block;
font-size: 2em
}
.my-note p {
display:block;
font-size : 1em;
}
```
I've done some basic styling for you, which you can change to fit your tastes, |
272,053 | <p>I am currently using a <code>WP_Query</code> that'll trigger from an AJAX call when a button is pressed. The post meta fields <code>lat</code> <code>lng</code> will be used as location data for a google map. The query outputs fine without AJAX but cannot seem to get it to return the results with it. </p>
<p>The response I receive - <code>[{name: "", lng: null, lat: null}, {name: "", lng: null, lat: null}]</code></p>
<p>Now I believe the error is when transforming the results into JSON at <code>json_encode</code> stage, but not too sure? Any help would be great, fairly new to AJAX!</p>
<p><strong>Function.php</strong></p>
<pre><code><?php
//Search Function
function ek_search(){
$args = array(
'orderby' => 'date',
'order' => $_POST['date'],
'post_type' => 'property',
'posts_per_page' => 20,
'date_query' => array(
array(
'after' => $_POST['property_added']
),
),
);
$query = new WP_Query( $args );
$posts = $query->get_posts();
foreach( $posts as $post ) {
$locations[] = array(
"name" => get_the_title(),
"lng" => get_field('loc_lng'),
"lat" => get_field('loc_lat')
);
}
$location = json_encode($locations);
echo $location;
die();
}
add_action( 'wp_ajax_nopriv_ek_search', 'ek_search' );
add_action( 'wp_ajax_ek_search', 'ek_search' );
</code></pre>
<p><strong>Form</strong></p>
<pre><code><form id="filter">
<button>Search</button>
<input type="hidden" name="action" value="ek_search">
</form>
</code></pre>
<p><strong>JS</strong></p>
<pre><code>jQuery(function($){
$('#filter').submit(function(){
var filter = $('#filter');
var ajaxurl = '<?php echo admin_url("admin-ajax.php", null); ?>';
data = { action: "ek_search"};
$.ajax({
url: ajaxurl,
data:data,
type: 'post',
dataType: 'json',
success: function(response) {
console.log(response);
}
});
return false;
});
});
</code></pre>
| [
{
"answer_id": 272065,
"author": "Johansson",
"author_id": 94498,
"author_profile": "https://wordpress.stackexchange.com/users/94498",
"pm_score": 4,
"selected": true,
"text": "<p>Admin-AJAX is not optimized for JSON. If you need your answer to be in JSON, use the REST-API instead. This API generates JSON response by default.</p>\n\n<p>All you have to do is to register a rest route, and access the URL:</p>\n\n<pre><code>add_action( 'rest_api_init', function () {\n //Path to REST route and the callback function\n register_rest_route( 'scopeak/v2', '/my_request/', array(\n 'methods' => 'POST', \n 'callback' => 'my_json_response' \n ) );\n});\n</code></pre>\n\n<p>Now, the callback function:</p>\n\n<pre><code>function my_json_response(){\n $args = array(\n 'orderby' => 'date',\n 'order' => $_POST['date'], \n 'post_type' => 'property',\n 'posts_per_page' => 20,\n 'date_query' => array(\n array(\n 'after' => $_POST['property_added']\n ),\n ),\n );\n\n $query = new WP_Query( $args ); \n if($query->have_posts()){\n while($query->have_posts()){\n $query->the_post();\n $locations[]['name'] = get_the_title();\n $locations[]['lat'] = get_field('loc_lng');\n $locations[]['lng'] = get_field('loc_lat');\n }\n }\n //Return the data\n return $locations;\n}\n</code></pre>\n\n<p>Now, you can get your JSON response by visiting the following URL:</p>\n\n<pre><code>wp-json/scopeak/v2/my_json_response/\n</code></pre>\n\n<p>For testing purposes, you can change <code>POST</code> method to <code>GET</code> and directly access this URL. If you get a response, then change it back to <code>POST</code> and work on your javascript.</p>\n\n<p>That's all.</p>\n"
},
{
"answer_id": 272069,
"author": "Cesar Henrique Damascena",
"author_id": 109804,
"author_profile": "https://wordpress.stackexchange.com/users/109804",
"pm_score": 1,
"selected": false,
"text": "<p>First of all, how are you getting the <code>$_POST</code> variables? you have to pass them in your <code>data</code> object on your ajax call. Example:</p>\n\n<pre><code>jQuery(function($){\n$('#filter').submit(function(){\n var filter = $('#filter');\n var ajaxurl = '<?php echo admin_url(\"admin-ajax.php\", null); ?>';\n data = { action: 'ek_search', date: date, property_added: property};\n $.ajax({\n url: ajaxurl,\n data:data,\n type: 'post',\n dataType: 'json',\n success: function(response) {\n console.log(response); \n }\n\n });\n return false;\n });\n});\n</code></pre>\n\n<p>See this <a href=\"https://premium.wpmudev.org/blog/using-ajax-with-wordpress/\" rel=\"nofollow noreferrer\">Article</a> for reference.</p>\n"
},
{
"answer_id": 331810,
"author": "Nikhil Saini",
"author_id": 163267,
"author_profile": "https://wordpress.stackexchange.com/users/163267",
"pm_score": 0,
"selected": false,
"text": "<p>Firstly, I am really sorry for responding a little late.</p>\n\n<p>Second, you need to get the values of your form by using the serialize method, Please check the below example.</p>\n\n<pre><code><form id=\"filter\">\n\n<input type=\"button\" name=\"smt\" value=\"Submit\" id=\"smt\" />\n<input type=\"hidden\" name=\"action\" value=\"ek_search\">\n\n</form>\n\n\n<script src=\"http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js\"></script>\n<script>\n$(document).ready(function(){\nvar form=$(\"#filter\");\n$(\"#smt\").click(function(){\n$.ajax({\n type:\"POST\",\n url:form.attr(\"action\"),\n data:form.serialize(),\n success: function(response){\n console.log(response); \n }\n});\n});\n});\n</script>\n</code></pre>\n"
}
]
| 2017/07/02 | [
"https://wordpress.stackexchange.com/questions/272053",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/87036/"
]
| I am currently using a `WP_Query` that'll trigger from an AJAX call when a button is pressed. The post meta fields `lat` `lng` will be used as location data for a google map. The query outputs fine without AJAX but cannot seem to get it to return the results with it.
The response I receive - `[{name: "", lng: null, lat: null}, {name: "", lng: null, lat: null}]`
Now I believe the error is when transforming the results into JSON at `json_encode` stage, but not too sure? Any help would be great, fairly new to AJAX!
**Function.php**
```
<?php
//Search Function
function ek_search(){
$args = array(
'orderby' => 'date',
'order' => $_POST['date'],
'post_type' => 'property',
'posts_per_page' => 20,
'date_query' => array(
array(
'after' => $_POST['property_added']
),
),
);
$query = new WP_Query( $args );
$posts = $query->get_posts();
foreach( $posts as $post ) {
$locations[] = array(
"name" => get_the_title(),
"lng" => get_field('loc_lng'),
"lat" => get_field('loc_lat')
);
}
$location = json_encode($locations);
echo $location;
die();
}
add_action( 'wp_ajax_nopriv_ek_search', 'ek_search' );
add_action( 'wp_ajax_ek_search', 'ek_search' );
```
**Form**
```
<form id="filter">
<button>Search</button>
<input type="hidden" name="action" value="ek_search">
</form>
```
**JS**
```
jQuery(function($){
$('#filter').submit(function(){
var filter = $('#filter');
var ajaxurl = '<?php echo admin_url("admin-ajax.php", null); ?>';
data = { action: "ek_search"};
$.ajax({
url: ajaxurl,
data:data,
type: 'post',
dataType: 'json',
success: function(response) {
console.log(response);
}
});
return false;
});
});
``` | Admin-AJAX is not optimized for JSON. If you need your answer to be in JSON, use the REST-API instead. This API generates JSON response by default.
All you have to do is to register a rest route, and access the URL:
```
add_action( 'rest_api_init', function () {
//Path to REST route and the callback function
register_rest_route( 'scopeak/v2', '/my_request/', array(
'methods' => 'POST',
'callback' => 'my_json_response'
) );
});
```
Now, the callback function:
```
function my_json_response(){
$args = array(
'orderby' => 'date',
'order' => $_POST['date'],
'post_type' => 'property',
'posts_per_page' => 20,
'date_query' => array(
array(
'after' => $_POST['property_added']
),
),
);
$query = new WP_Query( $args );
if($query->have_posts()){
while($query->have_posts()){
$query->the_post();
$locations[]['name'] = get_the_title();
$locations[]['lat'] = get_field('loc_lng');
$locations[]['lng'] = get_field('loc_lat');
}
}
//Return the data
return $locations;
}
```
Now, you can get your JSON response by visiting the following URL:
```
wp-json/scopeak/v2/my_json_response/
```
For testing purposes, you can change `POST` method to `GET` and directly access this URL. If you get a response, then change it back to `POST` and work on your javascript.
That's all. |
272,075 | <p>Apologies, for the very long title.</p>
<p>I'd really appreciate any help that anyone can offer with a situation I have currently before I go for the plugin option.</p>
<p>About a month ago I moved my site from:</p>
<p><code>http</code> to <code>https</code></p>
<p>I did the move myself and all went well.</p>
<p>Last night I decided to update the Permalink Structure from:</p>
<blockquote>
<p>/category/postname/</p>
</blockquote>
<p>to</p>
<blockquote>
<p>/postname/</p>
</blockquote>
<p>This switch went well and the site is running perfectly.</p>
<p>Now what I need to address is all the old URLs indexed in Google.</p>
<p>I have this <code>.htaccess</code> file on the .com version of my site:</p>
<pre><code>RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^/?(.*) https://%{SERVER_NAME}/$1 [R,L]
# 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
</code></pre>
<p>And I'm wondering if there is a modification that could be made to the above to permanently redirect the indexed URLs to there corresponding post on the new blog.</p>
<p>Indexed URLs such as:</p>
<blockquote>
<p>www.oldsite.net/category/postname</p>
</blockquote>
<p>are returning a 404.</p>
<p>Any help would be really appreciated.</p>
<p>Thanks.</p>
| [
{
"answer_id": 272058,
"author": "wplearner",
"author_id": 120693,
"author_profile": "https://wordpress.stackexchange.com/users/120693",
"pm_score": 2,
"selected": true,
"text": "<p>I am able to locate that file in my theme.\nFor categories woocommerce.php in root directory of my theme is working and i am able to complete my task.<br>\nThank you!</p>\n"
},
{
"answer_id": 272059,
"author": "ashvek",
"author_id": 122436,
"author_profile": "https://wordpress.stackexchange.com/users/122436",
"pm_score": 0,
"selected": false,
"text": "<p>Looks like you were looking for archive.php. You have edit archive.php or use hooks to modify all category pages. Copy plugins/woocommerce/templates/archive.php to themes/yourtheme/woocommerce/archive.php. Not sure how woocommerce.php is working for your.</p>\n"
}
]
| 2017/07/02 | [
"https://wordpress.stackexchange.com/questions/272075",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/123028/"
]
| Apologies, for the very long title.
I'd really appreciate any help that anyone can offer with a situation I have currently before I go for the plugin option.
About a month ago I moved my site from:
`http` to `https`
I did the move myself and all went well.
Last night I decided to update the Permalink Structure from:
>
> /category/postname/
>
>
>
to
>
> /postname/
>
>
>
This switch went well and the site is running perfectly.
Now what I need to address is all the old URLs indexed in Google.
I have this `.htaccess` file on the .com version of my site:
```
RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^/?(.*) https://%{SERVER_NAME}/$1 [R,L]
# 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
```
And I'm wondering if there is a modification that could be made to the above to permanently redirect the indexed URLs to there corresponding post on the new blog.
Indexed URLs such as:
>
> www.oldsite.net/category/postname
>
>
>
are returning a 404.
Any help would be really appreciated.
Thanks. | I am able to locate that file in my theme.
For categories woocommerce.php in root directory of my theme is working and i am able to complete my task.
Thank you! |
272,106 | <p>I'm having a little problem getting an information. In my plugin, I got a situation where I have to throw, in a very specific situation, a 403 error. But I can't find in the documentation if there is a recommended way to throw a 403, because WP LOVES wrap everything it's own way.</p>
<p>So! Do you know a way to trigger a 403 manually ?</p>
<p>Thanks</p>
| [
{
"answer_id": 272107,
"author": "Junaid",
"author_id": 66571,
"author_profile": "https://wordpress.stackexchange.com/users/66571",
"pm_score": 2,
"selected": false,
"text": "<p>Is there any limitation/issue setting/thowing <code>403</code> the usual PHP way?</p>\n\n<pre><code>header('HTTP/1.0 403 Forbidden');\ndie('You are not allowed to access this file.');\n</code></pre>\n"
},
{
"answer_id": 272209,
"author": "Rarst",
"author_id": 847,
"author_profile": "https://wordpress.stackexchange.com/users/847",
"pm_score": 0,
"selected": false,
"text": "<p>Modern PHP CMS/frameworks tend to abstract HTTP protocol as Request/Response.</p>\n\n<p>WP comes from older times and has a very weak concept of HTTP response. Essentially it follow “classical” just throw stuff on a page model.</p>\n\n<p>As such there is no “clean” way to work with headers in it.</p>\n\n<p>De facto approach is just to use some appropriate hook to output custom headers and interrupt remainder of page load, if necessary. Most typical hook to do this on it traditionally <code>template_redirect</code>.</p>\n"
}
]
| 2017/07/03 | [
"https://wordpress.stackexchange.com/questions/272106",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/94823/"
]
| I'm having a little problem getting an information. In my plugin, I got a situation where I have to throw, in a very specific situation, a 403 error. But I can't find in the documentation if there is a recommended way to throw a 403, because WP LOVES wrap everything it's own way.
So! Do you know a way to trigger a 403 manually ?
Thanks | Is there any limitation/issue setting/thowing `403` the usual PHP way?
```
header('HTTP/1.0 403 Forbidden');
die('You are not allowed to access this file.');
``` |
272,108 | <p>I'm trying to add a login/register button to my home page only when a user is logged out. I've tried using the do_shortcode call into the relevant template: (I know there is currently no conditional to check if logged in but I just want to ensure that the shortcode actually works first of all)
<pre><code>add_shortcode('loginout_button','add_loginout_button');
function add_loginout_button {
$content = '<div style="text-align:center;background-color:#7114B7;padding:15px;border-radius:50px;margin:20px;"><a href="">
LOGIN/REGISTER
</a>
</div>';
return $content;
}
</code></pre>
<p>which is then called using the </p>
<pre><code>echo do_shortcode('[loginout_button']);
</code></pre>
<p>in the template, but the shortcode is not registering- it's only echoing [loginout_button]. I guess this is not the way to do it then! Do I have to use a filter and then apply_filters? It made sense in my head but I honestly now need some help with this one- thanks in advance!</p>
| [
{
"answer_id": 272107,
"author": "Junaid",
"author_id": 66571,
"author_profile": "https://wordpress.stackexchange.com/users/66571",
"pm_score": 2,
"selected": false,
"text": "<p>Is there any limitation/issue setting/thowing <code>403</code> the usual PHP way?</p>\n\n<pre><code>header('HTTP/1.0 403 Forbidden');\ndie('You are not allowed to access this file.');\n</code></pre>\n"
},
{
"answer_id": 272209,
"author": "Rarst",
"author_id": 847,
"author_profile": "https://wordpress.stackexchange.com/users/847",
"pm_score": 0,
"selected": false,
"text": "<p>Modern PHP CMS/frameworks tend to abstract HTTP protocol as Request/Response.</p>\n\n<p>WP comes from older times and has a very weak concept of HTTP response. Essentially it follow “classical” just throw stuff on a page model.</p>\n\n<p>As such there is no “clean” way to work with headers in it.</p>\n\n<p>De facto approach is just to use some appropriate hook to output custom headers and interrupt remainder of page load, if necessary. Most typical hook to do this on it traditionally <code>template_redirect</code>.</p>\n"
}
]
| 2017/07/03 | [
"https://wordpress.stackexchange.com/questions/272108",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/123044/"
]
| I'm trying to add a login/register button to my home page only when a user is logged out. I've tried using the do\_shortcode call into the relevant template: (I know there is currently no conditional to check if logged in but I just want to ensure that the shortcode actually works first of all)
```
add_shortcode('loginout_button','add_loginout_button');
function add_loginout_button {
$content = '<div style="text-align:center;background-color:#7114B7;padding:15px;border-radius:50px;margin:20px;"><a href="">
LOGIN/REGISTER
</a>
</div>';
return $content;
}
```
which is then called using the
```
echo do_shortcode('[loginout_button']);
```
in the template, but the shortcode is not registering- it's only echoing [loginout\_button]. I guess this is not the way to do it then! Do I have to use a filter and then apply\_filters? It made sense in my head but I honestly now need some help with this one- thanks in advance! | Is there any limitation/issue setting/thowing `403` the usual PHP way?
```
header('HTTP/1.0 403 Forbidden');
die('You are not allowed to access this file.');
``` |
272,111 | <p>I'm using <code>get_pages()</code> to create a custom navigation that lists pages with a link, title and thumbnail for each page.
How can I add a "current-item" class to the item corresponding to the current page?</p>
<p>I'm using the following code:</p>
<pre><code><?php
$our_pages = get_pages( array( 'sort_column' => 'menu_order' ) );
foreach ($our_pages as $key => $page_item):
?>
<div class="menu-item">
<a href="<?php echo esc_url(get_permalink($page_item->ID)); ?>" class="menu-item-clicker"><span><?php echo $page_item->post_title ; ?></span></a>
<?php echo get_the_post_thumbnail($page_item->ID,'full'); ?>
</div>
<?php endforeach; ?>
</code></pre>
<p>The following does not display the class, but to illustrate what I'm trying to do, here's the conditional I tried, with no success:</p>
<pre><code><?php
$our_pages = get_pages( array( 'sort_column' => 'menu_order' ) );
foreach ($our_pages as $key => $page_item) :
if($page->ID == $page_item->ID) {
$class = 'current-item';
}
?>
<div class="menu-item <?php echo $class; ?>">
<a href="<?php echo esc_url(get_permalink($page_item->ID)); ?>" class="menu-item-clicker"><span><?php echo $page_item->post_title ; ?></span></a>
<?php echo get_the_post_thumbnail($page_item->ID,'full'); ?>
</div>
<?php endforeach; ?>
</code></pre>
<p>Looking forward to your input!</p>
| [
{
"answer_id": 272107,
"author": "Junaid",
"author_id": 66571,
"author_profile": "https://wordpress.stackexchange.com/users/66571",
"pm_score": 2,
"selected": false,
"text": "<p>Is there any limitation/issue setting/thowing <code>403</code> the usual PHP way?</p>\n\n<pre><code>header('HTTP/1.0 403 Forbidden');\ndie('You are not allowed to access this file.');\n</code></pre>\n"
},
{
"answer_id": 272209,
"author": "Rarst",
"author_id": 847,
"author_profile": "https://wordpress.stackexchange.com/users/847",
"pm_score": 0,
"selected": false,
"text": "<p>Modern PHP CMS/frameworks tend to abstract HTTP protocol as Request/Response.</p>\n\n<p>WP comes from older times and has a very weak concept of HTTP response. Essentially it follow “classical” just throw stuff on a page model.</p>\n\n<p>As such there is no “clean” way to work with headers in it.</p>\n\n<p>De facto approach is just to use some appropriate hook to output custom headers and interrupt remainder of page load, if necessary. Most typical hook to do this on it traditionally <code>template_redirect</code>.</p>\n"
}
]
| 2017/07/03 | [
"https://wordpress.stackexchange.com/questions/272111",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/113555/"
]
| I'm using `get_pages()` to create a custom navigation that lists pages with a link, title and thumbnail for each page.
How can I add a "current-item" class to the item corresponding to the current page?
I'm using the following code:
```
<?php
$our_pages = get_pages( array( 'sort_column' => 'menu_order' ) );
foreach ($our_pages as $key => $page_item):
?>
<div class="menu-item">
<a href="<?php echo esc_url(get_permalink($page_item->ID)); ?>" class="menu-item-clicker"><span><?php echo $page_item->post_title ; ?></span></a>
<?php echo get_the_post_thumbnail($page_item->ID,'full'); ?>
</div>
<?php endforeach; ?>
```
The following does not display the class, but to illustrate what I'm trying to do, here's the conditional I tried, with no success:
```
<?php
$our_pages = get_pages( array( 'sort_column' => 'menu_order' ) );
foreach ($our_pages as $key => $page_item) :
if($page->ID == $page_item->ID) {
$class = 'current-item';
}
?>
<div class="menu-item <?php echo $class; ?>">
<a href="<?php echo esc_url(get_permalink($page_item->ID)); ?>" class="menu-item-clicker"><span><?php echo $page_item->post_title ; ?></span></a>
<?php echo get_the_post_thumbnail($page_item->ID,'full'); ?>
</div>
<?php endforeach; ?>
```
Looking forward to your input! | Is there any limitation/issue setting/thowing `403` the usual PHP way?
```
header('HTTP/1.0 403 Forbidden');
die('You are not allowed to access this file.');
``` |
272,128 | <p>I did little tweak for date archive permalink.</p>
<pre><code>function my_rewrite_rules($wp_rewrite){
$rules = array();
$rules['news/([0-9]{4})/?$'] = 'index.php?year=$matches[1]';
$wp_rewrite->rules = $rules + $wp_rewrite->rules;
}
add_action('generate_rewrite_rules', 'my_rewrite_rules');
</code></pre>
<p>Then hit the url below.</p>
<pre><code>http://blahblah.blahblah/wp/news/2017/
</code></pre>
<p>This successfully shows posts belong to 2017. </p>
<p>Now I want to generate the links for date archive, but this doesn't generate the code I want.</p>
<pre><code>get_year_link($year);
</code></pre>
<p>Still generate the default permalink like this:</p>
<pre><code>http://blahblah.blahblah/wp/date/2017/
</code></pre>
<p>So how do I tell wordpress what permastructure to use?
Otherwise I may have to hard code...</p>
| [
{
"answer_id": 276819,
"author": "Luca Reghellin",
"author_id": 10381,
"author_profile": "https://wordpress.stackexchange.com/users/10381",
"pm_score": 1,
"selected": false,
"text": "<p>Yes norixxx, your comment above is the right answer:</p>\n\n<pre><code>add_filter('year_link', 'change_year_link', 10, 2);\nfunction change_year_link($yearlink, $year){\n return home_url(user_trailingslashit('news/'.$year));\n}\n</code></pre>\n\n<p>And thank you for sharing!</p>\n\n<p>Below, users can find an 'expanded' version:</p>\n\n<pre><code>// generate /year, /year/month, /year/month/post-slug rules\nadd_action('generate_rewrite_rules', 'rewrite_rules');\nfunction rewrite_rules($wp_rewrite){\n $rules = array();\n $rules['news/([0-9]{4})/?$'] = 'index.php?year=$matches[1]';\n $rules['news/([0-9]{4})/([0-9]{2})/?$'] = 'index.php?year=$matches[1]&monthnum=$matches[2]';\n $rules['news/([0-9]{4})/([0-9]{2})/([^/]+)/?$'] = 'index.php?year=$matches[1]&monthnum=$matches[2]&name=$matches[3]';\n $wp_rewrite->rules = $rules + $wp_rewrite->rules;\n}\n\n\nadd_filter('year_link', 'change_year_link', 10, 2);\nfunction change_year_link($yearlink, $year){\n return home_url(user_trailingslashit('news/'.$year));\n}\n\nadd_filter('month_link', 'change_month_link', 10, 2);\nfunction change_month_link($yearlink, $year, $month){\n return home_url(user_trailingslashit('news/'.$year.'/'.$month));\n}\n\n// this last is for generating /year/month/post-slug links\n// I think it can be optional. Keep in mind that by applying this filter,\n// You won't be able to manually modify the slug in admin edit post view\nadd_filter('post_link', 'set_post_links' , 10, 2);\nfunction set_post_links($permalink, $post){\n if(is_wp_error($post) || empty($post->post_name)) return $permalink;\n\n if('post' == $post->post_type){\n $year = get_the_date('Y', $post->ID);\n $month = get_the_date('m', $post->ID);\n return home_url(user_trailingslashit(\"$year/$month/$post->post_name\"));\n }\n\n return $permalink;\n} \n\n\n// If you use the post_link filter, \n// probably you'll want to auto-update post slugs upon post title modifications. \n// Here's how:\nadd_filter('wp_insert_post_data', 'update_post_data' , 10, 2);\nfunction update_post_data($data, $postarr){\n // protect non-post posts\n if($data['post_type'] !== 'post') return $data;\n\n $data['post_name'] = wp_unique_post_slug(sanitize_title($data['post_title']), $postarr['ID'], $data['post_status'], $data['post_type'], $data['post_parent']);\n return $data;\n}\n</code></pre>\n"
},
{
"answer_id": 289968,
"author": "Milo",
"author_id": 4771,
"author_profile": "https://wordpress.stackexchange.com/users/4771",
"pm_score": 2,
"selected": false,
"text": "<p>You can change the date links by directly modifying the <code>date_structure</code>:</p>\n\n<pre><code>function wpd_change_date_structure(){\n global $wp_rewrite;\n $wp_rewrite->date_structure = 'news/%year%/%monthnum%/%day%';\n}\nadd_action( 'init', 'wpd_change_date_structure' );\n</code></pre>\n\n<p>Don't forget to flush rewrite rules after the change.</p>\n\n<p>WordPress will use this to generate the rewrite rules for incoming requests as well as URL output when using API functions like <code>get_year_link</code>, so there's no need for a filter.</p>\n"
}
]
| 2017/07/03 | [
"https://wordpress.stackexchange.com/questions/272128",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/37130/"
]
| I did little tweak for date archive permalink.
```
function my_rewrite_rules($wp_rewrite){
$rules = array();
$rules['news/([0-9]{4})/?$'] = 'index.php?year=$matches[1]';
$wp_rewrite->rules = $rules + $wp_rewrite->rules;
}
add_action('generate_rewrite_rules', 'my_rewrite_rules');
```
Then hit the url below.
```
http://blahblah.blahblah/wp/news/2017/
```
This successfully shows posts belong to 2017.
Now I want to generate the links for date archive, but this doesn't generate the code I want.
```
get_year_link($year);
```
Still generate the default permalink like this:
```
http://blahblah.blahblah/wp/date/2017/
```
So how do I tell wordpress what permastructure to use?
Otherwise I may have to hard code... | You can change the date links by directly modifying the `date_structure`:
```
function wpd_change_date_structure(){
global $wp_rewrite;
$wp_rewrite->date_structure = 'news/%year%/%monthnum%/%day%';
}
add_action( 'init', 'wpd_change_date_structure' );
```
Don't forget to flush rewrite rules after the change.
WordPress will use this to generate the rewrite rules for incoming requests as well as URL output when using API functions like `get_year_link`, so there's no need for a filter. |
272,130 | <p>I have already tried about 20 different methods to get this working with no solution.</p>
<p>I am trying to change the classes of the buttons in the WooCommerce mini cart widget as shown below.</p>
<p><a href="https://i.stack.imgur.com/XO8L9.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/XO8L9.png" alt="enter image description here"></a></p>
<p>The mark up for those buttons is written in two functions inside the wc-template-functions.php file:</p>
<pre><code>if ( ! function_exists( 'woocommerce_widget_shopping_cart_button_view_cart' ) ) {
/**
* Output the proceed to checkout button.
*
* @subpackage Cart
*/
function woocommerce_widget_shopping_cart_button_view_cart() {
echo '<a href="' . esc_url( wc_get_cart_url() ) . '" class="button wc-forward">' . esc_html__( 'View cart', 'woocommerce' ) . '</a>';
}
}
if ( ! function_exists( 'woocommerce_widget_shopping_cart_proceed_to_checkout' ) ) {
/**
* Output the proceed to checkout button.
*
* @subpackage Cart
*/
function woocommerce_widget_shopping_cart_proceed_to_checkout() {
echo '<a href="' . esc_url( wc_get_checkout_url() ) . '" class="button checkout wc-forward">' . esc_html__( 'Checkout', 'woocommerce' ) . '</a>';
}
}
</code></pre>
<p>What is the correct way to override these functions within my own theme so that i can change the classes of those two buttons?</p>
| [
{
"answer_id": 281853,
"author": "Mat",
"author_id": 37985,
"author_profile": "https://wordpress.stackexchange.com/users/37985",
"pm_score": 2,
"selected": false,
"text": "<p>Not sure if you still need help with this but this might help others in your situation.</p>\n\n<p>If you want to change the class of the <code><p></code> tag in your example, the file you need to edit can be found in <code>/wp-content/plugins/woocommerce/templates/cart/mini-cart.php</code></p>\n\n<p>Obviously, don't directly edit the file. Copy it in to your theme (or preferably child theme) folder under <code>/wp-content/themes/your-theme-folder/woocommerce/cart/mini-cart.php</code> and you can edit line #75 to put in your own CSS class(es). Line #75 reads:</p>\n\n<pre><code><p class=\"woocommerce-mini-cart__buttons buttons\"><?php do_action( 'woocommerce_widget_shopping_cart_buttons' ); ?></p>\n</code></pre>\n\n<p>If you want to alter the CSS class of the <code><a></code> tag, then you'll need to remove the default 'action' and create your own within your theme (or preferably child themes) <code>functions.php</code> file eg.</p>\n\n<pre><code>remove_action( 'woocommerce_widget_shopping_cart_buttons', 'woocommerce_widget_shopping_cart_button_view_cart', 10 );\nremove_action( 'woocommerce_widget_shopping_cart_buttons', 'woocommerce_widget_shopping_cart_proceed_to_checkout', 20 );\n\nfunction my_woocommerce_widget_shopping_cart_button_view_cart() {\n echo '<a href=\"' . esc_url( wc_get_cart_url() ) . '\" class=\"btn btn-default\">' . esc_html__( 'View cart', 'woocommerce' ) . '</a>';\n}\nfunction my_woocommerce_widget_shopping_cart_proceed_to_checkout() {\n echo '<a href=\"' . esc_url( wc_get_checkout_url() ) . '\" class=\"btn btn-default\">' . esc_html__( 'Checkout', 'woocommerce' ) . '</a>';\n}\nadd_action( 'woocommerce_widget_shopping_cart_buttons', 'my_woocommerce_widget_shopping_cart_button_view_cart', 10 );\nadd_action( 'woocommerce_widget_shopping_cart_buttons', 'my_woocommerce_widget_shopping_cart_proceed_to_checkout', 20 );\n</code></pre>\n\n<p>You'll need to clear your browser cache or add another item to the cart to see the changes as the cart content is saved in the browsers sessionStorage to avoid pulling a new copy on every page.</p>\n"
},
{
"answer_id": 387428,
"author": "Ruvee",
"author_id": 200813,
"author_profile": "https://wordpress.stackexchange.com/users/200813",
"pm_score": 1,
"selected": false,
"text": "<p>The code in the old answer no longer works. <strong>The approach is still valid</strong> but the code doesn't work. So the following code works at the moment, you could plug it into your <code>functions.php</code>. (<strong>April 2021</strong>):</p>\n<p>Shout out to Mat, thank you for your answer.</p>\n<pre class=\"lang-php prettyprint-override\"><code>function custom_widget_cart_btn_view_cart()\n{\n echo '<a href="' . esc_url(wc_get_cart_url()) . '" class="button wc-forward">' . esc_html__('Custom View Cart', 'woocommerce') . '</a>';\n}\n\nfunction custom_widget_cart_checkout()\n{\n echo '<a href="' . esc_url(wc_get_checkout_url()) . '" class="button checkout wc-forward">' . esc_html__('Custom Checkout', 'woocommerce') . '</a>';\n}\n\nfunction custom_widget_cart_subtotal()\n{\n echo '<strong>' . esc_html__('Custom Subtotal: ', 'woocommerce') . '</strong> ' . WC()->cart->get_cart_subtotal();\n}\n\nremove_action('woocommerce_widget_shopping_cart_total', 'woocommerce_widget_shopping_cart_subtotal', 10);\nremove_action('woocommerce_widget_shopping_cart_buttons', 'woocommerce_widget_shopping_cart_button_view_cart', 10);\nremove_action('woocommerce_widget_shopping_cart_buttons', 'woocommerce_widget_shopping_cart_proceed_to_checkout', 20);\n\nadd_action('woocommerce_widget_shopping_cart_total', 'custom_widget_cart_subtotal', 11);\nadd_action('woocommerce_widget_shopping_cart_buttons', 'custom_widget_cart_btn_view_cart', 12);\nadd_action('woocommerce_widget_shopping_cart_buttons', 'custom_widget_cart_checkout', 21);\n</code></pre>\n"
}
]
| 2017/07/03 | [
"https://wordpress.stackexchange.com/questions/272130",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/118673/"
]
| I have already tried about 20 different methods to get this working with no solution.
I am trying to change the classes of the buttons in the WooCommerce mini cart widget as shown below.
[](https://i.stack.imgur.com/XO8L9.png)
The mark up for those buttons is written in two functions inside the wc-template-functions.php file:
```
if ( ! function_exists( 'woocommerce_widget_shopping_cart_button_view_cart' ) ) {
/**
* Output the proceed to checkout button.
*
* @subpackage Cart
*/
function woocommerce_widget_shopping_cart_button_view_cart() {
echo '<a href="' . esc_url( wc_get_cart_url() ) . '" class="button wc-forward">' . esc_html__( 'View cart', 'woocommerce' ) . '</a>';
}
}
if ( ! function_exists( 'woocommerce_widget_shopping_cart_proceed_to_checkout' ) ) {
/**
* Output the proceed to checkout button.
*
* @subpackage Cart
*/
function woocommerce_widget_shopping_cart_proceed_to_checkout() {
echo '<a href="' . esc_url( wc_get_checkout_url() ) . '" class="button checkout wc-forward">' . esc_html__( 'Checkout', 'woocommerce' ) . '</a>';
}
}
```
What is the correct way to override these functions within my own theme so that i can change the classes of those two buttons? | Not sure if you still need help with this but this might help others in your situation.
If you want to change the class of the `<p>` tag in your example, the file you need to edit can be found in `/wp-content/plugins/woocommerce/templates/cart/mini-cart.php`
Obviously, don't directly edit the file. Copy it in to your theme (or preferably child theme) folder under `/wp-content/themes/your-theme-folder/woocommerce/cart/mini-cart.php` and you can edit line #75 to put in your own CSS class(es). Line #75 reads:
```
<p class="woocommerce-mini-cart__buttons buttons"><?php do_action( 'woocommerce_widget_shopping_cart_buttons' ); ?></p>
```
If you want to alter the CSS class of the `<a>` tag, then you'll need to remove the default 'action' and create your own within your theme (or preferably child themes) `functions.php` file eg.
```
remove_action( 'woocommerce_widget_shopping_cart_buttons', 'woocommerce_widget_shopping_cart_button_view_cart', 10 );
remove_action( 'woocommerce_widget_shopping_cart_buttons', 'woocommerce_widget_shopping_cart_proceed_to_checkout', 20 );
function my_woocommerce_widget_shopping_cart_button_view_cart() {
echo '<a href="' . esc_url( wc_get_cart_url() ) . '" class="btn btn-default">' . esc_html__( 'View cart', 'woocommerce' ) . '</a>';
}
function my_woocommerce_widget_shopping_cart_proceed_to_checkout() {
echo '<a href="' . esc_url( wc_get_checkout_url() ) . '" class="btn btn-default">' . esc_html__( 'Checkout', 'woocommerce' ) . '</a>';
}
add_action( 'woocommerce_widget_shopping_cart_buttons', 'my_woocommerce_widget_shopping_cart_button_view_cart', 10 );
add_action( 'woocommerce_widget_shopping_cart_buttons', 'my_woocommerce_widget_shopping_cart_proceed_to_checkout', 20 );
```
You'll need to clear your browser cache or add another item to the cart to see the changes as the cart content is saved in the browsers sessionStorage to avoid pulling a new copy on every page. |
272,135 | <p>I have created a page on one of our sites which has a few snippets of custom CSS to make it display in a very modern, 100% width style <a href="http://www.hotrs.co.uk/" rel="nofollow noreferrer">like this</a>, as opposed to the standard, more constrained style of pages the site's theme allows. </p>
<p>This style of page, however, is not going to be used site-wide, so getting a new theme or editing the existing theme's child isn't really an option. </p>
<p>What I'd instead like to do is create a simple plugin that will add a checkbox to the edit page that, when checked, will load this custom CSS on the page in question. I know roughly how to set a plugin up, but how would I write it to;</p>
<ul>
<li>Add a checkbox to the edit page?</li>
<li>If the checkbox is ticked, load the custom CSS?</li>
</ul>
<p>While I could just add this custom CSS to each page manually, creating a plugin would mean transporting the code around from site to site will be much easier, and also mean that the risk of overwriting and losing it would be minimized.</p>
| [
{
"answer_id": 281853,
"author": "Mat",
"author_id": 37985,
"author_profile": "https://wordpress.stackexchange.com/users/37985",
"pm_score": 2,
"selected": false,
"text": "<p>Not sure if you still need help with this but this might help others in your situation.</p>\n\n<p>If you want to change the class of the <code><p></code> tag in your example, the file you need to edit can be found in <code>/wp-content/plugins/woocommerce/templates/cart/mini-cart.php</code></p>\n\n<p>Obviously, don't directly edit the file. Copy it in to your theme (or preferably child theme) folder under <code>/wp-content/themes/your-theme-folder/woocommerce/cart/mini-cart.php</code> and you can edit line #75 to put in your own CSS class(es). Line #75 reads:</p>\n\n<pre><code><p class=\"woocommerce-mini-cart__buttons buttons\"><?php do_action( 'woocommerce_widget_shopping_cart_buttons' ); ?></p>\n</code></pre>\n\n<p>If you want to alter the CSS class of the <code><a></code> tag, then you'll need to remove the default 'action' and create your own within your theme (or preferably child themes) <code>functions.php</code> file eg.</p>\n\n<pre><code>remove_action( 'woocommerce_widget_shopping_cart_buttons', 'woocommerce_widget_shopping_cart_button_view_cart', 10 );\nremove_action( 'woocommerce_widget_shopping_cart_buttons', 'woocommerce_widget_shopping_cart_proceed_to_checkout', 20 );\n\nfunction my_woocommerce_widget_shopping_cart_button_view_cart() {\n echo '<a href=\"' . esc_url( wc_get_cart_url() ) . '\" class=\"btn btn-default\">' . esc_html__( 'View cart', 'woocommerce' ) . '</a>';\n}\nfunction my_woocommerce_widget_shopping_cart_proceed_to_checkout() {\n echo '<a href=\"' . esc_url( wc_get_checkout_url() ) . '\" class=\"btn btn-default\">' . esc_html__( 'Checkout', 'woocommerce' ) . '</a>';\n}\nadd_action( 'woocommerce_widget_shopping_cart_buttons', 'my_woocommerce_widget_shopping_cart_button_view_cart', 10 );\nadd_action( 'woocommerce_widget_shopping_cart_buttons', 'my_woocommerce_widget_shopping_cart_proceed_to_checkout', 20 );\n</code></pre>\n\n<p>You'll need to clear your browser cache or add another item to the cart to see the changes as the cart content is saved in the browsers sessionStorage to avoid pulling a new copy on every page.</p>\n"
},
{
"answer_id": 387428,
"author": "Ruvee",
"author_id": 200813,
"author_profile": "https://wordpress.stackexchange.com/users/200813",
"pm_score": 1,
"selected": false,
"text": "<p>The code in the old answer no longer works. <strong>The approach is still valid</strong> but the code doesn't work. So the following code works at the moment, you could plug it into your <code>functions.php</code>. (<strong>April 2021</strong>):</p>\n<p>Shout out to Mat, thank you for your answer.</p>\n<pre class=\"lang-php prettyprint-override\"><code>function custom_widget_cart_btn_view_cart()\n{\n echo '<a href="' . esc_url(wc_get_cart_url()) . '" class="button wc-forward">' . esc_html__('Custom View Cart', 'woocommerce') . '</a>';\n}\n\nfunction custom_widget_cart_checkout()\n{\n echo '<a href="' . esc_url(wc_get_checkout_url()) . '" class="button checkout wc-forward">' . esc_html__('Custom Checkout', 'woocommerce') . '</a>';\n}\n\nfunction custom_widget_cart_subtotal()\n{\n echo '<strong>' . esc_html__('Custom Subtotal: ', 'woocommerce') . '</strong> ' . WC()->cart->get_cart_subtotal();\n}\n\nremove_action('woocommerce_widget_shopping_cart_total', 'woocommerce_widget_shopping_cart_subtotal', 10);\nremove_action('woocommerce_widget_shopping_cart_buttons', 'woocommerce_widget_shopping_cart_button_view_cart', 10);\nremove_action('woocommerce_widget_shopping_cart_buttons', 'woocommerce_widget_shopping_cart_proceed_to_checkout', 20);\n\nadd_action('woocommerce_widget_shopping_cart_total', 'custom_widget_cart_subtotal', 11);\nadd_action('woocommerce_widget_shopping_cart_buttons', 'custom_widget_cart_btn_view_cart', 12);\nadd_action('woocommerce_widget_shopping_cart_buttons', 'custom_widget_cart_checkout', 21);\n</code></pre>\n"
}
]
| 2017/07/03 | [
"https://wordpress.stackexchange.com/questions/272135",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/120427/"
]
| I have created a page on one of our sites which has a few snippets of custom CSS to make it display in a very modern, 100% width style [like this](http://www.hotrs.co.uk/), as opposed to the standard, more constrained style of pages the site's theme allows.
This style of page, however, is not going to be used site-wide, so getting a new theme or editing the existing theme's child isn't really an option.
What I'd instead like to do is create a simple plugin that will add a checkbox to the edit page that, when checked, will load this custom CSS on the page in question. I know roughly how to set a plugin up, but how would I write it to;
* Add a checkbox to the edit page?
* If the checkbox is ticked, load the custom CSS?
While I could just add this custom CSS to each page manually, creating a plugin would mean transporting the code around from site to site will be much easier, and also mean that the risk of overwriting and losing it would be minimized. | Not sure if you still need help with this but this might help others in your situation.
If you want to change the class of the `<p>` tag in your example, the file you need to edit can be found in `/wp-content/plugins/woocommerce/templates/cart/mini-cart.php`
Obviously, don't directly edit the file. Copy it in to your theme (or preferably child theme) folder under `/wp-content/themes/your-theme-folder/woocommerce/cart/mini-cart.php` and you can edit line #75 to put in your own CSS class(es). Line #75 reads:
```
<p class="woocommerce-mini-cart__buttons buttons"><?php do_action( 'woocommerce_widget_shopping_cart_buttons' ); ?></p>
```
If you want to alter the CSS class of the `<a>` tag, then you'll need to remove the default 'action' and create your own within your theme (or preferably child themes) `functions.php` file eg.
```
remove_action( 'woocommerce_widget_shopping_cart_buttons', 'woocommerce_widget_shopping_cart_button_view_cart', 10 );
remove_action( 'woocommerce_widget_shopping_cart_buttons', 'woocommerce_widget_shopping_cart_proceed_to_checkout', 20 );
function my_woocommerce_widget_shopping_cart_button_view_cart() {
echo '<a href="' . esc_url( wc_get_cart_url() ) . '" class="btn btn-default">' . esc_html__( 'View cart', 'woocommerce' ) . '</a>';
}
function my_woocommerce_widget_shopping_cart_proceed_to_checkout() {
echo '<a href="' . esc_url( wc_get_checkout_url() ) . '" class="btn btn-default">' . esc_html__( 'Checkout', 'woocommerce' ) . '</a>';
}
add_action( 'woocommerce_widget_shopping_cart_buttons', 'my_woocommerce_widget_shopping_cart_button_view_cart', 10 );
add_action( 'woocommerce_widget_shopping_cart_buttons', 'my_woocommerce_widget_shopping_cart_proceed_to_checkout', 20 );
```
You'll need to clear your browser cache or add another item to the cart to see the changes as the cart content is saved in the browsers sessionStorage to avoid pulling a new copy on every page. |
272,158 | <p>I have a custom post type called <code>vacancies</code> and another called <code>our_homes</code></p>
<p>How do I get the google map coordinates from <code>our_homes</code> and display inside the <code>vacancies</code> single post template?</p>
<p>My attempt below shows my tragic attempt at code inside the single-vacancies.php file:</p>
<pre><code> <?php
//Query custom post type our_homes and display tabs for each
$query = new WP_Query( array( 'post_type' => 'our_homes', 'field' => 'slug', 'posts_per_page' => 999 ) );
if ( $query->have_posts() ) :
//$count = 1;
//$title = the_title();
//$location = get_field('google_map_coordinates');
?>
<?php while ( $query->have_posts() ) : $query->the_post();
$location = get_field('google_map_coordinates', post_title);
?>
<?php if($title = $label) { echo $title; }
//echo $label;
?>
<?php endwhile; wp_reset_postdata(); ?>
<?php endif; ?>
</code></pre>
| [
{
"answer_id": 272164,
"author": "Cesar Henrique Damascena",
"author_id": 109804,
"author_profile": "https://wordpress.stackexchange.com/users/109804",
"pm_score": -1,
"selected": false,
"text": "<p>Try to do this inside the loop</p>\n\n<pre><code>$location = get_field('google_map_coordinates', get_the_ID);\n</code></pre>\n\n<p>See reference at <a href=\"https://www.advancedcustomfields.com/resources/get_field/\" rel=\"nofollow noreferrer\">ACF Documentation</a></p>\n"
},
{
"answer_id": 272167,
"author": "Johansson",
"author_id": 94498,
"author_profile": "https://wordpress.stackexchange.com/users/94498",
"pm_score": 0,
"selected": false,
"text": "<p>Although your question is confusing, but based on your attempts, I can say that you are using a loop inside another loop. You should store an array of main loop's titles in an array, and then write another loop <strong>outside</strong> the original loop and check the array.</p>\n\n<p>So, this is what your main query would look like (I summarized it and removed the actual loop):</p>\n\n<pre><code>if(have_posts()){\n // Define an empty array\n $posts_title = array();\n while(have_posts()){\n // Store each title inside the array\n $posts_title[] = get_the_title();\n }\n}\n</code></pre>\n\n<p>Now, you have an array of post titles. Write this query after the main query is finished, and closed:</p>\n\n<pre><code>$query = new WP_Query( \n array( \n 'post_type' => 'our_homes',\n 'posts_per_page' => -1 \n ) \n); \nif ( $query->have_posts() ) { \n$count = 0;\n while ( $query->have_posts() ) { \n $query->the_post(); \n $count++;\n // Check if this post's title matches the $label\n if( in_array( get_the_title(), $posts_title )) {\n // Do whatever you want\n the_title();\n }\n }\n}\nwp_reset_postdata();\n</code></pre>\n\n<p>Also, if you need to get the post's or page's ID by their title, you can use <a href=\"https://codex.wordpress.org/Function_Reference/get_page_by_title\" rel=\"nofollow noreferrer\"><code>get_page_by_title('TITLE HERE')</code></a> function.</p>\n"
}
]
| 2017/07/03 | [
"https://wordpress.stackexchange.com/questions/272158",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/63480/"
]
| I have a custom post type called `vacancies` and another called `our_homes`
How do I get the google map coordinates from `our_homes` and display inside the `vacancies` single post template?
My attempt below shows my tragic attempt at code inside the single-vacancies.php file:
```
<?php
//Query custom post type our_homes and display tabs for each
$query = new WP_Query( array( 'post_type' => 'our_homes', 'field' => 'slug', 'posts_per_page' => 999 ) );
if ( $query->have_posts() ) :
//$count = 1;
//$title = the_title();
//$location = get_field('google_map_coordinates');
?>
<?php while ( $query->have_posts() ) : $query->the_post();
$location = get_field('google_map_coordinates', post_title);
?>
<?php if($title = $label) { echo $title; }
//echo $label;
?>
<?php endwhile; wp_reset_postdata(); ?>
<?php endif; ?>
``` | Although your question is confusing, but based on your attempts, I can say that you are using a loop inside another loop. You should store an array of main loop's titles in an array, and then write another loop **outside** the original loop and check the array.
So, this is what your main query would look like (I summarized it and removed the actual loop):
```
if(have_posts()){
// Define an empty array
$posts_title = array();
while(have_posts()){
// Store each title inside the array
$posts_title[] = get_the_title();
}
}
```
Now, you have an array of post titles. Write this query after the main query is finished, and closed:
```
$query = new WP_Query(
array(
'post_type' => 'our_homes',
'posts_per_page' => -1
)
);
if ( $query->have_posts() ) {
$count = 0;
while ( $query->have_posts() ) {
$query->the_post();
$count++;
// Check if this post's title matches the $label
if( in_array( get_the_title(), $posts_title )) {
// Do whatever you want
the_title();
}
}
}
wp_reset_postdata();
```
Also, if you need to get the post's or page's ID by their title, you can use [`get_page_by_title('TITLE HERE')`](https://codex.wordpress.org/Function_Reference/get_page_by_title) function. |
272,161 | <p>I am customizing a theme that has the following code to display comments:</p>
<pre><code>if ( have_comments() ) : ?>
<h2 class="comments-title">
<?php
printf( // WPCS: XSS OK.
esc_html( _nx( 'One thought on &ldquo;%2$s&rdquo;', '%1$s thoughts on &ldquo;%2$s&rdquo;', get_comments_number(), 'comments title', 'kadabra' ) ),
number_format_i18n( get_comments_number() ),
'<span>' . get_the_title() . '</span>'
);
?>
</h2>
</code></pre>
<p>however it always shows the following:</p>
<pre><code>0 thoughts on “Post title”
</code></pre>
<p>even though I have several comments and the <code>if ( have_comments() ) :</code> part is passed. Any ideas?</p>
<p>PS: wp_debug is enabled and show no errors as well.</p>
| [
{
"answer_id": 272178,
"author": "Rarst",
"author_id": 847,
"author_profile": "https://wordpress.stackexchange.com/users/847",
"pm_score": 1,
"selected": false,
"text": "<p>From quick look at the source there seems to be three possibilities:</p>\n\n<ol>\n<li><code>get_post()</code> returned <em>falsy</em> value, so current post context is invalid in some way.</li>\n<li><code>$post->comment_count</code> is <code>0</code>.</li>\n<li><code>get_comments_number</code> filter is being used to adjust the output.</li>\n</ol>\n\n<p>Most commonly it would be case 1/2 with something interfering with global post context, dump <code>get_post()</code> at the point and see if it contains expected instance.</p>\n"
},
{
"answer_id": 361542,
"author": "Mantas Lukosevicius",
"author_id": 163560,
"author_profile": "https://wordpress.stackexchange.com/users/163560",
"pm_score": 0,
"selected": false,
"text": "<p>What probably happened is that you did not approve comments in admin panel.</p>\n\n<p>When you only have comments that are \"pending\" you still pass <code>have_comments()</code>, but those comments are not counted.</p>\n"
}
]
| 2017/07/03 | [
"https://wordpress.stackexchange.com/questions/272161",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/103046/"
]
| I am customizing a theme that has the following code to display comments:
```
if ( have_comments() ) : ?>
<h2 class="comments-title">
<?php
printf( // WPCS: XSS OK.
esc_html( _nx( 'One thought on “%2$s”', '%1$s thoughts on “%2$s”', get_comments_number(), 'comments title', 'kadabra' ) ),
number_format_i18n( get_comments_number() ),
'<span>' . get_the_title() . '</span>'
);
?>
</h2>
```
however it always shows the following:
```
0 thoughts on “Post title”
```
even though I have several comments and the `if ( have_comments() ) :` part is passed. Any ideas?
PS: wp\_debug is enabled and show no errors as well. | From quick look at the source there seems to be three possibilities:
1. `get_post()` returned *falsy* value, so current post context is invalid in some way.
2. `$post->comment_count` is `0`.
3. `get_comments_number` filter is being used to adjust the output.
Most commonly it would be case 1/2 with something interfering with global post context, dump `get_post()` at the point and see if it contains expected instance. |
272,163 | <p>I create a new db connection with: $mydb = new wpdb (<em>db info</em>)</p>
<p>I know it connects but for some reason I am unable to get any data from: </p>
<pre><code>$pulled = $mydb->get_results($mydb->prepare($query), "ARRAY_A").
</code></pre>
<p>I know the query it self is written correctly but for some reason $pulled contains no data. Anyone have any suggestions or solutions, please and thank you.</p>
| [
{
"answer_id": 272178,
"author": "Rarst",
"author_id": 847,
"author_profile": "https://wordpress.stackexchange.com/users/847",
"pm_score": 1,
"selected": false,
"text": "<p>From quick look at the source there seems to be three possibilities:</p>\n\n<ol>\n<li><code>get_post()</code> returned <em>falsy</em> value, so current post context is invalid in some way.</li>\n<li><code>$post->comment_count</code> is <code>0</code>.</li>\n<li><code>get_comments_number</code> filter is being used to adjust the output.</li>\n</ol>\n\n<p>Most commonly it would be case 1/2 with something interfering with global post context, dump <code>get_post()</code> at the point and see if it contains expected instance.</p>\n"
},
{
"answer_id": 361542,
"author": "Mantas Lukosevicius",
"author_id": 163560,
"author_profile": "https://wordpress.stackexchange.com/users/163560",
"pm_score": 0,
"selected": false,
"text": "<p>What probably happened is that you did not approve comments in admin panel.</p>\n\n<p>When you only have comments that are \"pending\" you still pass <code>have_comments()</code>, but those comments are not counted.</p>\n"
}
]
| 2017/07/03 | [
"https://wordpress.stackexchange.com/questions/272163",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/123061/"
]
| I create a new db connection with: $mydb = new wpdb (*db info*)
I know it connects but for some reason I am unable to get any data from:
```
$pulled = $mydb->get_results($mydb->prepare($query), "ARRAY_A").
```
I know the query it self is written correctly but for some reason $pulled contains no data. Anyone have any suggestions or solutions, please and thank you. | From quick look at the source there seems to be three possibilities:
1. `get_post()` returned *falsy* value, so current post context is invalid in some way.
2. `$post->comment_count` is `0`.
3. `get_comments_number` filter is being used to adjust the output.
Most commonly it would be case 1/2 with something interfering with global post context, dump `get_post()` at the point and see if it contains expected instance. |
272,179 | <p>I know this has been covered in different ways a thousand times (I read all the posts), but it seems not specifically for my case. I can't really get it to work myself, being a big development noobie. </p>
<p>I have a template which shows the last posts on the front page. I changed the type of posts shown to <code>question</code> (my website is a Q&A one) but then pagination was only showing 13 pages while there are 29 pages of questions. 13 pages being the number of non-custom-type normal posts.
So I added this code in <code>functions.php</code>: </p>
<pre><code>add_action( 'pre_get_posts', function($q) {
if( !is_admin() && $q->is_main_query() && !$q->is_tax() ) {
$q->set ('post_type', array( 'question' ) );
}
});
</code></pre>
<p>Now it counts the number of Questions correctly but it throws a 404 error every time I click on the link to a question. I understand that <code>pre_get_posts</code> is not the best approach, but I really don't know how to change it and use <code>WP_Query</code> instead, as I saw was advised to.</p>
<p>Any fix to that ? Thank you <3 </p>
| [
{
"answer_id": 272178,
"author": "Rarst",
"author_id": 847,
"author_profile": "https://wordpress.stackexchange.com/users/847",
"pm_score": 1,
"selected": false,
"text": "<p>From quick look at the source there seems to be three possibilities:</p>\n\n<ol>\n<li><code>get_post()</code> returned <em>falsy</em> value, so current post context is invalid in some way.</li>\n<li><code>$post->comment_count</code> is <code>0</code>.</li>\n<li><code>get_comments_number</code> filter is being used to adjust the output.</li>\n</ol>\n\n<p>Most commonly it would be case 1/2 with something interfering with global post context, dump <code>get_post()</code> at the point and see if it contains expected instance.</p>\n"
},
{
"answer_id": 361542,
"author": "Mantas Lukosevicius",
"author_id": 163560,
"author_profile": "https://wordpress.stackexchange.com/users/163560",
"pm_score": 0,
"selected": false,
"text": "<p>What probably happened is that you did not approve comments in admin panel.</p>\n\n<p>When you only have comments that are \"pending\" you still pass <code>have_comments()</code>, but those comments are not counted.</p>\n"
}
]
| 2017/07/03 | [
"https://wordpress.stackexchange.com/questions/272179",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/107594/"
]
| I know this has been covered in different ways a thousand times (I read all the posts), but it seems not specifically for my case. I can't really get it to work myself, being a big development noobie.
I have a template which shows the last posts on the front page. I changed the type of posts shown to `question` (my website is a Q&A one) but then pagination was only showing 13 pages while there are 29 pages of questions. 13 pages being the number of non-custom-type normal posts.
So I added this code in `functions.php`:
```
add_action( 'pre_get_posts', function($q) {
if( !is_admin() && $q->is_main_query() && !$q->is_tax() ) {
$q->set ('post_type', array( 'question' ) );
}
});
```
Now it counts the number of Questions correctly but it throws a 404 error every time I click on the link to a question. I understand that `pre_get_posts` is not the best approach, but I really don't know how to change it and use `WP_Query` instead, as I saw was advised to.
Any fix to that ? Thank you <3 | From quick look at the source there seems to be three possibilities:
1. `get_post()` returned *falsy* value, so current post context is invalid in some way.
2. `$post->comment_count` is `0`.
3. `get_comments_number` filter is being used to adjust the output.
Most commonly it would be case 1/2 with something interfering with global post context, dump `get_post()` at the point and see if it contains expected instance. |
272,236 | <p>I am trying to load several scripts and stylesheets into a plugin I am creating. I want to load scripts into multiple CPTs within admin. I have got this far:</p>
<pre><code>function fhaac_admin_enqueue_scripts(){
global $pagenow, $typenow;
if ( ($pagenow == 'post.php' || $pagenow == 'post-new.php') && $typenow == 'fhaac' ){}
}
</code></pre>
<p>The scripts are being loaded into the fhaac, but nothing else. I am not sure how to add multiple CPTs. I tried adding them in an array, but it didn't work. </p>
<p>Help would be greatly appreciated.</p>
<p>Cheers</p>
| [
{
"answer_id": 272241,
"author": "Johansson",
"author_id": 94498,
"author_profile": "https://wordpress.stackexchange.com/users/94498",
"pm_score": 2,
"selected": true,
"text": "<p>There is a built-in function that you can use, instead of globals. The <a href=\"https://codex.wordpress.org/Function_Reference/get_current_screen\" rel=\"nofollow noreferrer\"><code>get_current_screen()</code></a> function allows you to get the information associated with the current page.</p>\n\n<p>One of its return values is <code>post_type</code>. So you can check against an array of post types to see if anyone matches.</p>\n\n<pre><code>function fhaac_admin_enqueue_scripts(){\n $screen = get_current_screen();\n if (\n in_array( $screen->post_type, array('fhaac','blabla')) &&\n $screen->base == 'post'\n ) { // Do something }\n}\n</code></pre>\n"
},
{
"answer_id": 272242,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 0,
"selected": false,
"text": "<p>There's a really simple work around:</p>\n\n<p><strong>Load it everywhere and only run the code if the page matches</strong></p>\n\n<p>For example, on my site I have a CPT named <code>projects</code> and on the body tag I have the following:</p>\n\n<pre><code><body\n class=\"wp-admin wp-core-ui js jetpack-connected edit-php auto-fold admin-bar post-type-project branch-4-8 version-4-8 admin-color-fresh locale-en-us multisite customize-support sticky-menu svg\">\n</code></pre>\n\n<p>So I know that my posts listing will match <code>body.edit-php</code>, and <code>body.post-type-project</code></p>\n\n<p>So for CSS:</p>\n\n<pre><code>body.post-type-project.edit-php .... {\n ....\n}\n</code></pre>\n\n<p>And I can do the same check in javascript be it with jQuery</p>\n"
}
]
| 2017/07/04 | [
"https://wordpress.stackexchange.com/questions/272236",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/58313/"
]
| I am trying to load several scripts and stylesheets into a plugin I am creating. I want to load scripts into multiple CPTs within admin. I have got this far:
```
function fhaac_admin_enqueue_scripts(){
global $pagenow, $typenow;
if ( ($pagenow == 'post.php' || $pagenow == 'post-new.php') && $typenow == 'fhaac' ){}
}
```
The scripts are being loaded into the fhaac, but nothing else. I am not sure how to add multiple CPTs. I tried adding them in an array, but it didn't work.
Help would be greatly appreciated.
Cheers | There is a built-in function that you can use, instead of globals. The [`get_current_screen()`](https://codex.wordpress.org/Function_Reference/get_current_screen) function allows you to get the information associated with the current page.
One of its return values is `post_type`. So you can check against an array of post types to see if anyone matches.
```
function fhaac_admin_enqueue_scripts(){
$screen = get_current_screen();
if (
in_array( $screen->post_type, array('fhaac','blabla')) &&
$screen->base == 'post'
) { // Do something }
}
``` |
272,249 | <p>I honestly did expect to get here...<br />
I tried every tool in the book...<br />
<code>Save changes</code> on the <code>permalinks</code> page...<br />
I installed <code>debug this</code> to see what going on with the <code>query</code>...<br />
I repeated other operations and changes to configurations but of no avail.<br />
I've spent hours reading on <code>.htaccess</code> params as well as <code>nginx</code> server block configurations...nothing worx.<br />
My <code>menu</code> keeps on giving <code>404</code> unless I set <code>permalinks</code> to <code>plain</code>.<br />
I am on <code>linode VPS</code>, <code>ubuntu 14.04</code> + <code>LEMP</code> stack<br />
Here are my <code>.htaccess</code> & my site's configs...</p>
<p><strong>.htaccess</strong></p>
<pre><code># 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
<Files 403.shtml>
order allow,deny
allow from all
</Files>
# Leverage Browser Caching Ninja -- Starts here
<IfModule mod_expires.c>
ExpiresActive On
ExpiresDefault "access plus 1 month"
ExpiresByType image/x-icon "access plus 1 year"
ExpiresByType image/gif "access plus 1 month"
ExpiresByType image/png "access plus 1 month"
ExpiresByType image/jpg "access plus 1 month"
ExpiresByType image/jpeg "access plus 1 month"
ExpiresByType text/css "access 1 month"
ExpiresByType application/javascript "access plus 1 year"
</IfModule>
# Leverage Browser Caching Ninja -- Ends here
# compress text, html, javascript, css, xml:
AddOutputFilterByType DEFLATE text/plain
AddOutputFilterByType DEFLATE text/html
AddOutputFilterByType DEFLATE text/xml
AddOutputFilterByType DEFLATE text/css
AddOutputFilterByType DEFLATE application/xml
AddOutputFilterByType DEFLATE application/xhtml+xml
AddOutputFilterByType DEFLATE application/rss+xml
AddOutputFilterByType DEFLATE application/javascript
AddOutputFilterByType DEFLATE application/x-javascript
</code></pre>
<p><strong>nginx server block</strong></p>
<pre><code>server {
server_name www.xxx.com xxx.com;
root /home/alma/xxx.com;
index index.php;
include global/restrictions.conf;
include global/wordpress_xxx.conf;
error_log /var/log/nginx/xxx_error.log;
access_log /var/log/nginx/xxx_access.log;
}
</code></pre>
<p><strong>global/wordpress_xxx.conf</strong></p>
<pre><code># http://wiki.nginx.org/HttpCoreModule
location / {
#try_files $uri $uri/ /index.php?$args;
try_files $uri $uri/ /index.php?q=$uri&$args;
}
# Add trailing slash to */wp-admin requests.
rewrite /wp-admin$ $scheme://$host$uri/ permanent;
# Directives to send expires headers and turn off 404 error logging.
location ~* ^.+\.(ogg|ogv|svg|svgz|eot|otf|woff|mp4|ttf|rss|atom|jpg|jpeg|gif|png|ico|zip|tgz|gz|rar|bz2|doc|xls|exe|ppt|tar|mid|midi|wav|bmp|rtf)$ {
access_log off; log_not_found off; expires max;
}
# Pass all .php files onto a php-fpm/php-fcgi server.
location ~ [^/]\.php(/|$) {
fastcgi_split_path_info ^(.+?\.php)(/.*)$;
if (!-f $document_root$fastcgi_script_name) {
return 404;
}
fastcgi_pass unix:/var/run/php5-fpm.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
# fastcgi_intercept_errors on;
fastcgi_param PHP_VALUE "upload_max_filesize = 16M \n post_max_size=18M";
client_max_body_size 68M;
include fastcgi_params;
}
location ~ ^/(wp-admin|wp-login\.php) {
auth_basic "Welcome - Admin Restricted Content";
auth_basic_user_file /etc/nginx/.htpasswd;
}
location = /wp-login.php {
deny all;
try_files $uri =404;
fastcgi_split_path_info ^(.+\.php)(/.+)$;
fastcgi_pass unix:/var/run/php5-fpm.sock;
include fastcgi_params;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_param PHP_VALUE "upload_max_filesize = 16M \n post_max_size=18M";
client_max_body_size 68M;
}
</code></pre>
<p><strong>global/restrictions.conf</strong></p>
<pre><code># Global restrictions configuration file.
location = /favicon.ico {
log_not_found off;
access_log off;
}
location = /robots.txt {
allow all;
log_not_found off;
access_log off;
}
location ~ /\. {
deny all;
}
location ~* /(?:uploads|files)/.*\.php$ {
deny all;
}
</code></pre>
<p>These all worked prior to the last <code>update</code>...<br />
Has anyone encountered such an issue?
Does anyone know how to resolve this?
Is there something in my configuration that might be causing the issue after the <code>update</code> to 4.8?<br />
Thanx</p>
<p>P.s. the error logs are not showing anything in particular...</p>
| [
{
"answer_id": 272258,
"author": "Mandu",
"author_id": 74623,
"author_profile": "https://wordpress.stackexchange.com/users/74623",
"pm_score": 0,
"selected": false,
"text": "<p>You might try <code>flush_rewrite_rules( $hard );</code>\nBe sure to remove the function aftewards though. </p>\n\n<p><a href=\"https://codex.wordpress.org/Function_Reference/flush_rewrite_rules\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/flush_rewrite_rules</a></p>\n"
},
{
"answer_id": 291209,
"author": "cody cortez",
"author_id": 132708,
"author_profile": "https://wordpress.stackexchange.com/users/132708",
"pm_score": 1,
"selected": false,
"text": "<p>I've ran into that trouble before with some of my sites when I transferred them to another server.</p>\n\n<p>Here's what I did. edit your <code>apache2.conf</code> at <code>/etc/apache2/</code> folder.</p>\n\n<p>Run the following command:</p>\n\n<pre><code>nano /etc/apache2/apache2.conf\n</code></pre>\n\n<p>Scroll down and look for this section with a comment:</p>\n\n<pre><code># your system is serving content from a sub-directory in /srv you must allow\n# access here, or in any related virtual host.\n</code></pre>\n\n<p>Make sure that this is the one in there:</p>\n\n<pre><code><Directory /var/www/>\n Options Indexes FollowSymLinks\n AllowOverride all\n Require all granted\n</Directory>\n</code></pre>\n\n<p>For short, grant it. For your permalinks not to fail.</p>\n\n<p>-Dave</p>\n"
}
]
| 2017/07/04 | [
"https://wordpress.stackexchange.com/questions/272249",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/52581/"
]
| I honestly did expect to get here...
I tried every tool in the book...
`Save changes` on the `permalinks` page...
I installed `debug this` to see what going on with the `query`...
I repeated other operations and changes to configurations but of no avail.
I've spent hours reading on `.htaccess` params as well as `nginx` server block configurations...nothing worx.
My `menu` keeps on giving `404` unless I set `permalinks` to `plain`.
I am on `linode VPS`, `ubuntu 14.04` + `LEMP` stack
Here are my `.htaccess` & my site's configs...
**.htaccess**
```
# 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
<Files 403.shtml>
order allow,deny
allow from all
</Files>
# Leverage Browser Caching Ninja -- Starts here
<IfModule mod_expires.c>
ExpiresActive On
ExpiresDefault "access plus 1 month"
ExpiresByType image/x-icon "access plus 1 year"
ExpiresByType image/gif "access plus 1 month"
ExpiresByType image/png "access plus 1 month"
ExpiresByType image/jpg "access plus 1 month"
ExpiresByType image/jpeg "access plus 1 month"
ExpiresByType text/css "access 1 month"
ExpiresByType application/javascript "access plus 1 year"
</IfModule>
# Leverage Browser Caching Ninja -- Ends here
# compress text, html, javascript, css, xml:
AddOutputFilterByType DEFLATE text/plain
AddOutputFilterByType DEFLATE text/html
AddOutputFilterByType DEFLATE text/xml
AddOutputFilterByType DEFLATE text/css
AddOutputFilterByType DEFLATE application/xml
AddOutputFilterByType DEFLATE application/xhtml+xml
AddOutputFilterByType DEFLATE application/rss+xml
AddOutputFilterByType DEFLATE application/javascript
AddOutputFilterByType DEFLATE application/x-javascript
```
**nginx server block**
```
server {
server_name www.xxx.com xxx.com;
root /home/alma/xxx.com;
index index.php;
include global/restrictions.conf;
include global/wordpress_xxx.conf;
error_log /var/log/nginx/xxx_error.log;
access_log /var/log/nginx/xxx_access.log;
}
```
**global/wordpress\_xxx.conf**
```
# http://wiki.nginx.org/HttpCoreModule
location / {
#try_files $uri $uri/ /index.php?$args;
try_files $uri $uri/ /index.php?q=$uri&$args;
}
# Add trailing slash to */wp-admin requests.
rewrite /wp-admin$ $scheme://$host$uri/ permanent;
# Directives to send expires headers and turn off 404 error logging.
location ~* ^.+\.(ogg|ogv|svg|svgz|eot|otf|woff|mp4|ttf|rss|atom|jpg|jpeg|gif|png|ico|zip|tgz|gz|rar|bz2|doc|xls|exe|ppt|tar|mid|midi|wav|bmp|rtf)$ {
access_log off; log_not_found off; expires max;
}
# Pass all .php files onto a php-fpm/php-fcgi server.
location ~ [^/]\.php(/|$) {
fastcgi_split_path_info ^(.+?\.php)(/.*)$;
if (!-f $document_root$fastcgi_script_name) {
return 404;
}
fastcgi_pass unix:/var/run/php5-fpm.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
# fastcgi_intercept_errors on;
fastcgi_param PHP_VALUE "upload_max_filesize = 16M \n post_max_size=18M";
client_max_body_size 68M;
include fastcgi_params;
}
location ~ ^/(wp-admin|wp-login\.php) {
auth_basic "Welcome - Admin Restricted Content";
auth_basic_user_file /etc/nginx/.htpasswd;
}
location = /wp-login.php {
deny all;
try_files $uri =404;
fastcgi_split_path_info ^(.+\.php)(/.+)$;
fastcgi_pass unix:/var/run/php5-fpm.sock;
include fastcgi_params;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_param PHP_VALUE "upload_max_filesize = 16M \n post_max_size=18M";
client_max_body_size 68M;
}
```
**global/restrictions.conf**
```
# Global restrictions configuration file.
location = /favicon.ico {
log_not_found off;
access_log off;
}
location = /robots.txt {
allow all;
log_not_found off;
access_log off;
}
location ~ /\. {
deny all;
}
location ~* /(?:uploads|files)/.*\.php$ {
deny all;
}
```
These all worked prior to the last `update`...
Has anyone encountered such an issue?
Does anyone know how to resolve this?
Is there something in my configuration that might be causing the issue after the `update` to 4.8?
Thanx
P.s. the error logs are not showing anything in particular... | I've ran into that trouble before with some of my sites when I transferred them to another server.
Here's what I did. edit your `apache2.conf` at `/etc/apache2/` folder.
Run the following command:
```
nano /etc/apache2/apache2.conf
```
Scroll down and look for this section with a comment:
```
# your system is serving content from a sub-directory in /srv you must allow
# access here, or in any related virtual host.
```
Make sure that this is the one in there:
```
<Directory /var/www/>
Options Indexes FollowSymLinks
AllowOverride all
Require all granted
</Directory>
```
For short, grant it. For your permalinks not to fail.
-Dave |
272,261 | <p>Quite difficult to explain this one but I will do my best.</p>
<p>Let's assume we have the theme <strong>T</strong> and plugin <strong>P</strong>.</p>
<p><strong>T</strong> has a bunch of custom taxonomies and so does <strong>P</strong>, the plugin.</p>
<p>What I am trying to achieve is display content from the custom taxonomies in <strong>P</strong> in the <strong>T</strong> template/single files, without modifying any of the files in <strong>T</strong>. Basically, I want to "hijack" the single views from the theme by writing the code in <strong>P</strong>. Is that achievable? And if so, how?</p>
<p>I just couldn't find a better word than "hijack". It's just adding different sections in the single view, based on the content that is saved in the custom taxonomies in the plugin.</p>
<p>Thank you in advance!</p>
| [
{
"answer_id": 272258,
"author": "Mandu",
"author_id": 74623,
"author_profile": "https://wordpress.stackexchange.com/users/74623",
"pm_score": 0,
"selected": false,
"text": "<p>You might try <code>flush_rewrite_rules( $hard );</code>\nBe sure to remove the function aftewards though. </p>\n\n<p><a href=\"https://codex.wordpress.org/Function_Reference/flush_rewrite_rules\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/flush_rewrite_rules</a></p>\n"
},
{
"answer_id": 291209,
"author": "cody cortez",
"author_id": 132708,
"author_profile": "https://wordpress.stackexchange.com/users/132708",
"pm_score": 1,
"selected": false,
"text": "<p>I've ran into that trouble before with some of my sites when I transferred them to another server.</p>\n\n<p>Here's what I did. edit your <code>apache2.conf</code> at <code>/etc/apache2/</code> folder.</p>\n\n<p>Run the following command:</p>\n\n<pre><code>nano /etc/apache2/apache2.conf\n</code></pre>\n\n<p>Scroll down and look for this section with a comment:</p>\n\n<pre><code># your system is serving content from a sub-directory in /srv you must allow\n# access here, or in any related virtual host.\n</code></pre>\n\n<p>Make sure that this is the one in there:</p>\n\n<pre><code><Directory /var/www/>\n Options Indexes FollowSymLinks\n AllowOverride all\n Require all granted\n</Directory>\n</code></pre>\n\n<p>For short, grant it. For your permalinks not to fail.</p>\n\n<p>-Dave</p>\n"
}
]
| 2017/07/04 | [
"https://wordpress.stackexchange.com/questions/272261",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/123147/"
]
| Quite difficult to explain this one but I will do my best.
Let's assume we have the theme **T** and plugin **P**.
**T** has a bunch of custom taxonomies and so does **P**, the plugin.
What I am trying to achieve is display content from the custom taxonomies in **P** in the **T** template/single files, without modifying any of the files in **T**. Basically, I want to "hijack" the single views from the theme by writing the code in **P**. Is that achievable? And if so, how?
I just couldn't find a better word than "hijack". It's just adding different sections in the single view, based on the content that is saved in the custom taxonomies in the plugin.
Thank you in advance! | I've ran into that trouble before with some of my sites when I transferred them to another server.
Here's what I did. edit your `apache2.conf` at `/etc/apache2/` folder.
Run the following command:
```
nano /etc/apache2/apache2.conf
```
Scroll down and look for this section with a comment:
```
# your system is serving content from a sub-directory in /srv you must allow
# access here, or in any related virtual host.
```
Make sure that this is the one in there:
```
<Directory /var/www/>
Options Indexes FollowSymLinks
AllowOverride all
Require all granted
</Directory>
```
For short, grant it. For your permalinks not to fail.
-Dave |
272,276 | <p>I have created a custom map view page on my classified ads website and I seem to be having issues with the page loading, here is the code for the page.</p>
<pre><code> <?php
$featured_query = '';
if(!empty($stm_listing_filter['featured'])) {
$featured_query = $stm_listing_filter['featured'];
}
$listing = $stm_listing_filter['listing_query'];
$filter_badges = $stm_listing_filter['badges'];
$filter_links = stm_get_car_filter_links();
$listing_filter_position = get_theme_mod('listing_filter_position', 'left');
if(!empty($_GET['filter_position']) and $_GET['filter_position'] == 'right') {
$listing_filter_position = 'right';
}
$regular_price_label = get_post_meta(get_the_ID(), 'regular_price_label', true);
$special_price_label = get_post_meta(get_the_ID(),'special_price_label',true);
$price = get_post_meta(get_the_id(),'price',true);
$sale_price = get_post_meta(get_the_id(),'sale_price',true);
$car_price_form_label = get_post_meta(get_the_ID(), 'car_price_form_label', true);
$data_price = '0';
if(!empty($price)) {
$data_price = $price;
}
if(!empty($sale_price)) {
$data_price = $sale_price;
}
if(empty($price) and !empty($sale_price)) {
$price = $sale_price;
}
$mileage = get_post_meta(get_the_id(),'mileage',true);
$data_mileage = '0';
if(!empty($mileage)) {
$data_mileage = $mileage;
}
$taxonomies = stm_get_taxonomies();
$categories = wp_get_post_terms(get_the_ID(), $taxonomies);
$classes = array();
if(!empty($categories)) {
foreach($categories as $category) {
$classes[] = $category->slug.'-'.$category->term_id;
}
}
//Fav
$cars_in_favourite = array();
if(!empty($_COOKIE['stm_car_favourites'])) {
$cars_in_favourite = $_COOKIE['stm_car_favourites'];
$cars_in_favourite = explode(',', $cars_in_favourite);
}
if(is_user_logged_in()) {
$user = wp_get_current_user();
$user_id = $user->ID;
$user_added_fav = get_the_author_meta('stm_user_favourites', $user_id );
if(!empty($user_added_fav)) {
$user_added_fav = explode(',', $user_added_fav);
$cars_in_favourite = $user_added_fav;
}
}
$car_already_added_to_favourite = '';
$car_favourite_status = esc_html__('Add to favorites', 'motors');
if(!empty($cars_in_favourite) and in_array(get_the_ID(), $cars_in_favourite)){
$car_already_added_to_favourite = 'active';
$car_favourite_status = esc_html__('Remove from favorites', 'motors');
}
$show_favorite = get_theme_mod('enable_favorite_items', true);
//Compare
$show_compare = get_theme_mod('show_listing_compare', true);
$cars_in_compare = array();
if(!empty($_COOKIE['compare_ids'])) {
$cars_in_compare = $_COOKIE['compare_ids'];
}
$car_already_added_to_compare = '';
$car_compare_status = esc_html__('Add to compare', 'motors');
if(!empty($cars_in_compare) and in_array(get_the_ID(), $cars_in_compare)){
$car_already_added_to_compare = 'active';
$car_compare_status = esc_html__('Remove from compare', 'motors');
}
/*Media*/
$car_media = stm_get_car_medias(get_the_id());
?>
<div class="stm-isotope-sorting" style="display: none;">
<?php while($listing->have_posts()):
get_template_part( 'partials/listing-cars/listing-list', 'loop' );
endwhile; ?>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/markerclusterer.js"></script>
<script>
$(document).ready(function() {
var markersInfo = $('.ia-card').map(function() {
var info = {
id: $(this).data('map-id'),
address: $(this).data('map-address'),
title: $(this).data('map-title'),
price: $(this).data('map-price'),
latitude: $(this).data('map-latitude'),
longitude: $(this).data('map-longitude'),
html: "<img src=" + $(this).data('map-image') + ">",
link: $(this).data("map-link"),
contentHtml: "<div class='image'>" + "<img src=" + $(this).data('map-image') + ">" + "</div>" + '<b>' + $(this).data('map-title') + '</b><br>' + "<div class='changeprice'><div style='display: none;' class='currency-selector'></div>" + $(this).data('map-price') + "</div>" + "<br><a href='" + $(this).data("map-link") + "'>More>></a>"
};
return info;
}).get();
var distinctMarkerInfo = [];
markersInfo.forEach(function(item) {
if (!distinctMarkerInfo.some(function(distinct) {
return distinct.id == item.id;
})) distinctMarkerInfo.push(item);
});
initGoogleMap(distinctMarkerInfo);
// GMAP ON SEARCH RESULTS PAGE
function initGoogleMap(markersInfo) {
var mapOptions = {
// zoom: 2,
// center: new google.maps.LatLng(53.334430, -7.736673) // center of Ireland
},
bounds = new google.maps.LatLngBounds(),
mapElement = document.getElementById('stm_map_results'),
map = new google.maps.Map(mapElement, mapOptions);
markerList = []; // create an array to hold the markers
var geocoder = new google.maps.Geocoder();
var iconBase = 'http://throttlebuddies.com/wp-content/themes/motors/assets/images/';
$.each(markersInfo, function(key, val) {
var marker = new google.maps.Marker({
//map: map,
position: {lat: parseFloat(val.latitude), lng: parseFloat(val.longitude)},
title: val.title,
icon: iconBase + 'single.png',
info: new google.maps.InfoWindow({
content: val.contentHtml
})
});
markerList.push(marker); // add the marker to the list
google.maps.event.addListener(marker, 'click', function() {
marker.info.open(map, marker);
});
loc = new google.maps.LatLng(val.latitude, val.longitude);
bounds.extend(loc);
});
map.fitBounds(bounds);
map.panToBounds(bounds);
var markerCluster = new MarkerClusterer(map, markerList, {
imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'
});
};
});
</script>
<div id="stm_map_results" style="width:100%; height:600px;"></div>
<style>
.stm-isotope-sorting {
position: relative;
height: 600px !important;
}
</style>
</code></pre>
<p>The page loads fine however when I get rid of the following code. But I need this code to populate the map.</p>
<pre><code> <div class="stm-isotope-sorting" style="display: none;">
<?php while($listing->have_posts()):
get_template_part( 'partials/listing-cars/listing-list', 'loop' );
endwhile; ?>
</div>
</code></pre>
| [
{
"answer_id": 272277,
"author": "Milo",
"author_id": 4771,
"author_profile": "https://wordpress.stackexchange.com/users/4771",
"pm_score": 1,
"selected": false,
"text": "<p>This loop:</p>\n\n<pre><code>while($listing->have_posts()):\n get_template_part( 'partials/listing-cars/listing-list', 'loop' );\nendwhile;\n</code></pre>\n\n<p>will never terminate, because <code>$listing->have_posts()</code> will never be false. You need <code>$listing->the_post()</code> to advance the loop to the next post in each iteration. Then, when the last post is reached, <code>$listing->have_posts()</code> will be false and the loop will end.</p>\n\n<pre><code>while($listing->have_posts()):\n $listing->the_post();\n get_template_part( 'partials/listing-cars/listing-list', 'loop' );\nendwhile;\n</code></pre>\n"
},
{
"answer_id": 272284,
"author": "Roger Alridge",
"author_id": 123084,
"author_profile": "https://wordpress.stackexchange.com/users/123084",
"pm_score": 0,
"selected": false,
"text": "<p>I got it to work by removing the while and endwhile from the code and just used the template part.</p>\n\n<p>From -></p>\n\n<pre><code>while($listing->have_posts()):\n$listing->the_post();\nget_template_part( 'partials/listing-cars/listing-list', 'loop' );\nendwhile;\n</code></pre>\n\n<p>To -></p>\n\n<pre><code>get_template_part( 'partials/listing-cars/listing-list', 'loop' );\n</code></pre>\n"
}
]
| 2017/07/04 | [
"https://wordpress.stackexchange.com/questions/272276",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/123084/"
]
| I have created a custom map view page on my classified ads website and I seem to be having issues with the page loading, here is the code for the page.
```
<?php
$featured_query = '';
if(!empty($stm_listing_filter['featured'])) {
$featured_query = $stm_listing_filter['featured'];
}
$listing = $stm_listing_filter['listing_query'];
$filter_badges = $stm_listing_filter['badges'];
$filter_links = stm_get_car_filter_links();
$listing_filter_position = get_theme_mod('listing_filter_position', 'left');
if(!empty($_GET['filter_position']) and $_GET['filter_position'] == 'right') {
$listing_filter_position = 'right';
}
$regular_price_label = get_post_meta(get_the_ID(), 'regular_price_label', true);
$special_price_label = get_post_meta(get_the_ID(),'special_price_label',true);
$price = get_post_meta(get_the_id(),'price',true);
$sale_price = get_post_meta(get_the_id(),'sale_price',true);
$car_price_form_label = get_post_meta(get_the_ID(), 'car_price_form_label', true);
$data_price = '0';
if(!empty($price)) {
$data_price = $price;
}
if(!empty($sale_price)) {
$data_price = $sale_price;
}
if(empty($price) and !empty($sale_price)) {
$price = $sale_price;
}
$mileage = get_post_meta(get_the_id(),'mileage',true);
$data_mileage = '0';
if(!empty($mileage)) {
$data_mileage = $mileage;
}
$taxonomies = stm_get_taxonomies();
$categories = wp_get_post_terms(get_the_ID(), $taxonomies);
$classes = array();
if(!empty($categories)) {
foreach($categories as $category) {
$classes[] = $category->slug.'-'.$category->term_id;
}
}
//Fav
$cars_in_favourite = array();
if(!empty($_COOKIE['stm_car_favourites'])) {
$cars_in_favourite = $_COOKIE['stm_car_favourites'];
$cars_in_favourite = explode(',', $cars_in_favourite);
}
if(is_user_logged_in()) {
$user = wp_get_current_user();
$user_id = $user->ID;
$user_added_fav = get_the_author_meta('stm_user_favourites', $user_id );
if(!empty($user_added_fav)) {
$user_added_fav = explode(',', $user_added_fav);
$cars_in_favourite = $user_added_fav;
}
}
$car_already_added_to_favourite = '';
$car_favourite_status = esc_html__('Add to favorites', 'motors');
if(!empty($cars_in_favourite) and in_array(get_the_ID(), $cars_in_favourite)){
$car_already_added_to_favourite = 'active';
$car_favourite_status = esc_html__('Remove from favorites', 'motors');
}
$show_favorite = get_theme_mod('enable_favorite_items', true);
//Compare
$show_compare = get_theme_mod('show_listing_compare', true);
$cars_in_compare = array();
if(!empty($_COOKIE['compare_ids'])) {
$cars_in_compare = $_COOKIE['compare_ids'];
}
$car_already_added_to_compare = '';
$car_compare_status = esc_html__('Add to compare', 'motors');
if(!empty($cars_in_compare) and in_array(get_the_ID(), $cars_in_compare)){
$car_already_added_to_compare = 'active';
$car_compare_status = esc_html__('Remove from compare', 'motors');
}
/*Media*/
$car_media = stm_get_car_medias(get_the_id());
?>
<div class="stm-isotope-sorting" style="display: none;">
<?php while($listing->have_posts()):
get_template_part( 'partials/listing-cars/listing-list', 'loop' );
endwhile; ?>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/markerclusterer.js"></script>
<script>
$(document).ready(function() {
var markersInfo = $('.ia-card').map(function() {
var info = {
id: $(this).data('map-id'),
address: $(this).data('map-address'),
title: $(this).data('map-title'),
price: $(this).data('map-price'),
latitude: $(this).data('map-latitude'),
longitude: $(this).data('map-longitude'),
html: "<img src=" + $(this).data('map-image') + ">",
link: $(this).data("map-link"),
contentHtml: "<div class='image'>" + "<img src=" + $(this).data('map-image') + ">" + "</div>" + '<b>' + $(this).data('map-title') + '</b><br>' + "<div class='changeprice'><div style='display: none;' class='currency-selector'></div>" + $(this).data('map-price') + "</div>" + "<br><a href='" + $(this).data("map-link") + "'>More>></a>"
};
return info;
}).get();
var distinctMarkerInfo = [];
markersInfo.forEach(function(item) {
if (!distinctMarkerInfo.some(function(distinct) {
return distinct.id == item.id;
})) distinctMarkerInfo.push(item);
});
initGoogleMap(distinctMarkerInfo);
// GMAP ON SEARCH RESULTS PAGE
function initGoogleMap(markersInfo) {
var mapOptions = {
// zoom: 2,
// center: new google.maps.LatLng(53.334430, -7.736673) // center of Ireland
},
bounds = new google.maps.LatLngBounds(),
mapElement = document.getElementById('stm_map_results'),
map = new google.maps.Map(mapElement, mapOptions);
markerList = []; // create an array to hold the markers
var geocoder = new google.maps.Geocoder();
var iconBase = 'http://throttlebuddies.com/wp-content/themes/motors/assets/images/';
$.each(markersInfo, function(key, val) {
var marker = new google.maps.Marker({
//map: map,
position: {lat: parseFloat(val.latitude), lng: parseFloat(val.longitude)},
title: val.title,
icon: iconBase + 'single.png',
info: new google.maps.InfoWindow({
content: val.contentHtml
})
});
markerList.push(marker); // add the marker to the list
google.maps.event.addListener(marker, 'click', function() {
marker.info.open(map, marker);
});
loc = new google.maps.LatLng(val.latitude, val.longitude);
bounds.extend(loc);
});
map.fitBounds(bounds);
map.panToBounds(bounds);
var markerCluster = new MarkerClusterer(map, markerList, {
imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'
});
};
});
</script>
<div id="stm_map_results" style="width:100%; height:600px;"></div>
<style>
.stm-isotope-sorting {
position: relative;
height: 600px !important;
}
</style>
```
The page loads fine however when I get rid of the following code. But I need this code to populate the map.
```
<div class="stm-isotope-sorting" style="display: none;">
<?php while($listing->have_posts()):
get_template_part( 'partials/listing-cars/listing-list', 'loop' );
endwhile; ?>
</div>
``` | This loop:
```
while($listing->have_posts()):
get_template_part( 'partials/listing-cars/listing-list', 'loop' );
endwhile;
```
will never terminate, because `$listing->have_posts()` will never be false. You need `$listing->the_post()` to advance the loop to the next post in each iteration. Then, when the last post is reached, `$listing->have_posts()` will be false and the loop will end.
```
while($listing->have_posts()):
$listing->the_post();
get_template_part( 'partials/listing-cars/listing-list', 'loop' );
endwhile;
``` |
272,291 | <p>I developed a site in WordPress where you can click on the featured image and title of the featured image and it should take you to the corresponding page same as if you would click on the nav item:</p>
<p><a href="https://i.stack.imgur.com/VwD9y.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/VwD9y.jpg" alt="enter image description here"></a></p>
<p>This was done using Custom Post Type UI that I called Quick Links:</p>
<p><a href="https://i.stack.imgur.com/O9fZw.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/O9fZw.png" alt="enter image description here"></a></p>
<p>I think I may have made this more complex than it needs to be though because when you click on one of the images or title the permalink takes you to yousite.com/quick-links/news instead of just yoursite.com/news</p>
<p>I am not sure if I should just gut the Custom Post Type UI, the source code for this page is this one at home-page.php:</p>
<pre><code><?php
/*
Template Name: Home Page
*/
// Advanced Custom Fields
$quick_links_title = get_field('quick_links_title');
get_header(); ?>
<?php get_template_part('content','hero'); ?>
<?php get_template_part('content','donate'); ?>
<div class="container-fluid">
<div class="row">
<div class="col-md-8">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">Welcome to Three Green Birds!</h3>
</div><!-- panel-heading -->
<div class="panel-body">
<?php if (have_posts()) : ?>
<?php while (have_posts()) : the_post(); ?>
<!--<div class="spacer"></div>-->
<div class="post-title">
<?php if (function_exists('get_cat_icon')) get_cat_icon('class=myicons'); ?><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></div>
<div class="spacer"></div>
<div class="post-content">
<?php the_content('Read the rest of this entry &raquo;'); ?>
</div>
<div class="spacer"></div>
<div class="post-footer"></div>
<?php endwhile; ?>
<div class="navigation">
<br/><br/>
<div class="alignleft"><?php next_posts_link('&laquo; Older Entries') ?></div>
<div class="alignright"><?php previous_posts_link('Newer Entries &raquo;') ?></div>
</div>
<?php else : ?>
<div class="post-title">Not Found</div>
<p class="post-content">Sorry, but you are looking for something that isn't here.</p>
<?php include (TEMPLATEPATH . "/searchform.php"); ?>
<?php endif; ?>
<!-- Quick Links
======================================================== -->
<section id="quick-links">
<div class="container">
<h2><?php echo $quick_links_title; ?></h2>
<div class="row">
<?php $loop = new WP_Query(array('post_type' => 'quick_links', 'orderby' => 'post_id', 'order' => 'ASC')); ?>
<?php while($loop->have_posts()) : $loop->the_post(); ?>
<div class="col-sm-3">
<a href="<?php echo the_permalink(); ?>"><?php
if(has_post_thumbnail()) {
the_post_thumbnail();
}
?></a>
<a href="<?php echo the_permalink(); ?>"><h3><?php the_title(); ?></h3></a>
<p><?php the_content(); ?></p>
</div><!-- end col -->
<?php endwhile; ?><!-- end of the loop -->
<?php wp_reset_postdata(); ?>
</div><!-- row -->
</div><!-- container -->
</section><!-- quick-links -->
</div><!-- panel-body -->
</div><!-- panel panel-default -->
</div><!-- col-md-8 -->
<!-- SIDEBAR
====================================================================== -->
<div class="col-md-4">
<?php if (is_active_sidebar('sidebar')) : ?>
<?php dynamic_sidebar('sidebar'); ?>
<?php endif; ?>
</div><!-- col-md-4 -->
</div><!-- row -->
</div><!-- container-fluid -->
<?php get_sidebar(); ?>
<?php get_footer(); ?>
</code></pre>
<p>If I were to gut the Custom Post Type UI, could I still use the code above to get the browser to render what you see above, the quick-links title notwithstanding since that is a variable so I am not sure that would appear if I am no longer using the Quick Links Custom Post Type.</p>
<p>So to be clear I just want the user to click on the News image or text and have the user be taken to mysite.com/news and not mysite.com/quick-links/news.</p>
<p>I believe the problem is here:</p>
<pre><code><?php $loop = new WP_Query(array('post_type' => 'quick_links', 'orderby' => 'post_id', 'order' => 'ASC')); ?>
</code></pre>
<p>I get mysite.com/quick-links/news when I hover over the featured images and title of the featured image, but I just want it to go to mysite.com/news as if I were clicking on the news item in the nav menu. So what I did was edit the $loop I am using so that the site no longer displays mysite.com/quick-links/news but just mysite.com/news. I changed the $loop from:</p>
<pre><code><?php $loop = new WP_Query(array('post_type' => 'quick_links', 'orderby' => 'post_id', 'order' => 'ASC')); ?>
</code></pre>
<p>to</p>
<pre><code><?php $loop = new WP_Query(array('post_type' => 'page', 'orderby' => 'post_id', 'order' => 'ASC')); ?>
</code></pre>
<p>but now the Quick Links section of the home page wants to display all the pages and not just news, about us and get involved. Any ideas on how to query only those three specific pages?</p>
| [
{
"answer_id": 272303,
"author": "Regolith",
"author_id": 103884,
"author_profile": "https://wordpress.stackexchange.com/users/103884",
"pm_score": 0,
"selected": false,
"text": "<p>first off you are using <code>echo the_permalink()</code></p>\n\n<pre><code><a href=\"<?php echo the_permalink(); ?>\"><?php \n if(has_post_thumbnail()) {\n the_post_thumbnail();\n }\n?></a>\n</code></pre>\n\n<p>you don't have to echo out permalink</p>\n\n<pre><code><a href=\"<?php the_permalink(); ?>\"><?php \n if(has_post_thumbnail()) {\n the_post_thumbnail();\n }\n?></a>\n</code></pre>\n\n<p>carefully read the <code>https://codex.wordpress.org/Using_Permalinks</code> codex part in wordpress site</p>\n\n<p>Also if you are using multiple loops in the page use <code>wp_reset_query();</code> after or before the loop. And be sure to review your query arguments. For example:<br>\nwhere is the query for contents after <code><h3 class=\"panel-title\">Welcome to Three Green Birds!</h3></code>.\n<br>\ntake reference for wp queries from <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query\" rel=\"nofollow noreferrer\">WP_Query</a> and <a href=\"https://developer.wordpress.org/reference/functions/query_posts/\" rel=\"nofollow noreferrer\">query_posts</a></p>\n"
},
{
"answer_id": 272437,
"author": "Daniel",
"author_id": 109760,
"author_profile": "https://wordpress.stackexchange.com/users/109760",
"pm_score": 2,
"selected": true,
"text": "<p>I learned that in the WP Query I had to specify page instead of quick_links which was the custom post type. In fact I completely removed the Custom Post Type UI and the plugin. It was all completely unnecessary.</p>\n\n<p>I did not want every single page, just the news, about us and get involved so I researched if there was a way to grab specific pages, namely, those with a featured image and in the correct order and from what I found online I was able to piece together this code:</p>\n\n<pre><code><?php $loop = new WP_Query(array('post_type' => 'page', 'meta_key' => '_thumbnail_id', 'order' => 'asc')); ?>\n</code></pre>\n\n<p>and it works:</p>\n\n<p><a href=\"https://i.stack.imgur.com/GRnnI.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/GRnnI.jpg\" alt=\"enter image description here\"></a></p>\n"
}
]
| 2017/07/04 | [
"https://wordpress.stackexchange.com/questions/272291",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/109760/"
]
| I developed a site in WordPress where you can click on the featured image and title of the featured image and it should take you to the corresponding page same as if you would click on the nav item:
[](https://i.stack.imgur.com/VwD9y.jpg)
This was done using Custom Post Type UI that I called Quick Links:
[](https://i.stack.imgur.com/O9fZw.png)
I think I may have made this more complex than it needs to be though because when you click on one of the images or title the permalink takes you to yousite.com/quick-links/news instead of just yoursite.com/news
I am not sure if I should just gut the Custom Post Type UI, the source code for this page is this one at home-page.php:
```
<?php
/*
Template Name: Home Page
*/
// Advanced Custom Fields
$quick_links_title = get_field('quick_links_title');
get_header(); ?>
<?php get_template_part('content','hero'); ?>
<?php get_template_part('content','donate'); ?>
<div class="container-fluid">
<div class="row">
<div class="col-md-8">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">Welcome to Three Green Birds!</h3>
</div><!-- panel-heading -->
<div class="panel-body">
<?php if (have_posts()) : ?>
<?php while (have_posts()) : the_post(); ?>
<!--<div class="spacer"></div>-->
<div class="post-title">
<?php if (function_exists('get_cat_icon')) get_cat_icon('class=myicons'); ?><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></div>
<div class="spacer"></div>
<div class="post-content">
<?php the_content('Read the rest of this entry »'); ?>
</div>
<div class="spacer"></div>
<div class="post-footer"></div>
<?php endwhile; ?>
<div class="navigation">
<br/><br/>
<div class="alignleft"><?php next_posts_link('« Older Entries') ?></div>
<div class="alignright"><?php previous_posts_link('Newer Entries »') ?></div>
</div>
<?php else : ?>
<div class="post-title">Not Found</div>
<p class="post-content">Sorry, but you are looking for something that isn't here.</p>
<?php include (TEMPLATEPATH . "/searchform.php"); ?>
<?php endif; ?>
<!-- Quick Links
======================================================== -->
<section id="quick-links">
<div class="container">
<h2><?php echo $quick_links_title; ?></h2>
<div class="row">
<?php $loop = new WP_Query(array('post_type' => 'quick_links', 'orderby' => 'post_id', 'order' => 'ASC')); ?>
<?php while($loop->have_posts()) : $loop->the_post(); ?>
<div class="col-sm-3">
<a href="<?php echo the_permalink(); ?>"><?php
if(has_post_thumbnail()) {
the_post_thumbnail();
}
?></a>
<a href="<?php echo the_permalink(); ?>"><h3><?php the_title(); ?></h3></a>
<p><?php the_content(); ?></p>
</div><!-- end col -->
<?php endwhile; ?><!-- end of the loop -->
<?php wp_reset_postdata(); ?>
</div><!-- row -->
</div><!-- container -->
</section><!-- quick-links -->
</div><!-- panel-body -->
</div><!-- panel panel-default -->
</div><!-- col-md-8 -->
<!-- SIDEBAR
====================================================================== -->
<div class="col-md-4">
<?php if (is_active_sidebar('sidebar')) : ?>
<?php dynamic_sidebar('sidebar'); ?>
<?php endif; ?>
</div><!-- col-md-4 -->
</div><!-- row -->
</div><!-- container-fluid -->
<?php get_sidebar(); ?>
<?php get_footer(); ?>
```
If I were to gut the Custom Post Type UI, could I still use the code above to get the browser to render what you see above, the quick-links title notwithstanding since that is a variable so I am not sure that would appear if I am no longer using the Quick Links Custom Post Type.
So to be clear I just want the user to click on the News image or text and have the user be taken to mysite.com/news and not mysite.com/quick-links/news.
I believe the problem is here:
```
<?php $loop = new WP_Query(array('post_type' => 'quick_links', 'orderby' => 'post_id', 'order' => 'ASC')); ?>
```
I get mysite.com/quick-links/news when I hover over the featured images and title of the featured image, but I just want it to go to mysite.com/news as if I were clicking on the news item in the nav menu. So what I did was edit the $loop I am using so that the site no longer displays mysite.com/quick-links/news but just mysite.com/news. I changed the $loop from:
```
<?php $loop = new WP_Query(array('post_type' => 'quick_links', 'orderby' => 'post_id', 'order' => 'ASC')); ?>
```
to
```
<?php $loop = new WP_Query(array('post_type' => 'page', 'orderby' => 'post_id', 'order' => 'ASC')); ?>
```
but now the Quick Links section of the home page wants to display all the pages and not just news, about us and get involved. Any ideas on how to query only those three specific pages? | I learned that in the WP Query I had to specify page instead of quick\_links which was the custom post type. In fact I completely removed the Custom Post Type UI and the plugin. It was all completely unnecessary.
I did not want every single page, just the news, about us and get involved so I researched if there was a way to grab specific pages, namely, those with a featured image and in the correct order and from what I found online I was able to piece together this code:
```
<?php $loop = new WP_Query(array('post_type' => 'page', 'meta_key' => '_thumbnail_id', 'order' => 'asc')); ?>
```
and it works:
[](https://i.stack.imgur.com/GRnnI.jpg) |
272,324 | <p>I accidentally deleted about 20 blog posts and they were in my trash folder for over a month and now have permanently deleted. I was wondering if there's a way to recover these? For example I have seen mention of MySql database and phpMyAdmin, and was wondering if these would be applicable in my case and, if so, how do I use them?
Thanks in advance!</p>
| [
{
"answer_id": 272303,
"author": "Regolith",
"author_id": 103884,
"author_profile": "https://wordpress.stackexchange.com/users/103884",
"pm_score": 0,
"selected": false,
"text": "<p>first off you are using <code>echo the_permalink()</code></p>\n\n<pre><code><a href=\"<?php echo the_permalink(); ?>\"><?php \n if(has_post_thumbnail()) {\n the_post_thumbnail();\n }\n?></a>\n</code></pre>\n\n<p>you don't have to echo out permalink</p>\n\n<pre><code><a href=\"<?php the_permalink(); ?>\"><?php \n if(has_post_thumbnail()) {\n the_post_thumbnail();\n }\n?></a>\n</code></pre>\n\n<p>carefully read the <code>https://codex.wordpress.org/Using_Permalinks</code> codex part in wordpress site</p>\n\n<p>Also if you are using multiple loops in the page use <code>wp_reset_query();</code> after or before the loop. And be sure to review your query arguments. For example:<br>\nwhere is the query for contents after <code><h3 class=\"panel-title\">Welcome to Three Green Birds!</h3></code>.\n<br>\ntake reference for wp queries from <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query\" rel=\"nofollow noreferrer\">WP_Query</a> and <a href=\"https://developer.wordpress.org/reference/functions/query_posts/\" rel=\"nofollow noreferrer\">query_posts</a></p>\n"
},
{
"answer_id": 272437,
"author": "Daniel",
"author_id": 109760,
"author_profile": "https://wordpress.stackexchange.com/users/109760",
"pm_score": 2,
"selected": true,
"text": "<p>I learned that in the WP Query I had to specify page instead of quick_links which was the custom post type. In fact I completely removed the Custom Post Type UI and the plugin. It was all completely unnecessary.</p>\n\n<p>I did not want every single page, just the news, about us and get involved so I researched if there was a way to grab specific pages, namely, those with a featured image and in the correct order and from what I found online I was able to piece together this code:</p>\n\n<pre><code><?php $loop = new WP_Query(array('post_type' => 'page', 'meta_key' => '_thumbnail_id', 'order' => 'asc')); ?>\n</code></pre>\n\n<p>and it works:</p>\n\n<p><a href=\"https://i.stack.imgur.com/GRnnI.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/GRnnI.jpg\" alt=\"enter image description here\"></a></p>\n"
}
]
| 2017/07/05 | [
"https://wordpress.stackexchange.com/questions/272324",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/123197/"
]
| I accidentally deleted about 20 blog posts and they were in my trash folder for over a month and now have permanently deleted. I was wondering if there's a way to recover these? For example I have seen mention of MySql database and phpMyAdmin, and was wondering if these would be applicable in my case and, if so, how do I use them?
Thanks in advance! | I learned that in the WP Query I had to specify page instead of quick\_links which was the custom post type. In fact I completely removed the Custom Post Type UI and the plugin. It was all completely unnecessary.
I did not want every single page, just the news, about us and get involved so I researched if there was a way to grab specific pages, namely, those with a featured image and in the correct order and from what I found online I was able to piece together this code:
```
<?php $loop = new WP_Query(array('post_type' => 'page', 'meta_key' => '_thumbnail_id', 'order' => 'asc')); ?>
```
and it works:
[](https://i.stack.imgur.com/GRnnI.jpg) |
272,331 | <p>Hi I just switched woocomerce version from 3.0.9 to 3.1.0. And I received this mesage "WooCommerce data update – We need to update your store database to the latest version"</p>
<p>So can I udpate safely woocommerce data?</p>
<p>Thanks</p>
| [
{
"answer_id": 272303,
"author": "Regolith",
"author_id": 103884,
"author_profile": "https://wordpress.stackexchange.com/users/103884",
"pm_score": 0,
"selected": false,
"text": "<p>first off you are using <code>echo the_permalink()</code></p>\n\n<pre><code><a href=\"<?php echo the_permalink(); ?>\"><?php \n if(has_post_thumbnail()) {\n the_post_thumbnail();\n }\n?></a>\n</code></pre>\n\n<p>you don't have to echo out permalink</p>\n\n<pre><code><a href=\"<?php the_permalink(); ?>\"><?php \n if(has_post_thumbnail()) {\n the_post_thumbnail();\n }\n?></a>\n</code></pre>\n\n<p>carefully read the <code>https://codex.wordpress.org/Using_Permalinks</code> codex part in wordpress site</p>\n\n<p>Also if you are using multiple loops in the page use <code>wp_reset_query();</code> after or before the loop. And be sure to review your query arguments. For example:<br>\nwhere is the query for contents after <code><h3 class=\"panel-title\">Welcome to Three Green Birds!</h3></code>.\n<br>\ntake reference for wp queries from <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query\" rel=\"nofollow noreferrer\">WP_Query</a> and <a href=\"https://developer.wordpress.org/reference/functions/query_posts/\" rel=\"nofollow noreferrer\">query_posts</a></p>\n"
},
{
"answer_id": 272437,
"author": "Daniel",
"author_id": 109760,
"author_profile": "https://wordpress.stackexchange.com/users/109760",
"pm_score": 2,
"selected": true,
"text": "<p>I learned that in the WP Query I had to specify page instead of quick_links which was the custom post type. In fact I completely removed the Custom Post Type UI and the plugin. It was all completely unnecessary.</p>\n\n<p>I did not want every single page, just the news, about us and get involved so I researched if there was a way to grab specific pages, namely, those with a featured image and in the correct order and from what I found online I was able to piece together this code:</p>\n\n<pre><code><?php $loop = new WP_Query(array('post_type' => 'page', 'meta_key' => '_thumbnail_id', 'order' => 'asc')); ?>\n</code></pre>\n\n<p>and it works:</p>\n\n<p><a href=\"https://i.stack.imgur.com/GRnnI.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/GRnnI.jpg\" alt=\"enter image description here\"></a></p>\n"
}
]
| 2017/07/05 | [
"https://wordpress.stackexchange.com/questions/272331",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/119118/"
]
| Hi I just switched woocomerce version from 3.0.9 to 3.1.0. And I received this mesage "WooCommerce data update – We need to update your store database to the latest version"
So can I udpate safely woocommerce data?
Thanks | I learned that in the WP Query I had to specify page instead of quick\_links which was the custom post type. In fact I completely removed the Custom Post Type UI and the plugin. It was all completely unnecessary.
I did not want every single page, just the news, about us and get involved so I researched if there was a way to grab specific pages, namely, those with a featured image and in the correct order and from what I found online I was able to piece together this code:
```
<?php $loop = new WP_Query(array('post_type' => 'page', 'meta_key' => '_thumbnail_id', 'order' => 'asc')); ?>
```
and it works:
[](https://i.stack.imgur.com/GRnnI.jpg) |
272,337 | <p>I am attempting to filter results based on what the user has inputted.</p>
<pre><code>function custom_archive() {
if ( is_post_type_archive( 'profiles' ) ) {
// if we are on a profiles archive page, edit the query according to the posted data.
$data = $_POST['networks'];
if ( isset( $data ) ) {
//count the array
if ( count( $data ) > 1 ) {
$data = implode( ',', $data );
} else {
//$data = $data[0];
}
//set the query to only search for whatever the user wants, eg news
$wp_query->set( 'tax_query', array(
array(
'taxonomy' => 'networks',
'field' => 'id',
'terms' => $data,
'operator' => 'IN',
),
) );
}
}
}
add_action( 'pre_get_posts', 'custom_archive' );
</code></pre>
<p>I have debugged my code and the data get's inputted correctly. Although, I get no posts back.</p>
<p>Are there any problems with this code? I believe the error may be elsewhere in my theme, but I do wish to check out this code so I can take it out of the equation. Cheers!</p>
<p><strong>EDIT:</strong> One thing I should mention is that I have a version of this code working for my Blog page. I am trying to now get this code working for an archive, and for it to return the correct posts still within the archive page, but instead it redirects me to a Search page. </p>
| [
{
"answer_id": 272338,
"author": "Picard",
"author_id": 118566,
"author_profile": "https://wordpress.stackexchange.com/users/118566",
"pm_score": 0,
"selected": false,
"text": "<p>You should provide an array of id's to the tax_query - like here in the example from the <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Taxonomy_Parameters\" rel=\"nofollow noreferrer\">docs</a>:</p>\n\n<pre><code>'tax_query' => array(\n array(\n 'taxonomy' => 'actor',\n 'field' => 'term_id',\n 'terms' => array( 103, 115, 206 ),\n 'operator' => 'NOT IN',\n ),\n</code></pre>\n\n<p>So you could and should sanitize the values from <code>$_POST['networks']</code> but shouldn't do implode which turns the array into a flat string.</p>\n"
},
{
"answer_id": 272342,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 1,
"selected": false,
"text": "<p>So there's a few things wrong with the code:</p>\n\n<ol>\n<li>You're not using the query object that's passed to the pre_get_posts hook, so you're not modifying the actual query.</li>\n<li>Field is set to <code>id</code> instead of <code>term_id</code>.</li>\n<li>If you're using <code>IN</code> as the operator, pass an array to terms.</li>\n<li>You're not sanitizing the value of $_POST['networks']. You <em>might</em> be ok without it, since WordPress shouldn't let anything too nasty happen, but it's a good idea to at least ensure that the values are the correct type.</li>\n</ol>\n\n<p>This version of the function addresses these issues:</p>\n\n<pre><code>function my_query_by_selected_networks( $query ) {\n if ( is_admin() ) {\n return;\n }\n\n if ( $query->is_main_query() && $query->is_post_type_archive( 'profiles' ) ) {\n if ( isset( $_POST['networks'] ) ) {\n if ( is_array( $_POST['networks'] ) ) {\n $networks = array_map( 'intval', $_POST['networks'])\n } else {\n $networks = array( intval( $_POST['networks'] ) );\n }\n\n $tax_query = $query->get( 'tax_query' ) ?: array();\n\n $tax_query[] = array(\n 'taxonomy' => 'networks',\n 'field' => 'term_id',\n 'terms' => $networks,\n 'operator' => 'IN',\n );\n\n $query->set( 'tax_query', $tax_query );\n }\n }\n}\nadd_action( 'pre_get_posts', 'my_query_by_selected_networks' );\n</code></pre>\n\n<p>Note:</p>\n\n<ol>\n<li>The function accepts the <code>$query</code> variable and uses that the update the query.</li>\n<li>It uses <code>term_id</code> as the value for <code>field</code>.</li>\n<li><code>$networks</code>, the value passed to the tax query is left as an array, or made an array if <code>$_POST['networks']</code> isn't already an array.</li>\n<li>It sanitizes the value of <code>$_POST['networks']</code> with <code>intval</code>, making sure that <code>$networks</code> is an array of integers, which is what the tax query expects.</li>\n</ol>\n\n<p>Additionally, I modified the tax_query code so that it doesn't entirely replace any tax queries that could be made by other plugins. It does this by checking if there's already a tax query and adding on to it if there is. This is probably unnecessary, but it's a habit of mine.</p>\n\n<p><strong>EDIT:</strong> As per Tom's suggestion I've added in <code>$query->is_main_query()</code>, to make sure that we're only modifying the main loop, so this doesn't go and affect things like widgets and menus etc. I also added a bit at the top to bail if we're in the admin, since we don't want to modify back-end queries.</p>\n\n<p>Also, <code>custom_archive</code> is a very generic name for a function, and could easily be shared by other plugins or WordPress itself. It's a good idea to be more descriptive, but most importantly, you should prefix functions with something unique to your theme or plugin to avoid conflicts. In my example it's just <code>my_</code>. I suggest replacing it, since <code>my_</code> is a common example prefix.</p>\n"
}
]
| 2017/07/05 | [
"https://wordpress.stackexchange.com/questions/272337",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/118553/"
]
| I am attempting to filter results based on what the user has inputted.
```
function custom_archive() {
if ( is_post_type_archive( 'profiles' ) ) {
// if we are on a profiles archive page, edit the query according to the posted data.
$data = $_POST['networks'];
if ( isset( $data ) ) {
//count the array
if ( count( $data ) > 1 ) {
$data = implode( ',', $data );
} else {
//$data = $data[0];
}
//set the query to only search for whatever the user wants, eg news
$wp_query->set( 'tax_query', array(
array(
'taxonomy' => 'networks',
'field' => 'id',
'terms' => $data,
'operator' => 'IN',
),
) );
}
}
}
add_action( 'pre_get_posts', 'custom_archive' );
```
I have debugged my code and the data get's inputted correctly. Although, I get no posts back.
Are there any problems with this code? I believe the error may be elsewhere in my theme, but I do wish to check out this code so I can take it out of the equation. Cheers!
**EDIT:** One thing I should mention is that I have a version of this code working for my Blog page. I am trying to now get this code working for an archive, and for it to return the correct posts still within the archive page, but instead it redirects me to a Search page. | So there's a few things wrong with the code:
1. You're not using the query object that's passed to the pre\_get\_posts hook, so you're not modifying the actual query.
2. Field is set to `id` instead of `term_id`.
3. If you're using `IN` as the operator, pass an array to terms.
4. You're not sanitizing the value of $\_POST['networks']. You *might* be ok without it, since WordPress shouldn't let anything too nasty happen, but it's a good idea to at least ensure that the values are the correct type.
This version of the function addresses these issues:
```
function my_query_by_selected_networks( $query ) {
if ( is_admin() ) {
return;
}
if ( $query->is_main_query() && $query->is_post_type_archive( 'profiles' ) ) {
if ( isset( $_POST['networks'] ) ) {
if ( is_array( $_POST['networks'] ) ) {
$networks = array_map( 'intval', $_POST['networks'])
} else {
$networks = array( intval( $_POST['networks'] ) );
}
$tax_query = $query->get( 'tax_query' ) ?: array();
$tax_query[] = array(
'taxonomy' => 'networks',
'field' => 'term_id',
'terms' => $networks,
'operator' => 'IN',
);
$query->set( 'tax_query', $tax_query );
}
}
}
add_action( 'pre_get_posts', 'my_query_by_selected_networks' );
```
Note:
1. The function accepts the `$query` variable and uses that the update the query.
2. It uses `term_id` as the value for `field`.
3. `$networks`, the value passed to the tax query is left as an array, or made an array if `$_POST['networks']` isn't already an array.
4. It sanitizes the value of `$_POST['networks']` with `intval`, making sure that `$networks` is an array of integers, which is what the tax query expects.
Additionally, I modified the tax\_query code so that it doesn't entirely replace any tax queries that could be made by other plugins. It does this by checking if there's already a tax query and adding on to it if there is. This is probably unnecessary, but it's a habit of mine.
**EDIT:** As per Tom's suggestion I've added in `$query->is_main_query()`, to make sure that we're only modifying the main loop, so this doesn't go and affect things like widgets and menus etc. I also added a bit at the top to bail if we're in the admin, since we don't want to modify back-end queries.
Also, `custom_archive` is a very generic name for a function, and could easily be shared by other plugins or WordPress itself. It's a good idea to be more descriptive, but most importantly, you should prefix functions with something unique to your theme or plugin to avoid conflicts. In my example it's just `my_`. I suggest replacing it, since `my_` is a common example prefix. |
272,351 | <p>I have a simple control that displays a checkbox in the Customizer:</p>
<pre><code>$wp_customize->add_setting( 'display_about_text', array(
'default' => true
) );
$wp_customize->add_control( 'display_about_text', array(
'label' => __( 'Display Text', 'my_theme_name' ),
'type' => 'checkbox',
'section' => 'about'
) );
</code></pre>
<p>I would like to bold <code>Display Text</code> in the Customizer, so I changed the label line to:</p>
<pre><code> 'label' => __( '<strong>Display Text</strong>', 'minitheme' ),
</code></pre>
<p>However, it just outputs the HTML tags in the Customizer like this:</p>
<p><code><strong>Display Text</strong></code></p>
<p>How do I get it to display bold instead of outputting the HTML? I've run into this problem several times when I try to output HTML in the Customizer. Same problem with <code>esc_html()</code>.</p>
| [
{
"answer_id": 272409,
"author": "Dave Romsey",
"author_id": 2807,
"author_profile": "https://wordpress.stackexchange.com/users/2807",
"pm_score": 1,
"selected": false,
"text": "<p>The Customizer runs the label text through <code>esc_html()</code>, so HTML is not permitted in labels by default. You could override the renderer for each control's content where you want to use a bold label, but that's probably overkill.</p>\n\n<p>Instead, here's a solution that uses the <code>customize_controls_enqueue_scripts</code> action to enqueue JavaScript on the Customizer screen. jQuery is then used to target the desired control and wrap the label's text in <code><strong></code> tags.</p>\n\n<pre><code>add_action( 'customize_controls_enqueue_scripts', 'wpse_customize_controls_scripts' );\nfunction wpse_customize_controls_scripts() {\n wp_enqueue_script(\n 'wpse-customize',\n get_template_directory_uri() . '/js/wpse-customize.js',\n [ 'jquery', 'customize-controls' ],\n false,\n true\n );\n}\n</code></pre>\n\n<p><strong>wpse-customize.js</strong></p>\n\n<pre><code>jQuery( document ).ready( function( $ ) {\n $( \"#customize-control-display_about_text label\" ).wrapInner( \"<strong></strong>\" );\n});\n</code></pre>\n"
},
{
"answer_id": 272412,
"author": "Weston Ruter",
"author_id": 8521,
"author_profile": "https://wordpress.stackexchange.com/users/8521",
"pm_score": 3,
"selected": true,
"text": "<p>You should use CSS for this. For example:</p>\n\n<pre><code>#customize-control-display_about_text label {\n font-weight: bold;\n}\n</code></pre>\n\n<p>Enqueue the stylesheet for this at the <code>customize_controls_enqueue_scripts</code> action.</p>\n\n<p>If you must use JS to modify a control, then note that I would not advise using <code>jQuery.ready</code> in the other answer. You should instead make use of the Customizer JS API to access the control once it is ready, for example enqueue a script at the <code>customize_controls_enqueue_scripts</code> action which contains:</p>\n\n<pre><code>wp.customize.control( 'display_about_text', function( control ) {\n control.deferred.embedded.done( function() {\n control.container.find( 'label' ).wrapInner( '<strong></strong>' );\n });\n});\n</code></pre>\n\n<p>This pattern can be seen in core actually in how the <code>textarea</code> for the Custom CSS feature is extended: <a href=\"https://github.com/WordPress/wordpress-develop/blob/4.8.0/src/wp-admin/js/customize-controls.js#L5343-L5346\" rel=\"nofollow noreferrer\">https://github.com/WordPress/wordpress-develop/blob/4.8.0/src/wp-admin/js/customize-controls.js#L5343-L5346</a></p>\n"
}
]
| 2017/07/05 | [
"https://wordpress.stackexchange.com/questions/272351",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/40536/"
]
| I have a simple control that displays a checkbox in the Customizer:
```
$wp_customize->add_setting( 'display_about_text', array(
'default' => true
) );
$wp_customize->add_control( 'display_about_text', array(
'label' => __( 'Display Text', 'my_theme_name' ),
'type' => 'checkbox',
'section' => 'about'
) );
```
I would like to bold `Display Text` in the Customizer, so I changed the label line to:
```
'label' => __( '<strong>Display Text</strong>', 'minitheme' ),
```
However, it just outputs the HTML tags in the Customizer like this:
`<strong>Display Text</strong>`
How do I get it to display bold instead of outputting the HTML? I've run into this problem several times when I try to output HTML in the Customizer. Same problem with `esc_html()`. | You should use CSS for this. For example:
```
#customize-control-display_about_text label {
font-weight: bold;
}
```
Enqueue the stylesheet for this at the `customize_controls_enqueue_scripts` action.
If you must use JS to modify a control, then note that I would not advise using `jQuery.ready` in the other answer. You should instead make use of the Customizer JS API to access the control once it is ready, for example enqueue a script at the `customize_controls_enqueue_scripts` action which contains:
```
wp.customize.control( 'display_about_text', function( control ) {
control.deferred.embedded.done( function() {
control.container.find( 'label' ).wrapInner( '<strong></strong>' );
});
});
```
This pattern can be seen in core actually in how the `textarea` for the Custom CSS feature is extended: <https://github.com/WordPress/wordpress-develop/blob/4.8.0/src/wp-admin/js/customize-controls.js#L5343-L5346> |
272,360 | <p>I need to 'soft' disable posts in a WordPress site. By that I mean I am hiding the 'Posts' menu item from admin... and not much else.</p>
<p>I would also like to disable 'posts' from appearing in the Menu admin. This can already be turned off by deselecting it from 'Screen Options', but is there a way to do this programmatically and, as a bonus, also hide the 'posts' checkbox from the Screen Options panel?</p>
| [
{
"answer_id": 272372,
"author": "Pratik bhatt",
"author_id": 60922,
"author_profile": "https://wordpress.stackexchange.com/users/60922",
"pm_score": 1,
"selected": false,
"text": "<p>Now create your own function called post_remove() and add code in functions.php as:</p>\n\n<pre><code>function posts_hide() //creating functions post_remove for removing menu item\n{ \n remove_menu_page('edit.php');\n}\n\nadd_action('admin_menu', 'posts_hide'); //adding action for triggering function call\n</code></pre>\n\n<p>Hope this solves you query.</p>\n"
},
{
"answer_id": 272377,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 3,
"selected": true,
"text": "<p>We can use the <code>register_post_type_args</code> filter to adjust how the <code>post</code> post type is displayed in the backend with e.g.:</p>\n\n<pre><code>add_filter( 'register_post_type_args', function( $args, $name )\n{\n if( 'post' === $name )\n { \n // $args['show_ui'] = false; // Display the user-interface\n $args['show_in_nav_menus'] = false; // Display for selection in navigation menus\n $args['show_in_menu'] = false; // Display in the admin menu\n $args['show_in_admin_bar'] = false; // Display in the WordPress admin bar\n }\n return $args;\n}, 10, 2 );\n</code></pre>\n\n<p>More info on the parameters <a href=\"https://developer.wordpress.org/reference/functions/register_post_type/\" rel=\"nofollow noreferrer\">here</a> in the Codex.</p>\n"
}
]
| 2017/07/05 | [
"https://wordpress.stackexchange.com/questions/272360",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/60816/"
]
| I need to 'soft' disable posts in a WordPress site. By that I mean I am hiding the 'Posts' menu item from admin... and not much else.
I would also like to disable 'posts' from appearing in the Menu admin. This can already be turned off by deselecting it from 'Screen Options', but is there a way to do this programmatically and, as a bonus, also hide the 'posts' checkbox from the Screen Options panel? | We can use the `register_post_type_args` filter to adjust how the `post` post type is displayed in the backend with e.g.:
```
add_filter( 'register_post_type_args', function( $args, $name )
{
if( 'post' === $name )
{
// $args['show_ui'] = false; // Display the user-interface
$args['show_in_nav_menus'] = false; // Display for selection in navigation menus
$args['show_in_menu'] = false; // Display in the admin menu
$args['show_in_admin_bar'] = false; // Display in the WordPress admin bar
}
return $args;
}, 10, 2 );
```
More info on the parameters [here](https://developer.wordpress.org/reference/functions/register_post_type/) in the Codex. |
272,375 | <p>I'm searching a lot about custom widgets, it seems that it can be displayed just in the sidebar, but I want to display it in my theme's footer
It's just a copyright custom text that I want to add into a widget to easily change it in WP admin, I was following this tutorial: <a href="http://www.wpbeginner.com/wp-tutorials/how-to-create-a-custom-wordpress-widget/" rel="nofollow noreferrer">http://www.wpbeginner.com/wp-tutorials/how-to-create-a-custom-wordpress-widget/</a></p>
<p>I have the following structure:</p>
<pre><code>theme-folder
----includes
--------widgets
------------copyright.php
//functions.php
include_once( 'includes/widgets/copyright.php' );
if (function_exists("register_sidebar")) {
register_sidebar();
}
</code></pre>
<p>copyright.php file:</p>
<pre><code><?php
function register_my_widget() {// function to register my widget
register_widget( 'My_Widget' );
}
function My_Widget() {
$widget_ops = array( 'classname' => 'example', 'description' => __('A widget that displays the authors name ', 'example') );
$control_ops = array( 'width' => 300, 'height' => 350, 'id_base' => 'example-widget' );
$this->WP_Widget( 'example-widget', __('Example Widget', 'example'), $widget_ops, $control_ops );
}
add_action( 'widgets_init', 'register_my_widget' );// function to load my widget
class my_widget extends WP_Widget {// The example widget class
// constructor
function __construct() {
parent::__construct(
false,
__( 'My Widget', 'my-widget' ),
array( 'description' => __( 'My sample widget', 'my-widget' ) ) );
}
}
function widget( $args, $instance ) {// display the widget
extract( $args );
$title = apply_filters('widget_title', $instance['title'] );
$name = $instance['name'];
$show_info = isset( $instance['show_info'] ) ? $instance['show_info'] : false;
echo $before_widget;
// Display the widget title
if ( $title )
echo $before_title . $title . $after_title;
//Display the name
if ( $name )
printf( '<p>' . __('Hey their Sailor! My name is %1$s.', 'example') . '</p>', $name );
if ( $show_info )
printf( $name );
echo $after_widget;
}
function update( $new_instance, $old_instance ) {// update the widget
$instance = $old_instance;
//Strip tags from title and name to remove HTML
$instance['title'] = strip_tags( $new_instance['title'] );
$instance['name'] = strip_tags( $new_instance['name'] );
$instance['show_info'] = $new_instance['show_info'];
return $instance;
}
function form() {// and of course the form for the widget options
//Set up some default widget settings.
$defaults = array( 'title' => __('Example', 'example'), 'name' => __('Bilal Shaheen', 'example'), 'show_info' => true );
$instance = wp_parse_args( (array) $instance, $defaults );
//Text Input
// <p>
// <label for="echo $this->get_field_id( 'name' );"><?php _e('Your Name:', 'example');</label>
// <input id="echo $this->get_field_id( 'name' );" name="echo $this->get_field_name( 'name' );" value="echo $instance['name'];" style="width:100%;" />
// </p>
}
?>
</code></pre>
<p>I needed to comment the html because it's not being recognized, and I don't know how to call the widget inside my footer.php, anyone have tried to do the same before?</p>
| [
{
"answer_id": 272372,
"author": "Pratik bhatt",
"author_id": 60922,
"author_profile": "https://wordpress.stackexchange.com/users/60922",
"pm_score": 1,
"selected": false,
"text": "<p>Now create your own function called post_remove() and add code in functions.php as:</p>\n\n<pre><code>function posts_hide() //creating functions post_remove for removing menu item\n{ \n remove_menu_page('edit.php');\n}\n\nadd_action('admin_menu', 'posts_hide'); //adding action for triggering function call\n</code></pre>\n\n<p>Hope this solves you query.</p>\n"
},
{
"answer_id": 272377,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 3,
"selected": true,
"text": "<p>We can use the <code>register_post_type_args</code> filter to adjust how the <code>post</code> post type is displayed in the backend with e.g.:</p>\n\n<pre><code>add_filter( 'register_post_type_args', function( $args, $name )\n{\n if( 'post' === $name )\n { \n // $args['show_ui'] = false; // Display the user-interface\n $args['show_in_nav_menus'] = false; // Display for selection in navigation menus\n $args['show_in_menu'] = false; // Display in the admin menu\n $args['show_in_admin_bar'] = false; // Display in the WordPress admin bar\n }\n return $args;\n}, 10, 2 );\n</code></pre>\n\n<p>More info on the parameters <a href=\"https://developer.wordpress.org/reference/functions/register_post_type/\" rel=\"nofollow noreferrer\">here</a> in the Codex.</p>\n"
}
]
| 2017/07/05 | [
"https://wordpress.stackexchange.com/questions/272375",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/26805/"
]
| I'm searching a lot about custom widgets, it seems that it can be displayed just in the sidebar, but I want to display it in my theme's footer
It's just a copyright custom text that I want to add into a widget to easily change it in WP admin, I was following this tutorial: <http://www.wpbeginner.com/wp-tutorials/how-to-create-a-custom-wordpress-widget/>
I have the following structure:
```
theme-folder
----includes
--------widgets
------------copyright.php
//functions.php
include_once( 'includes/widgets/copyright.php' );
if (function_exists("register_sidebar")) {
register_sidebar();
}
```
copyright.php file:
```
<?php
function register_my_widget() {// function to register my widget
register_widget( 'My_Widget' );
}
function My_Widget() {
$widget_ops = array( 'classname' => 'example', 'description' => __('A widget that displays the authors name ', 'example') );
$control_ops = array( 'width' => 300, 'height' => 350, 'id_base' => 'example-widget' );
$this->WP_Widget( 'example-widget', __('Example Widget', 'example'), $widget_ops, $control_ops );
}
add_action( 'widgets_init', 'register_my_widget' );// function to load my widget
class my_widget extends WP_Widget {// The example widget class
// constructor
function __construct() {
parent::__construct(
false,
__( 'My Widget', 'my-widget' ),
array( 'description' => __( 'My sample widget', 'my-widget' ) ) );
}
}
function widget( $args, $instance ) {// display the widget
extract( $args );
$title = apply_filters('widget_title', $instance['title'] );
$name = $instance['name'];
$show_info = isset( $instance['show_info'] ) ? $instance['show_info'] : false;
echo $before_widget;
// Display the widget title
if ( $title )
echo $before_title . $title . $after_title;
//Display the name
if ( $name )
printf( '<p>' . __('Hey their Sailor! My name is %1$s.', 'example') . '</p>', $name );
if ( $show_info )
printf( $name );
echo $after_widget;
}
function update( $new_instance, $old_instance ) {// update the widget
$instance = $old_instance;
//Strip tags from title and name to remove HTML
$instance['title'] = strip_tags( $new_instance['title'] );
$instance['name'] = strip_tags( $new_instance['name'] );
$instance['show_info'] = $new_instance['show_info'];
return $instance;
}
function form() {// and of course the form for the widget options
//Set up some default widget settings.
$defaults = array( 'title' => __('Example', 'example'), 'name' => __('Bilal Shaheen', 'example'), 'show_info' => true );
$instance = wp_parse_args( (array) $instance, $defaults );
//Text Input
// <p>
// <label for="echo $this->get_field_id( 'name' );"><?php _e('Your Name:', 'example');</label>
// <input id="echo $this->get_field_id( 'name' );" name="echo $this->get_field_name( 'name' );" value="echo $instance['name'];" style="width:100%;" />
// </p>
}
?>
```
I needed to comment the html because it's not being recognized, and I don't know how to call the widget inside my footer.php, anyone have tried to do the same before? | We can use the `register_post_type_args` filter to adjust how the `post` post type is displayed in the backend with e.g.:
```
add_filter( 'register_post_type_args', function( $args, $name )
{
if( 'post' === $name )
{
// $args['show_ui'] = false; // Display the user-interface
$args['show_in_nav_menus'] = false; // Display for selection in navigation menus
$args['show_in_menu'] = false; // Display in the admin menu
$args['show_in_admin_bar'] = false; // Display in the WordPress admin bar
}
return $args;
}, 10, 2 );
```
More info on the parameters [here](https://developer.wordpress.org/reference/functions/register_post_type/) in the Codex. |
272,386 | <p>I'm trying to create a secure download plugin.</p>
<p>I found the rest api the best option for this task, but i cant change headers like <code>Content-Type:</code>. In the <code>register_rest_route</code> callback these headers already set.
If i set <code>Content-disposition: attachment, filename=asd.txt</code> i get <code>ERR_RESPONSE_HEADERS_MULTIPLE_CONTENT_DISPOSITION</code> in chrome.</p>
<p>I know rest is not meant to handle these tasks, but i couldn't find any alternatives. If there is, pls tell me about it.</p>
<p>The data downloaded seems like it's json encoded.</p>
<p>I'm sick of wordpress "magic". These tasks would be so easy using plain PHP but wordpress just makes it complicated.</p>
<p>Please someone tell me how to disable these magic headers *** or recommend me a way for secured (php) downloads in my plugin.</p>
<p>(No, i don't want to use third party plugins. I've tried many of them. None of them worked so far... :D These whole wordpress thing is a huge step backwards after symfony...)</p>
<p>Here is my <strong>experimental</strong> code:</p>
<pre><code>add_action('rest_api_init', function() {
register_rest_route('secure-downloads/v1', '/download/(?P<filename>.*)',
array(
'methods' => 'GET',
'callback' => 'secure_downloads_handle_download'
));
});
function secure_downloads_handle_download(WP_REST_Request $request)
{
$filename = urldecode($request->offsetGet('filename'));
if(strpos($filename, '/..'))
{
return new WP_REST_Response('', 403);
}
$path = SECURE_DOWNLOADS_UPLOAD_DIR . $filename;
return new WP_REST_Response(file_get_contents($path), 200, array(
'Content-Type' => 'application/octet-stream',
'Content-Transfer-Encoding' => 'Binary',
'Content-disposition' => 'attachment, filename=\\' . $filename . '\\'
));
}
</code></pre>
| [
{
"answer_id": 272389,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 1,
"selected": false,
"text": "<p>It should be enough to add the content disposition field.</p>\n\n<p>But specifically it's Content-<strong>D</strong>isposition not Content-<strong>d</strong>isposition</p>\n\n<p>I would also add some validation to your filename parameter thats being passed to <code>file_get_contents</code> to ensure it exists and it's valid. Else you might be vulnerable to directory traversal attacks or remote URL requests</p>\n"
},
{
"answer_id": 272402,
"author": "Jumi",
"author_id": 123204,
"author_profile": "https://wordpress.stackexchange.com/users/123204",
"pm_score": 2,
"selected": true,
"text": "<p>Here is what i found out:</p>\n\n<p>The <code>ERR_RESPONSE_HEADERS_MULTIPLE_CONTENT_DISPOSITION</code> error was the bad composition of the <code>Content-Disposition</code> header. Here is the correct one:</p>\n\n<pre><code>array(\n 'Content-Disposition' => 'attachment; filename=\"' . $filename . '\"'\n)\n</code></pre>\n\n<p>Note the <strong>semicolon</strong> after attachment, the <strong>doublequotes</strong> around the filename and the <strong>capital D</strong> in disposition word as @Tom J Nowell pointed out.</p>\n\n<p>This solved the headers problem but the <code>WP_REST_Response</code> still outputs the files like they were json encoded. So i went the conventional way:</p>\n\n<pre><code>header('Content-Disposition: attachment; filename=\"' . $filename . '\"');\nheader('Content-Type: application/octet-stream');\nreadfile($path);\nexit;\n</code></pre>\n"
},
{
"answer_id": 386882,
"author": "Walf",
"author_id": 27856,
"author_profile": "https://wordpress.stackexchange.com/users/27856",
"pm_score": 0,
"selected": false,
"text": "<p>There is a hook for exactly this situation that avoids prematurely stopping script execution, and maintains WP's handling of <code>HEAD</code> method requests. Put something similar to this in your REST response handler function:</p>\n<pre class=\"lang-php prettyprint-override\"><code>$your_served = false;\n$your_content = $something;\n\nadd_filter(\n 'rest_pre_serve_request',\n function($served, $result, $request, $rest_server) use (&$your_served, &$your_content) {\n if (!$served) {\n if ($your_served) {\n $served = $your_served;\n }\n else {\n add_filter(\n 'rest_pre_echo_response',\n function($result, $rest_server, $request) use (&$your_served, &$your_content) {\n # serve $your_content here but do not return or exit, in this case readfile() would be optimal\n $your_served = true;\n return null; # explicitly prevent WP sending the normal JSON response\n },\n 10, # change priority to suit\n 3\n );\n }\n }\n return $served;\n },\n 10, # change priority to suit\n 4\n);\n\n$result = new WP_REST_Response();\n$result->set_headers([\n 'Content-Type' => $your_content_type,\n # you may include others such as 'Content-Length'\n]);\nreturn $result;\n</code></pre>\n"
}
]
| 2017/07/05 | [
"https://wordpress.stackexchange.com/questions/272386",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/123204/"
]
| I'm trying to create a secure download plugin.
I found the rest api the best option for this task, but i cant change headers like `Content-Type:`. In the `register_rest_route` callback these headers already set.
If i set `Content-disposition: attachment, filename=asd.txt` i get `ERR_RESPONSE_HEADERS_MULTIPLE_CONTENT_DISPOSITION` in chrome.
I know rest is not meant to handle these tasks, but i couldn't find any alternatives. If there is, pls tell me about it.
The data downloaded seems like it's json encoded.
I'm sick of wordpress "magic". These tasks would be so easy using plain PHP but wordpress just makes it complicated.
Please someone tell me how to disable these magic headers \*\*\* or recommend me a way for secured (php) downloads in my plugin.
(No, i don't want to use third party plugins. I've tried many of them. None of them worked so far... :D These whole wordpress thing is a huge step backwards after symfony...)
Here is my **experimental** code:
```
add_action('rest_api_init', function() {
register_rest_route('secure-downloads/v1', '/download/(?P<filename>.*)',
array(
'methods' => 'GET',
'callback' => 'secure_downloads_handle_download'
));
});
function secure_downloads_handle_download(WP_REST_Request $request)
{
$filename = urldecode($request->offsetGet('filename'));
if(strpos($filename, '/..'))
{
return new WP_REST_Response('', 403);
}
$path = SECURE_DOWNLOADS_UPLOAD_DIR . $filename;
return new WP_REST_Response(file_get_contents($path), 200, array(
'Content-Type' => 'application/octet-stream',
'Content-Transfer-Encoding' => 'Binary',
'Content-disposition' => 'attachment, filename=\\' . $filename . '\\'
));
}
``` | Here is what i found out:
The `ERR_RESPONSE_HEADERS_MULTIPLE_CONTENT_DISPOSITION` error was the bad composition of the `Content-Disposition` header. Here is the correct one:
```
array(
'Content-Disposition' => 'attachment; filename="' . $filename . '"'
)
```
Note the **semicolon** after attachment, the **doublequotes** around the filename and the **capital D** in disposition word as @Tom J Nowell pointed out.
This solved the headers problem but the `WP_REST_Response` still outputs the files like they were json encoded. So i went the conventional way:
```
header('Content-Disposition: attachment; filename="' . $filename . '"');
header('Content-Type: application/octet-stream');
readfile($path);
exit;
``` |
272,406 | <p>I am migrating a static site over to WP. Currently I have a header function that changes the inverted logo to full color on user scroll using JS.
<a href="https://synchronygroup.com/" rel="nofollow noreferrer">See Function on scroll</a></p>
<p><strong>Current JS for Scroll function:</strong></p>
<pre><code>$(window).scroll(function() {
var top = $(window).scrollTop();
//Clears navbar timing functions on initial scroll
clearTimeout(timeout);
//Conditional to make function run if header is scroll pased 100px
if ((top > 100) && $('#mainNav').is(':hidden')) {
showNav();
timeout = setTimeout(hideNav, 2000);
} else if ((top > 100) && $('#mainNav').is(':visible')) {
showNav();
$('#logo').attr('src', './assets/sg-logo-inverted.svg');
$('.nav-trigger-line').css({'background-color':'#fff'});
} else {
$('header').css({
'background-color': 'transparent'
});
$('#logo').attr('src', './assets/sg-logo-inverted.svg');
$('#logo').css({'width': '175px'});
$('.nav-trigger-line').css({'background-color':'#fff'});
}
});
</code></pre>
<p><strong>Current HTML Markup:</strong></p>
<pre><code><header class="fixed-top p-3">
<!-- Logo and Burger -->
<div class="container-fluid brand-wrap">
<div class="row">
<div class="col-6">
<a href="index.html"><img id="logo" src="./assets/sg-logo-inverted.svg" class="img-fluid" alt="Synchrony Group"></a>
</div>
<div class="col-6 trigger-wrapper py-1">
<div id="burger">
<div class="nav-trigger-line"></div>
<div class="nav-trigger-line"></div>
<div class="nav-trigger-line"></div>
</div>
</div>
</div>
</div>
</header>
</code></pre>
<p>I have revised the mark in my header.php file to dynamically include the site logo via the WP Dashboard:</p>
<p><strong>Revised HTML Markup:</strong></p>
<pre><code><header class="fixed-top p-3">
<!-- Logo and Burger -->
<div class="container-fluid brand-wrap">
<div class="row">
<?php if ( get_header_image() ) : ?>
<div class="col-6">
<a href="<?php echo esc_url( home_url( '/' ) ); ?>" rel="home">
<img id="logo" src="<?php header_image(); ?>" class="img-fluid" alt="Synchrony Group">
</a>
</div>
<?php endif; ?>
<div class="col-6 trigger-wrapper py-1">
<div id="burger">
<div class="nav-trigger-line"></div>
<div class="nav-trigger-line"></div>
<div class="nav-trigger-line"></div>
</div>
</div>
</div>
</div>
</header>
</code></pre>
<p>The Scroll Function still works but fails to replace the image because it looks for the image in the specific dir of the page, which does not exist.</p>
<p><strong>Question:</strong> How can I dynamically change the logo on scroll function? Is this something that is handled by PHP rather than JS. What is the correct method to go about doing this?</p>
| [
{
"answer_id": 272403,
"author": "Den Isahac",
"author_id": 113233,
"author_profile": "https://wordpress.stackexchange.com/users/113233",
"pm_score": 4,
"selected": true,
"text": "<p>As stated in the official blog of <strong>jQuery</strong>. Note that <strong>WordPress</strong> is mentioned in the quote.</p>\n<blockquote>\n<h1>jQuery Migrate 1.4.1 released, and the path to jQuery 3.0</h1>\n<p>Version 1.4.1 of the jQuery Migrate plugin has been released. It has only a few changes but the most important of them fixes a problem with unquoted selectors that seems to be very common in some <strong>WordPress</strong> themes. In most cases Migrate can automatically fix this problem when it is used with jQuery 1.12.x or 2.2.x, although it may not be able to repair some complex selectors. The good news is that all the cases of unquoted selectors reported in <strong>WordPress</strong> themes appear to be fixable by this version of Migrate!</p>\n</blockquote>\n<p>A quick answer to your question; <strong>yes</strong> you can remove the <em>jQuery migration</em> script and if you don't see any unwanted behavior after the removal of the script, then it's safe to say that you can completely remove the reference migration script.</p>\n<p>Can be read in <a href=\"https://blog.jquery.com/2016/05/19/jquery-migrate-1-4-1-released-and-the-path-to-jquery-3-0/\" rel=\"nofollow noreferrer\">here</a></p>\n"
},
{
"answer_id": 301944,
"author": "Guy Dumais Digital",
"author_id": 142531,
"author_profile": "https://wordpress.stackexchange.com/users/142531",
"pm_score": 2,
"selected": false,
"text": "<p><strong>Yes you can remove JQuery Migrate</strong> to speed up the loading of your page on the client side.\n<br/>\n<br/></p>\n<h2>What is jQuery Migrate?</h2>\n<p>The jQuery Migrate module (<strong>jquery-migrate.min.js</strong>) is a javascript library that allows you to preserve the compatibility of your jQuery code developed for versions of jQuery older than 1.9. JQuery Migrate also allows developers to detect deprecated code that is no longer supported by the latest jQuery libraries and to adapt it according to the newest versions of jQuery 1.9 and higher.\n<br/>\n<br/></p>\n<h2>PHP code to disable jQuery Migrate in WordPress</h2>\n<p>This is the code I'm using for my clients and it is the right way to remove it properly on the client side without affecting any other components in the WordPress Dashboard. Grab this code and paste it in your functions.php file to remove the JQuery:</p>\n<pre><code>/**\n * Disable jQuery Migrate in WordPress.\n *\n * @author Guy Dumais.\n * @link https://en.guydumais.digital/disable-jquery-migrate-in-wordpress/\n */\nadd_filter( 'wp_default_scripts', $af = static function( &$scripts) {\n if(!is_admin()) {\n $scripts->remove( 'jquery');\n $scripts->add( 'jquery', false, array( 'jquery-core' ), '1.12.4' );\n } \n}, PHP_INT_MAX );\nunset( $af );\n</code></pre>\n<p>Hope this helps!</p>\n"
}
]
| 2017/07/05 | [
"https://wordpress.stackexchange.com/questions/272406",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/104284/"
]
| I am migrating a static site over to WP. Currently I have a header function that changes the inverted logo to full color on user scroll using JS.
[See Function on scroll](https://synchronygroup.com/)
**Current JS for Scroll function:**
```
$(window).scroll(function() {
var top = $(window).scrollTop();
//Clears navbar timing functions on initial scroll
clearTimeout(timeout);
//Conditional to make function run if header is scroll pased 100px
if ((top > 100) && $('#mainNav').is(':hidden')) {
showNav();
timeout = setTimeout(hideNav, 2000);
} else if ((top > 100) && $('#mainNav').is(':visible')) {
showNav();
$('#logo').attr('src', './assets/sg-logo-inverted.svg');
$('.nav-trigger-line').css({'background-color':'#fff'});
} else {
$('header').css({
'background-color': 'transparent'
});
$('#logo').attr('src', './assets/sg-logo-inverted.svg');
$('#logo').css({'width': '175px'});
$('.nav-trigger-line').css({'background-color':'#fff'});
}
});
```
**Current HTML Markup:**
```
<header class="fixed-top p-3">
<!-- Logo and Burger -->
<div class="container-fluid brand-wrap">
<div class="row">
<div class="col-6">
<a href="index.html"><img id="logo" src="./assets/sg-logo-inverted.svg" class="img-fluid" alt="Synchrony Group"></a>
</div>
<div class="col-6 trigger-wrapper py-1">
<div id="burger">
<div class="nav-trigger-line"></div>
<div class="nav-trigger-line"></div>
<div class="nav-trigger-line"></div>
</div>
</div>
</div>
</div>
</header>
```
I have revised the mark in my header.php file to dynamically include the site logo via the WP Dashboard:
**Revised HTML Markup:**
```
<header class="fixed-top p-3">
<!-- Logo and Burger -->
<div class="container-fluid brand-wrap">
<div class="row">
<?php if ( get_header_image() ) : ?>
<div class="col-6">
<a href="<?php echo esc_url( home_url( '/' ) ); ?>" rel="home">
<img id="logo" src="<?php header_image(); ?>" class="img-fluid" alt="Synchrony Group">
</a>
</div>
<?php endif; ?>
<div class="col-6 trigger-wrapper py-1">
<div id="burger">
<div class="nav-trigger-line"></div>
<div class="nav-trigger-line"></div>
<div class="nav-trigger-line"></div>
</div>
</div>
</div>
</div>
</header>
```
The Scroll Function still works but fails to replace the image because it looks for the image in the specific dir of the page, which does not exist.
**Question:** How can I dynamically change the logo on scroll function? Is this something that is handled by PHP rather than JS. What is the correct method to go about doing this? | As stated in the official blog of **jQuery**. Note that **WordPress** is mentioned in the quote.
>
> jQuery Migrate 1.4.1 released, and the path to jQuery 3.0
> =========================================================
>
>
> Version 1.4.1 of the jQuery Migrate plugin has been released. It has only a few changes but the most important of them fixes a problem with unquoted selectors that seems to be very common in some **WordPress** themes. In most cases Migrate can automatically fix this problem when it is used with jQuery 1.12.x or 2.2.x, although it may not be able to repair some complex selectors. The good news is that all the cases of unquoted selectors reported in **WordPress** themes appear to be fixable by this version of Migrate!
>
>
>
A quick answer to your question; **yes** you can remove the *jQuery migration* script and if you don't see any unwanted behavior after the removal of the script, then it's safe to say that you can completely remove the reference migration script.
Can be read in [here](https://blog.jquery.com/2016/05/19/jquery-migrate-1-4-1-released-and-the-path-to-jquery-3-0/) |
272,456 | <p>Hello i use woocommerce and i want to remove the field from the admin panel. How can I do it right?
<a href="https://i.stack.imgur.com/QrJvu.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/QrJvu.jpg" alt="enter image description here"></a></p>
| [
{
"answer_id": 272459,
"author": "tushonline",
"author_id": 15946,
"author_profile": "https://wordpress.stackexchange.com/users/15946",
"pm_score": 3,
"selected": true,
"text": "<p>You cannot remove the field using a code but you can disable using the sale price across the store. </p>\n\n<p><strong>To disable sale price</strong></p>\n\n<pre><code>function custom_wc_get_sale_price( $sale_price, $product ) {\nreturn $product->get_regular_price(); \n return $sale_price;\n}\nadd_filter( 'woocommerce_get_sale_price', 'custom_wc_get_sale_price', 50, 2 );\nadd_filter( 'woocommerce_get_price', 'custom_wc_get_sale_price', 50, 2 );\n</code></pre>\n\n<p><strong>To hide this field,</strong> you can use a CSS to hide it from Product Edit screen. But that CSS needs to be loaded on the admin side, so putting this in theme style sheet may not work. </p>\n"
},
{
"answer_id": 324316,
"author": "T.Todua",
"author_id": 33667,
"author_profile": "https://wordpress.stackexchange.com/users/33667",
"pm_score": 0,
"selected": false,
"text": "<p>You can apply the CSS style to dashboard:</p>\n\n<pre><code>add_action('admin_head', function(){ ?> \n <style> #woocommerce-product-data ._sale_price_field {display:none;} </style> <?php \n});\n</code></pre>\n\n<p>put this code in <code>functions.php</code></p>\n"
}
]
| 2017/07/06 | [
"https://wordpress.stackexchange.com/questions/272456",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/113939/"
]
| Hello i use woocommerce and i want to remove the field from the admin panel. How can I do it right?
[](https://i.stack.imgur.com/QrJvu.jpg) | You cannot remove the field using a code but you can disable using the sale price across the store.
**To disable sale price**
```
function custom_wc_get_sale_price( $sale_price, $product ) {
return $product->get_regular_price();
return $sale_price;
}
add_filter( 'woocommerce_get_sale_price', 'custom_wc_get_sale_price', 50, 2 );
add_filter( 'woocommerce_get_price', 'custom_wc_get_sale_price', 50, 2 );
```
**To hide this field,** you can use a CSS to hide it from Product Edit screen. But that CSS needs to be loaded on the admin side, so putting this in theme style sheet may not work. |
272,471 | <p>I am trying to implement a feature on our site where a user is able to join a team by clicking a button on that teams page (teams being custom roles set up in User Role Editor). However, if the user is already a member of that team, I don't want the button to be displayed for them. </p>
<p>I already have the code working to enable someone to join a team:</p>
<pre><code><?php
add_shortcode( 'select_marketing', 'select_marketing' );
function select_marketing() {
// Stop if user is not logged in.
if ( ! is_user_logged_in() )
return;
ob_start();
?>
<form method="post" action="">
<button class="btn btn-default" type="submit" name="role" value="marketing">Join this Team</button>
</form>
<?php
// Do not process anything if it's not $_POST
if ( ! isset( $_POST['role'] ) )
return;
// Never trust user input.
$role = sanitize_key( $_POST['role'] );
if ( ! in_array( $role, array( 'marketing', ) ) )
return;
// Get the user object
$user = new WP_User( get_current_user_id() );
$index = key( $user->roles );
$user_role = $user->roles[ $index ];
// User already got that user
if ( $user_role == $role ) {
echo sprintf( __( 'You already have %s role.' ), $role );
} else {
// update user role
$user->set_role( $role );
echo sprintf( __( 'Your role was changed to %s.' ), $role );
}
$output = ob_get_contents();
ob_end_clean();
return $output;
}
?>
</code></pre>
<p>However I can't for the life of me figure out how to hide the button for just one specific role, in the example above it would be the marketing role.</p>
<p>If anyone could give me a hand, that would be highly appreciated.</p>
<p>Oh, and if there is a more elegant approach to doing what I am trying achieve, please feel free to let me know. I'm quite new to wordpress and php. </p>
<p>The above code is slightly modified from this post:
<a href="https://wordpress.stackexchange.com/questions/240230/how-to-allow-registered-users-to-change-their-user-role-through-frontend">How to allow registered users to change their user role through frontend?</a></p>
| [
{
"answer_id": 272459,
"author": "tushonline",
"author_id": 15946,
"author_profile": "https://wordpress.stackexchange.com/users/15946",
"pm_score": 3,
"selected": true,
"text": "<p>You cannot remove the field using a code but you can disable using the sale price across the store. </p>\n\n<p><strong>To disable sale price</strong></p>\n\n<pre><code>function custom_wc_get_sale_price( $sale_price, $product ) {\nreturn $product->get_regular_price(); \n return $sale_price;\n}\nadd_filter( 'woocommerce_get_sale_price', 'custom_wc_get_sale_price', 50, 2 );\nadd_filter( 'woocommerce_get_price', 'custom_wc_get_sale_price', 50, 2 );\n</code></pre>\n\n<p><strong>To hide this field,</strong> you can use a CSS to hide it from Product Edit screen. But that CSS needs to be loaded on the admin side, so putting this in theme style sheet may not work. </p>\n"
},
{
"answer_id": 324316,
"author": "T.Todua",
"author_id": 33667,
"author_profile": "https://wordpress.stackexchange.com/users/33667",
"pm_score": 0,
"selected": false,
"text": "<p>You can apply the CSS style to dashboard:</p>\n\n<pre><code>add_action('admin_head', function(){ ?> \n <style> #woocommerce-product-data ._sale_price_field {display:none;} </style> <?php \n});\n</code></pre>\n\n<p>put this code in <code>functions.php</code></p>\n"
}
]
| 2017/07/06 | [
"https://wordpress.stackexchange.com/questions/272471",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/123279/"
]
| I am trying to implement a feature on our site where a user is able to join a team by clicking a button on that teams page (teams being custom roles set up in User Role Editor). However, if the user is already a member of that team, I don't want the button to be displayed for them.
I already have the code working to enable someone to join a team:
```
<?php
add_shortcode( 'select_marketing', 'select_marketing' );
function select_marketing() {
// Stop if user is not logged in.
if ( ! is_user_logged_in() )
return;
ob_start();
?>
<form method="post" action="">
<button class="btn btn-default" type="submit" name="role" value="marketing">Join this Team</button>
</form>
<?php
// Do not process anything if it's not $_POST
if ( ! isset( $_POST['role'] ) )
return;
// Never trust user input.
$role = sanitize_key( $_POST['role'] );
if ( ! in_array( $role, array( 'marketing', ) ) )
return;
// Get the user object
$user = new WP_User( get_current_user_id() );
$index = key( $user->roles );
$user_role = $user->roles[ $index ];
// User already got that user
if ( $user_role == $role ) {
echo sprintf( __( 'You already have %s role.' ), $role );
} else {
// update user role
$user->set_role( $role );
echo sprintf( __( 'Your role was changed to %s.' ), $role );
}
$output = ob_get_contents();
ob_end_clean();
return $output;
}
?>
```
However I can't for the life of me figure out how to hide the button for just one specific role, in the example above it would be the marketing role.
If anyone could give me a hand, that would be highly appreciated.
Oh, and if there is a more elegant approach to doing what I am trying achieve, please feel free to let me know. I'm quite new to wordpress and php.
The above code is slightly modified from this post:
[How to allow registered users to change their user role through frontend?](https://wordpress.stackexchange.com/questions/240230/how-to-allow-registered-users-to-change-their-user-role-through-frontend) | You cannot remove the field using a code but you can disable using the sale price across the store.
**To disable sale price**
```
function custom_wc_get_sale_price( $sale_price, $product ) {
return $product->get_regular_price();
return $sale_price;
}
add_filter( 'woocommerce_get_sale_price', 'custom_wc_get_sale_price', 50, 2 );
add_filter( 'woocommerce_get_price', 'custom_wc_get_sale_price', 50, 2 );
```
**To hide this field,** you can use a CSS to hide it from Product Edit screen. But that CSS needs to be loaded on the admin side, so putting this in theme style sheet may not work. |
272,476 | <p>I have a post-type Collection with custom-post-type categories.</p>
<p>I want the following url structure: www.baseurl.com/collection/current-category-name/postname</p>
<p>How do I accomplish this?</p>
| [
{
"answer_id": 272477,
"author": "berend",
"author_id": 120717,
"author_profile": "https://wordpress.stackexchange.com/users/120717",
"pm_score": 2,
"selected": true,
"text": "<p>Yes you can use the rewrite parameter when creating your custom post type:</p>\n\n<pre><code>register_post_type( 'example_type',\n array(\n 'labels' => array(\n 'name' => \"Example-Type\",\n 'singular_name' => \"example-type\"\n ),\n 'public' => true,\n 'has_archive' => true,\n 'rewrite' => array('slug' => 'the-url-you-want',\n )\n );\n}\n</code></pre>\n\n<p>You will need to reset your permalinks for it to take effect as well.</p>\n\n<p>EDIT:</p>\n\n<pre><code>function custom_post_link( $post_link, $id = 0 ){\n $post = get_post($id); \n if ( is_object( $post ) ){\n $terms = wp_get_object_terms( $post->ID, 'category' );\n if( $terms ){\n return str_replace( '%category%' , $terms[0]->slug , $post_link );\n }\n }\n return $post_link; \n}\nadd_filter( 'post_type_link', 'custom_post_link', 1, 3 );\n</code></pre>\n"
},
{
"answer_id": 272520,
"author": "Luckyfella",
"author_id": 83907,
"author_profile": "https://wordpress.stackexchange.com/users/83907",
"pm_score": 0,
"selected": false,
"text": "<p>I had exactly that problem to solve as well and found this post from <a href=\"https://wordpress.stackexchange.com/users/17048/diana\">Diana</a> that solves it:</p>\n\n<p><a href=\"https://wordpress.stackexchange.com/questions/55351/permalink-rewrite-with-custom-post-type-and-custom-taxonomy/55366#55366\">Permalink rewrite with custom post type and custom taxonomy</a></p>\n"
}
]
| 2017/07/06 | [
"https://wordpress.stackexchange.com/questions/272476",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/31706/"
]
| I have a post-type Collection with custom-post-type categories.
I want the following url structure: www.baseurl.com/collection/current-category-name/postname
How do I accomplish this? | Yes you can use the rewrite parameter when creating your custom post type:
```
register_post_type( 'example_type',
array(
'labels' => array(
'name' => "Example-Type",
'singular_name' => "example-type"
),
'public' => true,
'has_archive' => true,
'rewrite' => array('slug' => 'the-url-you-want',
)
);
}
```
You will need to reset your permalinks for it to take effect as well.
EDIT:
```
function custom_post_link( $post_link, $id = 0 ){
$post = get_post($id);
if ( is_object( $post ) ){
$terms = wp_get_object_terms( $post->ID, 'category' );
if( $terms ){
return str_replace( '%category%' , $terms[0]->slug , $post_link );
}
}
return $post_link;
}
add_filter( 'post_type_link', 'custom_post_link', 1, 3 );
``` |
272,488 | <p>So far I have tried these three options and all 3 of them are not working.</p>
<h2>Option 1</h2>
<pre><code>$options = array(
'meta_key' => 'first_name',
'meta_value' => '',
'meta_compare' => '=',
);
$users = get_users( $options );
</code></pre>
<h2>Option 2</h2>
<pre><code>$options = array(
'meta_key' => 'first_name',
'meta_value' => null,
'meta_compare' => '=',
);
$users = get_users( $options );
</code></pre>
<h2>Option 3</h2>
<pre><code>$options = array(
'meta_query' => array(
array(
'key' => 'first_name',
'compare' => 'NOT EXISTS',
),
)
);
$users = get_users( $options );
</code></pre>
| [
{
"answer_id": 272492,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 2,
"selected": true,
"text": "<p>It looks like you're searching for the <code>first_name</code> meta keys with <strong>empty</strong> string meta values:</p>\n\n<pre><code>$options = array(\n 'meta_query' => array(\n array(\n 'key' => 'first_name',\n 'value' => '',\n 'compare' => '=',\n ),\n )\n);\n$users = get_users( $options );\n</code></pre>\n\n<p>that generates this kind of SQL query:</p>\n\n<pre><code>SELECT wp_users.* \nFROM wp_users \nINNER JOIN wp_usermeta ON ( wp_users.ID = wp_usermeta.user_id ) \nWHERE \n 1=1 AND ( ( wp_usermeta.meta_key = 'first_name' AND wp_usermeta.meta_value = '' ) ) \nORDER BY user_login ASC \n</code></pre>\n\n<p>Note that</p>\n\n<pre><code>$options = array(\n 'meta_key' => 'first_name',\n 'meta_value' => '',\n 'meta_compare' => '=',\n);\n$users = get_users( $options );\n</code></pre>\n\n<p>generates this kind of SQL query:</p>\n\n<pre><code>SELECT wp_users.* \nFROM wp_users \nINNER JOIN wp_usermeta ON ( wp_users.ID = wp_usermeta.user_id ) \nWHERE 1=1 AND ( wp_usermeta.meta_key = 'first_name' ) \nORDER BY user_login ASC ;\n</code></pre>\n"
},
{
"answer_id": 272498,
"author": "Jignesh Patel",
"author_id": 111556,
"author_profile": "https://wordpress.stackexchange.com/users/111556",
"pm_score": 3,
"selected": false,
"text": "<p>Used below code. it return all data which has not first_name key in data base or which has empty first_name </p>\n\n<pre><code>$args = array(\n 'meta_query' => array(\n 'relation' => 'OR',\n array(\n 'key' => 'first_name',\n 'value' => '',\n 'compare' => '=',\n ),\n array(\n 'key' => 'first_name',\n 'value' => '',\n 'compare' => 'NOT EXISTS',\n ),\n )\n);\n$users = get_users( $args );\nvar_dump($users);exit;\n</code></pre>\n"
}
]
| 2017/07/06 | [
"https://wordpress.stackexchange.com/questions/272488",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/24579/"
]
| So far I have tried these three options and all 3 of them are not working.
Option 1
--------
```
$options = array(
'meta_key' => 'first_name',
'meta_value' => '',
'meta_compare' => '=',
);
$users = get_users( $options );
```
Option 2
--------
```
$options = array(
'meta_key' => 'first_name',
'meta_value' => null,
'meta_compare' => '=',
);
$users = get_users( $options );
```
Option 3
--------
```
$options = array(
'meta_query' => array(
array(
'key' => 'first_name',
'compare' => 'NOT EXISTS',
),
)
);
$users = get_users( $options );
``` | It looks like you're searching for the `first_name` meta keys with **empty** string meta values:
```
$options = array(
'meta_query' => array(
array(
'key' => 'first_name',
'value' => '',
'compare' => '=',
),
)
);
$users = get_users( $options );
```
that generates this kind of SQL query:
```
SELECT wp_users.*
FROM wp_users
INNER JOIN wp_usermeta ON ( wp_users.ID = wp_usermeta.user_id )
WHERE
1=1 AND ( ( wp_usermeta.meta_key = 'first_name' AND wp_usermeta.meta_value = '' ) )
ORDER BY user_login ASC
```
Note that
```
$options = array(
'meta_key' => 'first_name',
'meta_value' => '',
'meta_compare' => '=',
);
$users = get_users( $options );
```
generates this kind of SQL query:
```
SELECT wp_users.*
FROM wp_users
INNER JOIN wp_usermeta ON ( wp_users.ID = wp_usermeta.user_id )
WHERE 1=1 AND ( wp_usermeta.meta_key = 'first_name' )
ORDER BY user_login ASC ;
``` |
272,515 | <p>Slowly going crazy over trying to make taxonomy admin columns sortable by a custom field number. I have a custom taxonomy called "typer" and these taxonomies have a custom field called "prioritet". </p>
<p>I managed to get my code to show the column, and make it sortable. Only issue is, that the fields are sorted alphabetically, despite all being numbers. thats means that a fieldset of [1, 3, 14, 22] would show as:</p>
<p>1</p>
<p>14</p>
<p>22</p>
<p>3</p>
<p>My code so far</p>
<pre><code>function create_date_column_for_issues($issue_columns) {
$issue_columns['prioritet'] = 'Prioritet / sortering';
return $issue_columns;
}
add_filter('manage_edit-typer_columns', 'create_date_column_for_issues');
function populate_date_column_for_issues($value, $column_name, $term_id) {
$issue = get_term($term_id, 'typer');
$date = get_field('prioritet', $issue);
switch($column_name) {
case 'prioritet':
$value = $date;
break;
default:
break;
}
return $value;
}
add_filter('manage_typer_custom_column', 'populate_date_column_for_issues', 10, 3);
function register_date_column_for_issues_sortable($columns) {
$columns['prioritet'] = 'prioritet';
return $columns;
}
add_filter('manage_edit-typer_sortable_columns', 'register_date_column_for_issues_sortable');
add_filter( 'terms_clauses', 'filter_terms_clauses', 10, 3 );
/**
* Filter WP_Term_Query meta query
*
* @param object $query WP_Term_Query
* @return object
*/
function filter_terms_clauses( $pieces, $taxonomies, $args ) {
global $pagenow, $wpdb;
// Require ordering
$orderby = ( isset( $_GET['orderby'] ) ) ? trim( sanitize_text_field( $_GET['orderby'] ) ) : '';
if ( empty( $orderby ) ) { return $pieces; }
// set taxonomy
$taxonomy = $taxonomies[0];
// only if current taxonomy or edit page in admin
if ( !is_admin() || $pagenow !== 'edit-tags.php' || !in_array( $taxonomy, [ 'typer' ] ) ) { return $pieces; }
// and ordering matches
if ( $orderby === 'prioritet' ) {
$pieces['join'] .= ' INNER JOIN ' . $wpdb->termmeta . ' AS tm ON t.term_id = tm.term_id ';
$pieces['where'] .= ' AND tm.meta_key = "prioritet"';
$pieces['orderby'] = ' ORDER BY tm.meta_value ';
}
return $pieces;
}
</code></pre>
<p>My knowledge on MySQL is next to nothing, so i have no idea where to go width this. </p>
<p>As an extra:</p>
<p>Right now the sorting will exclude all taxonomies that has an empty field. Would be nice to have these shown in the bottom, but i do realize i requires a way more complicated query. So only join in on that if just so happen to have the solution on the top of your head.</p>
| [
{
"answer_id": 284925,
"author": "dipak_pusti",
"author_id": 44528,
"author_profile": "https://wordpress.stackexchange.com/users/44528",
"pm_score": 2,
"selected": false,
"text": "<p>The code I am posting is a modified and simplified version of yours. I got my solution using your code.</p>\n\n<pre><code>/**\n * Filter WP_Term_Query meta query\n *\n * @param object $query WP_Term_Query\n * @return object\n */\nfunction filter_terms_clauses( $pieces, $taxonomies, $args ) {\n\n global $pagenow, $wpdb;\n\n if(!is_admin()) {\n return $pieces;\n }\n\n if(\n is_admin() \n && $pagenow == 'edit-tags.php' \n && $taxonomies[0] == 'typer' \n && ( isset($_GET['orderby']) && $_GET['orderby'] == 'prioritet' )\n ) {\n\n $pieces['join'] .= ' INNER JOIN ' . $wpdb->termmeta . ' AS tm ON t.term_id = tm.term_id ';\n $pieces['where'] .= ' AND tm.meta_key = \"prioritet\"'; \n $pieces['orderby'] = ' ORDER BY tm.meta_value ';\n $pieces['order'] = isset($_GET['order']) ? $_GET['order'] : \"DESC\";\n }\n\n return $pieces;\n}\n\nadd_filter( 'terms_clauses', 'filter_terms_clauses', 10, 3 );\n</code></pre>\n\n<p>Hope this one helps.</p>\n"
},
{
"answer_id": 285542,
"author": "Lucas Gabriel",
"author_id": 27812,
"author_profile": "https://wordpress.stackexchange.com/users/27812",
"pm_score": 1,
"selected": false,
"text": "<p>for me, I made a custom taxonomy and in that custom taxonomy I had a custom meta. I wanted to have in the admin backend a column and made it sortable. to make sortable work for a custom taxonomy in a custom meta I did this.</p>\n\n<p><a href=\"https://pastebin.com/vr2sCKzX\" rel=\"nofollow noreferrer\">https://pastebin.com/vr2sCKzX</a></p>\n\n<pre><code>public function pre_get_terms( $query ) {\n $meta_query_args = array(\n 'relation' => 'AND', // Optional, defaults to \"AND\"\n array(\n 'key' => 'order_index',\n 'value' => 0,\n 'compare' => '>='\n )\n );\n $meta_query = new WP_Meta_Query( $meta_query_args );\n $query->meta_query = $meta_query;\n $query->orderby = 'position_clause';\n}\n</code></pre>\n\n<p>I found the answer in this link <a href=\"https://core.trac.wordpress.org/ticket/34996\" rel=\"nofollow noreferrer\">https://core.trac.wordpress.org/ticket/34996</a></p>\n\n<p>I just had to adapt the answer provided in the comments by @eherman24</p>\n"
}
]
| 2017/07/06 | [
"https://wordpress.stackexchange.com/questions/272515",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/104160/"
]
| Slowly going crazy over trying to make taxonomy admin columns sortable by a custom field number. I have a custom taxonomy called "typer" and these taxonomies have a custom field called "prioritet".
I managed to get my code to show the column, and make it sortable. Only issue is, that the fields are sorted alphabetically, despite all being numbers. thats means that a fieldset of [1, 3, 14, 22] would show as:
1
14
22
3
My code so far
```
function create_date_column_for_issues($issue_columns) {
$issue_columns['prioritet'] = 'Prioritet / sortering';
return $issue_columns;
}
add_filter('manage_edit-typer_columns', 'create_date_column_for_issues');
function populate_date_column_for_issues($value, $column_name, $term_id) {
$issue = get_term($term_id, 'typer');
$date = get_field('prioritet', $issue);
switch($column_name) {
case 'prioritet':
$value = $date;
break;
default:
break;
}
return $value;
}
add_filter('manage_typer_custom_column', 'populate_date_column_for_issues', 10, 3);
function register_date_column_for_issues_sortable($columns) {
$columns['prioritet'] = 'prioritet';
return $columns;
}
add_filter('manage_edit-typer_sortable_columns', 'register_date_column_for_issues_sortable');
add_filter( 'terms_clauses', 'filter_terms_clauses', 10, 3 );
/**
* Filter WP_Term_Query meta query
*
* @param object $query WP_Term_Query
* @return object
*/
function filter_terms_clauses( $pieces, $taxonomies, $args ) {
global $pagenow, $wpdb;
// Require ordering
$orderby = ( isset( $_GET['orderby'] ) ) ? trim( sanitize_text_field( $_GET['orderby'] ) ) : '';
if ( empty( $orderby ) ) { return $pieces; }
// set taxonomy
$taxonomy = $taxonomies[0];
// only if current taxonomy or edit page in admin
if ( !is_admin() || $pagenow !== 'edit-tags.php' || !in_array( $taxonomy, [ 'typer' ] ) ) { return $pieces; }
// and ordering matches
if ( $orderby === 'prioritet' ) {
$pieces['join'] .= ' INNER JOIN ' . $wpdb->termmeta . ' AS tm ON t.term_id = tm.term_id ';
$pieces['where'] .= ' AND tm.meta_key = "prioritet"';
$pieces['orderby'] = ' ORDER BY tm.meta_value ';
}
return $pieces;
}
```
My knowledge on MySQL is next to nothing, so i have no idea where to go width this.
As an extra:
Right now the sorting will exclude all taxonomies that has an empty field. Would be nice to have these shown in the bottom, but i do realize i requires a way more complicated query. So only join in on that if just so happen to have the solution on the top of your head. | The code I am posting is a modified and simplified version of yours. I got my solution using your code.
```
/**
* Filter WP_Term_Query meta query
*
* @param object $query WP_Term_Query
* @return object
*/
function filter_terms_clauses( $pieces, $taxonomies, $args ) {
global $pagenow, $wpdb;
if(!is_admin()) {
return $pieces;
}
if(
is_admin()
&& $pagenow == 'edit-tags.php'
&& $taxonomies[0] == 'typer'
&& ( isset($_GET['orderby']) && $_GET['orderby'] == 'prioritet' )
) {
$pieces['join'] .= ' INNER JOIN ' . $wpdb->termmeta . ' AS tm ON t.term_id = tm.term_id ';
$pieces['where'] .= ' AND tm.meta_key = "prioritet"';
$pieces['orderby'] = ' ORDER BY tm.meta_value ';
$pieces['order'] = isset($_GET['order']) ? $_GET['order'] : "DESC";
}
return $pieces;
}
add_filter( 'terms_clauses', 'filter_terms_clauses', 10, 3 );
```
Hope this one helps. |
272,525 | <p>I have created <strong>Dynamic Add/Remove Custom Fields (Repeater Fields)</strong> in my custom Post types. It is working perfectly. I want to add a new <strong>JQuery Date Picker</strong> field. I tried hard to create code and also searched the web but found no luck.</p>
<p>Plz Help me.</p>
<p>Following is my code.</p>
<pre><code>function project_rewards_select_options() {
$options = array (
'Option 1' => 'Option 1',
'Option 2' => 'Option 2',
'Option 3' => 'Option 3',
);
return $options;
}
function project_reward_callback( $post ) {
wp_nonce_field( 'project_reward_nonce', 'project_reward_nonce' );
$reward_value = get_post_meta( get_the_ID(), '_project_rewards', true );
$options = project_rewards_select_options();
?>
<script type="text/javascript">
jQuery(document).ready(function( $ ){
$( '#add-row' ).on('click', function() {
var row = $( '.empty-row.screen-reader-text' ).clone(true);
row.removeClass( 'empty-row screen-reader-text' );
row.insertBefore( '#repeatable-fieldset-one tbody>tr:last' );
return false;
});
$( '.remove-row' ).on('click', function() {
$(this).parents('tr').remove();
return false;
});
});
</script>
<table id="repeatable-fieldset-one" width="100%">
<thead>
<tr>
<th width="15%">Reward Amount</th>
<th width="25%">Reward Title</th>
<th width="10%">Shipping</th>
<th width="45%">Reward Description</th>
<th width="5%"></th>
</tr>
</thead>
<tbody>
<?php
( $reward_value );
foreach ( $reward_value as $field ) {
?>
<tr>
<td><input type="text" class="widefat" name="reward[]" value="<?php if ( isset ( $field['reward'] ) ) echo esc_attr( $field['reward'] ); ?>" pattern="[1-9]\d*" /></td>
<td><input type="text" class="widefat" name="reward_title[]" value="<?php if ( isset ( $field['reward_title'] ) ) echo esc_attr( $field['reward_title'] ); ?>" /></td>
<td>
<select class="widefat" name="reward_shipping[]">
<?php foreach ( $options as $label => $value ) : ?>
<option value="<?php echo $value; ?>"<?php selected( $field['reward_shipping'], $value ); ?>><?php echo $label; ?></option>
<?php endforeach; ?>
</select>
</td>
<td><textarea class="widefat" name="reward_description[]"><?php if ( isset ( $field['reward_description'] ) ) echo esc_attr( $field['reward_description'] ); ?></textarea></td>
<td><input type="image" class="remove-row" src="<?php bloginfo('template_directory'); ?>/assets/images/remove-icon.png" alt="Submit" width="35" height="35"></td>
</tr>
<?php } ?>
<!-- empty hidden one for jQuery -->
<tr class="empty-row screen-reader-text">
<td><input type="text" class="widefat" name="reward[]" /></td>
<td><input type="text" class="widefat" name="reward_title[]" /></td>
<td>
<select class="widefat" name="reward_shipping[]">
<?php foreach ( $options as $label => $value ) : ?>
<option value="<?php echo $value; ?>"><?php echo $label; ?></option>
<?php endforeach; ?>
</select>
</td>
<td><textarea class="widefat" name="reward_description[]" ></textarea></td>
<td><input type="image" class="remove-row" src="<?php bloginfo('template_directory'); ?>/assets/images/remove-icon.png" alt="Submit" width="35" height="35"></td>
</tr>
</tbody>
</table>
<p><a id="add-row" class="button" href="#">Add Reward</a></p>
<?php
}
function save_project_reward( $post_id ) {
// Check if our nonce is set.
if ( ! isset( $_POST['project_reward_nonce'] ) ) {
return;
}
// Verify that the nonce is valid.
if ( ! wp_verify_nonce( $_POST['project_reward_nonce'], 'project_reward_nonce' ) ) {
return;
}
// If this is an autosave, our form has not been submitted, so we don't want to do anything.
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
return;
}
// Check the user's permissions.
if ( isset( $_POST['post_type'] ) && 'page' == $_POST['post_type'] ) {
if ( ! current_user_can( 'edit_page', $post_id ) ) {
return;
}
}
else {
if ( ! current_user_can( 'edit_post', $post_id ) ) {
return;
}
}
$reward_data = array();
$options = project_rewards_select_options();
$rewards = $_POST['reward'];
$reward_titles = $_POST['reward_title'];
$reward_shippings = $_POST['reward_shipping'];
$reward_descriptions = $_POST['reward_description'];
$count = count( $rewards );
for ( $i = 0; $i < $count; $i++ ) {
if ( $rewards[$i] != '' ) :
$reward_data[$i]['reward'] = stripslashes( strip_tags( $rewards[$i] ) );
if ( in_array( $reward_shippings[$i], $options ) )
$reward_data[$i]['reward_shipping'] = stripslashes( strip_tags( $reward_shippings[$i] ) );
else
$reward_data[$i]['reward_shipping'] = '';
endif;
if ( $reward_titles[$i] != '' ) :
$reward_data[$i]['reward_title'] = stripslashes( strip_tags( $reward_titles[$i] ) );
endif;
if ( $reward_descriptions[$i] != '' ) :
$reward_data[$i]['reward_description'] = stripslashes( $reward_descriptions[$i] );
endif;
}
update_post_meta( $post_id, '_project_rewards', $reward_data );
}
add_action( 'save_post', 'save_project_reward' );
</code></pre>
| [
{
"answer_id": 272631,
"author": "LWS-Mo",
"author_id": 88895,
"author_profile": "https://wordpress.stackexchange.com/users/88895",
"pm_score": 1,
"selected": false,
"text": "<p>Wordpress has the jQuery datepicker already included. So you can enqueue the default WP script. However, as far as I know, WP doesnt include the necessary styling for the datepicker!<br>\nSo try to enqueue the WP script, and for example, styles from external source:</p>\n\n<pre><code>function my_datepicker_enqueue() {\n wp_enqueue_script( 'jquery-ui-datepicker' ); // enqueue datepicker from WP\n wp_enqueue_style( 'jquery-ui-style', '//ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/base/jquery-ui.css', true);\n}\nadd_action( 'admin_enqueue_scripts', 'my_datepicker_enqueue' );\n</code></pre>\n\n<p>Create a new HTML input field with atleast with a class and a name.\nHTML of the input field: (you already have some input fields defined, so jump to the script)</p>\n\n<pre><code><input type=\"text\" name=\"_custom_datepicker[]\" id=\"_custom_datepicker[]\" class=\"my-custom-datepicker-field\" value=\"<?php echo $your_saved_value; ?>\" />\n</code></pre>\n\n<p>Than add a script to init the datepicker for our new element.\nScript: (make sure that you target the right input element, we are looking at the defined class here, cause we want to use multiple instances.)</p>\n\n<pre><code>jQuery(document).ready(function($){\n $('.my-custom-datepicker-field').datepicker({\n dateFormat: 'dd-mm-yy', //maybe you want something like this\n showButtonPanel: true\n });\n});\n</code></pre>\n\n<hr>\n\n<p><strong>Update:</strong><br>\nI had some problems reading your code at first, and you also have several errors in your code. First I could see the same strange behaviour. I have now setup a testplugin on a dev site, and there it is now working. </p>\n\n<p><strong>1:</strong> You set up your save function so that you cannot just enter a date and save.\nYou will have to either add a amount, title or description also, to be able to save.\nI think this is intended by you?</p>\n\n<p><strong>2:</strong> In the save function you have the following code:</p>\n\n<pre><code>if ( $reward_descriptions[$i] != '' ) :\n $reward_data[$i]['reward_date'] = stripslashes( $reward_dates[$i] );\nendif;\n</code></pre>\n\n<p>So only when the description field is not empty the date will get saved?!\nSeems this was a typo because the other fields look good.\nChange to:</p>\n\n<pre><code>if ( $reward_data[$i] != '' ) :\n $reward_data[$i]['reward_date'] = stripslashes( $reward_dates[$i] );\nendif;\n</code></pre>\n\n<p><strong>3:</strong> In your callback code you have these fields as datepicker fields:</p>\n\n<pre><code><td><input type=\"text\" name=\"_custom_datepicker[]\" id=\"_custom_datepicker[]\" class=\"my-custom-datepicker-field\" value=\"<?php echo esc_attr( $field['reward_date'] ); ?>\" /></td>\n</code></pre>\n\n<p>and</p>\n\n<pre><code><td><input type=\"text\" class=\"my-custom-datepicker-field\" name=\"_custom_datepicker[]\" /></td>\n</code></pre>\n\n<p>Both named <code>_custom_datepicker[]</code>.\nBut in your save function you try to save fields called <code>reward_date</code> instead. </p>\n\n<p>Also the <code>id</code> should be unique. But you add the same <code>id</code> to all datefields.\nYou could just remove the <code>id</code> from these fields, its not needed anyway.</p>\n\n<p><strong>4.</strong> If you add fields dynamically like you want to, you need to change the datepicker JS function.\nAnd instead of loading the JS code inline (and multiple times like you did), I recommend enqueuing one JS file.\nSo try to replace your JS code with something like this:</p>\n\n<pre><code>jQuery(document).ready(function($){\n\n // your default code\n $( '#add-row' ).on('click', function() {\n var row = $( '.empty-row.screen-reader-text' ).clone(true);\n row.removeClass( 'empty-row screen-reader-text' );\n row.insertBefore( '#repeatable-fieldset-one tbody>tr:last' );\n return false;\n });\n\n $( '.remove-row' ).on('click', function() {\n $(this).parents('tr').remove();\n return false;\n });\n\n //changed to be used on dynamic field which gets added and removed from DOM\n //if the element with the class .my-custom-datepicker-field gets focus, add datepicker\n $(document).on('focus', '.my-custom-datepicker-field', function(){\n $(this).datepicker({\n dateFormat: 'dd-mm-yy', //maybe you want something like this\n showButtonPanel: true\n });\n });\n\n});\n</code></pre>\n\n<p>After I fixed these things and enqueued the JS file with the code like WordPress wants it to, it is now working.</p>\n"
},
{
"answer_id": 272636,
"author": "Minu",
"author_id": 113946,
"author_profile": "https://wordpress.stackexchange.com/users/113946",
"pm_score": -1,
"selected": false,
"text": "<p>@LWS-Mo,\n Thanks for helping. I have added the codes accordingly but the datepicker is working weirdly. The date selected in first field get reflected in subsiquent field. Not working properly.</p>\n\n<p>Plz tell me where I am getting wrong. Following is the code.</p>\n\n<pre><code>function project_rewards_select_options() {\n $options = array (\n 'Option 1' => 'Option 1',\n 'Option 2' => 'Option 2',\n 'Option 3' => 'Option 3',\n );\n\n return $options;\n}\n\nfunction crazicle_project_reward_callback( $post ) {\n wp_nonce_field( 'project_reward_nonce', 'project_reward_nonce' );\n $reward_value = get_post_meta( get_the_ID(), '_project_rewards', true );\n $options = project_rewards_select_options();\n\n?>\n\n <script type=\"text/javascript\">\n jQuery(document).ready(function( $ ){\n $( '#add-row' ).on('click', function() {\n var row = $( '.empty-row.screen-reader-text' ).clone(true);\n row.removeClass( 'empty-row screen-reader-text' );\n row.insertBefore( '#repeatable-fieldset-one tbody>tr:last' );\n return false;\n });\n\n $( '.remove-row' ).on('click', function() {\n $(this).parents('tr').remove();\n return false;\n });\n });\n </script>\n\n <table id=\"repeatable-fieldset-one\" width=\"100%\">\n\n <thead>\n <tr>\n <th width=\"15%\">Reward Amount</th>\n <th width=\"25%\">Reward Title</th>\n <th width=\"10%\">Shipping</th>\n <th width=\"20%\">date</th> \n <th width=\"25%\">Reward Description</th>\n <th width=\"5%\"></th> \n </tr>\n </thead>\n\n <tbody>\n\n<?php\n\n ( $reward_value );\n\n foreach ( $reward_value as $field ) {\n\n?>\n\n <tr>\n <td><input type=\"text\" class=\"widefat\" name=\"reward[]\" value=\"<?php if ( isset ( $field['reward'] ) ) echo esc_attr( $field['reward'] ); ?>\" pattern=\"[1-9]\\d*\" /></td>\n\n <td><input type=\"text\" class=\"widefat\" name=\"reward_title[]\" value=\"<?php if ( isset ( $field['reward_title'] ) ) echo esc_attr( $field['reward_title'] ); ?>\" /></td>\n\n <td>\n <select class=\"widefat\" name=\"reward_shipping[]\">\n <?php foreach ( $options as $label => $value ) : ?>\n <option value=\"<?php echo $value; ?>\"<?php selected( $field['reward_shipping'], $value ); ?>><?php echo $label; ?></option>\n <?php endforeach; ?>\n </select>\n </td>\n\n <script type=\"text/javascript\">\n jQuery(document).ready(function($){\n $('.my-custom-datepicker-field').datepicker({\n dateFormat: 'dd-mm-yy', //maybe you want something like this\n showButtonPanel: true\n });\n});\n </script>\n\n <td><input type=\"text\" name=\"_custom_datepicker[]\" id=\"_custom_datepicker[]\" class=\"my-custom-datepicker-field\" value=\"<?php echo esc_attr( $field['reward_date'] ); ?>\" /></td>\n\n <td><textarea class=\"widefat\" name=\"reward_description[]\"><?php if ( isset ( $field['reward_description'] ) ) echo esc_attr( $field['reward_description'] ); ?></textarea></td>\n\n <td><input type=\"image\" class=\"remove-row\" src=\"<?php bloginfo('template_directory'); ?>/assets/images/remove-icon.png\" alt=\"Submit\" width=\"35\" height=\"35\"></td>\n </tr>\n\n<?php } ?>\n\n <!-- empty hidden one for jQuery -->\n <tr class=\"empty-row screen-reader-text\">\n <td><input type=\"text\" class=\"widefat\" name=\"reward[]\" /></td>\n\n <td><input type=\"text\" class=\"widefat\" name=\"reward_title[]\" /></td>\n\n <td>\n <select class=\"widefat\" name=\"reward_shipping[]\">\n <?php foreach ( $options as $label => $value ) : ?>\n <option value=\"<?php echo $value; ?>\"><?php echo $label; ?></option>\n <?php endforeach; ?>\n </select>\n </td>\n\n <script type=\"text/javascript\">\n jQuery(document).ready(function($){\n $('.my-custom-datepicker-field').datepicker({\n dateFormat: 'dd-mm-yy', //maybe you want something like this\n showButtonPanel: true\n });\n});\n </script> \n\n <td><input type=\"text\" class=\"my-custom-datepicker-field\" name=\"_custom_datepicker[]\" /></td> \n\n <td><textarea class=\"widefat\" name=\"reward_description[]\" ></textarea></td>\n\n <td><input type=\"image\" class=\"remove-row\" src=\"<?php bloginfo('template_directory'); ?>/assets/images/remove-icon.png\" alt=\"Submit\" width=\"35\" height=\"35\"></td>\n </tr>\n\n </tbody>\n\n </table>\n\n <p><a id=\"add-row\" class=\"button\" href=\"#\">Add Reward</a></p>\n\n<?php \n\n}\n\nfunction save_project_reward( $post_id ) {\n\n // Check if our nonce is set.\n if ( ! isset( $_POST['project_reward_nonce'] ) ) {\n return;\n }\n\n // Verify that the nonce is valid.\n if ( ! wp_verify_nonce( $_POST['project_reward_nonce'], 'project_reward_nonce' ) ) {\n return;\n }\n\n // If this is an autosave, our form has not been submitted, so we don't want to do anything.\n if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {\n return;\n }\n\n // Check the user's permissions.\n if ( isset( $_POST['post_type'] ) && 'page' == $_POST['post_type'] ) {\n\n if ( ! current_user_can( 'edit_page', $post_id ) ) {\n return;\n }\n\n }\n else {\n\n if ( ! current_user_can( 'edit_post', $post_id ) ) {\n return;\n }\n }\n\n $reward_data = array();\n $options = project_rewards_select_options();\n\n $rewards = $_POST['reward'];\n $reward_titles = $_POST['reward_title'];\n $reward_shippings = $_POST['reward_shipping'];\n $reward_dates = $_POST['reward_date']; \n $reward_descriptions = $_POST['reward_description'];\n\n $count = count( $rewards );\n for ( $i = 0; $i < $count; $i++ ) {\n\n if ( $rewards[$i] != '' ) :\n $reward_data[$i]['reward'] = stripslashes( strip_tags( $rewards[$i] ) );\n\n if ( in_array( $reward_shippings[$i], $options ) )\n $reward_data[$i]['reward_shipping'] = stripslashes( strip_tags( $reward_shippings[$i] ) );\n else\n $reward_data[$i]['reward_shipping'] = '';\nendif;\n\n if ( $reward_titles[$i] != '' ) :\n $reward_data[$i]['reward_title'] = stripslashes( strip_tags( $reward_titles[$i] ) );\nendif;\n\n if ( $reward_descriptions[$i] != '' ) :\n $reward_data[$i]['reward_description'] = stripslashes( $reward_descriptions[$i] );\nendif;\n\n if ( $reward_descriptions[$i] != '' ) :\n $reward_data[$i]['reward_date'] = stripslashes( $reward_dates[$i] );\nendif; \n\n }\n\n update_post_meta( $post_id, '_project_rewards', $reward_data );\n\n}\n\nadd_action( 'save_post', 'save_project_reward' );\n</code></pre>\n"
}
]
| 2017/07/06 | [
"https://wordpress.stackexchange.com/questions/272525",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/113946/"
]
| I have created **Dynamic Add/Remove Custom Fields (Repeater Fields)** in my custom Post types. It is working perfectly. I want to add a new **JQuery Date Picker** field. I tried hard to create code and also searched the web but found no luck.
Plz Help me.
Following is my code.
```
function project_rewards_select_options() {
$options = array (
'Option 1' => 'Option 1',
'Option 2' => 'Option 2',
'Option 3' => 'Option 3',
);
return $options;
}
function project_reward_callback( $post ) {
wp_nonce_field( 'project_reward_nonce', 'project_reward_nonce' );
$reward_value = get_post_meta( get_the_ID(), '_project_rewards', true );
$options = project_rewards_select_options();
?>
<script type="text/javascript">
jQuery(document).ready(function( $ ){
$( '#add-row' ).on('click', function() {
var row = $( '.empty-row.screen-reader-text' ).clone(true);
row.removeClass( 'empty-row screen-reader-text' );
row.insertBefore( '#repeatable-fieldset-one tbody>tr:last' );
return false;
});
$( '.remove-row' ).on('click', function() {
$(this).parents('tr').remove();
return false;
});
});
</script>
<table id="repeatable-fieldset-one" width="100%">
<thead>
<tr>
<th width="15%">Reward Amount</th>
<th width="25%">Reward Title</th>
<th width="10%">Shipping</th>
<th width="45%">Reward Description</th>
<th width="5%"></th>
</tr>
</thead>
<tbody>
<?php
( $reward_value );
foreach ( $reward_value as $field ) {
?>
<tr>
<td><input type="text" class="widefat" name="reward[]" value="<?php if ( isset ( $field['reward'] ) ) echo esc_attr( $field['reward'] ); ?>" pattern="[1-9]\d*" /></td>
<td><input type="text" class="widefat" name="reward_title[]" value="<?php if ( isset ( $field['reward_title'] ) ) echo esc_attr( $field['reward_title'] ); ?>" /></td>
<td>
<select class="widefat" name="reward_shipping[]">
<?php foreach ( $options as $label => $value ) : ?>
<option value="<?php echo $value; ?>"<?php selected( $field['reward_shipping'], $value ); ?>><?php echo $label; ?></option>
<?php endforeach; ?>
</select>
</td>
<td><textarea class="widefat" name="reward_description[]"><?php if ( isset ( $field['reward_description'] ) ) echo esc_attr( $field['reward_description'] ); ?></textarea></td>
<td><input type="image" class="remove-row" src="<?php bloginfo('template_directory'); ?>/assets/images/remove-icon.png" alt="Submit" width="35" height="35"></td>
</tr>
<?php } ?>
<!-- empty hidden one for jQuery -->
<tr class="empty-row screen-reader-text">
<td><input type="text" class="widefat" name="reward[]" /></td>
<td><input type="text" class="widefat" name="reward_title[]" /></td>
<td>
<select class="widefat" name="reward_shipping[]">
<?php foreach ( $options as $label => $value ) : ?>
<option value="<?php echo $value; ?>"><?php echo $label; ?></option>
<?php endforeach; ?>
</select>
</td>
<td><textarea class="widefat" name="reward_description[]" ></textarea></td>
<td><input type="image" class="remove-row" src="<?php bloginfo('template_directory'); ?>/assets/images/remove-icon.png" alt="Submit" width="35" height="35"></td>
</tr>
</tbody>
</table>
<p><a id="add-row" class="button" href="#">Add Reward</a></p>
<?php
}
function save_project_reward( $post_id ) {
// Check if our nonce is set.
if ( ! isset( $_POST['project_reward_nonce'] ) ) {
return;
}
// Verify that the nonce is valid.
if ( ! wp_verify_nonce( $_POST['project_reward_nonce'], 'project_reward_nonce' ) ) {
return;
}
// If this is an autosave, our form has not been submitted, so we don't want to do anything.
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
return;
}
// Check the user's permissions.
if ( isset( $_POST['post_type'] ) && 'page' == $_POST['post_type'] ) {
if ( ! current_user_can( 'edit_page', $post_id ) ) {
return;
}
}
else {
if ( ! current_user_can( 'edit_post', $post_id ) ) {
return;
}
}
$reward_data = array();
$options = project_rewards_select_options();
$rewards = $_POST['reward'];
$reward_titles = $_POST['reward_title'];
$reward_shippings = $_POST['reward_shipping'];
$reward_descriptions = $_POST['reward_description'];
$count = count( $rewards );
for ( $i = 0; $i < $count; $i++ ) {
if ( $rewards[$i] != '' ) :
$reward_data[$i]['reward'] = stripslashes( strip_tags( $rewards[$i] ) );
if ( in_array( $reward_shippings[$i], $options ) )
$reward_data[$i]['reward_shipping'] = stripslashes( strip_tags( $reward_shippings[$i] ) );
else
$reward_data[$i]['reward_shipping'] = '';
endif;
if ( $reward_titles[$i] != '' ) :
$reward_data[$i]['reward_title'] = stripslashes( strip_tags( $reward_titles[$i] ) );
endif;
if ( $reward_descriptions[$i] != '' ) :
$reward_data[$i]['reward_description'] = stripslashes( $reward_descriptions[$i] );
endif;
}
update_post_meta( $post_id, '_project_rewards', $reward_data );
}
add_action( 'save_post', 'save_project_reward' );
``` | Wordpress has the jQuery datepicker already included. So you can enqueue the default WP script. However, as far as I know, WP doesnt include the necessary styling for the datepicker!
So try to enqueue the WP script, and for example, styles from external source:
```
function my_datepicker_enqueue() {
wp_enqueue_script( 'jquery-ui-datepicker' ); // enqueue datepicker from WP
wp_enqueue_style( 'jquery-ui-style', '//ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/base/jquery-ui.css', true);
}
add_action( 'admin_enqueue_scripts', 'my_datepicker_enqueue' );
```
Create a new HTML input field with atleast with a class and a name.
HTML of the input field: (you already have some input fields defined, so jump to the script)
```
<input type="text" name="_custom_datepicker[]" id="_custom_datepicker[]" class="my-custom-datepicker-field" value="<?php echo $your_saved_value; ?>" />
```
Than add a script to init the datepicker for our new element.
Script: (make sure that you target the right input element, we are looking at the defined class here, cause we want to use multiple instances.)
```
jQuery(document).ready(function($){
$('.my-custom-datepicker-field').datepicker({
dateFormat: 'dd-mm-yy', //maybe you want something like this
showButtonPanel: true
});
});
```
---
**Update:**
I had some problems reading your code at first, and you also have several errors in your code. First I could see the same strange behaviour. I have now setup a testplugin on a dev site, and there it is now working.
**1:** You set up your save function so that you cannot just enter a date and save.
You will have to either add a amount, title or description also, to be able to save.
I think this is intended by you?
**2:** In the save function you have the following code:
```
if ( $reward_descriptions[$i] != '' ) :
$reward_data[$i]['reward_date'] = stripslashes( $reward_dates[$i] );
endif;
```
So only when the description field is not empty the date will get saved?!
Seems this was a typo because the other fields look good.
Change to:
```
if ( $reward_data[$i] != '' ) :
$reward_data[$i]['reward_date'] = stripslashes( $reward_dates[$i] );
endif;
```
**3:** In your callback code you have these fields as datepicker fields:
```
<td><input type="text" name="_custom_datepicker[]" id="_custom_datepicker[]" class="my-custom-datepicker-field" value="<?php echo esc_attr( $field['reward_date'] ); ?>" /></td>
```
and
```
<td><input type="text" class="my-custom-datepicker-field" name="_custom_datepicker[]" /></td>
```
Both named `_custom_datepicker[]`.
But in your save function you try to save fields called `reward_date` instead.
Also the `id` should be unique. But you add the same `id` to all datefields.
You could just remove the `id` from these fields, its not needed anyway.
**4.** If you add fields dynamically like you want to, you need to change the datepicker JS function.
And instead of loading the JS code inline (and multiple times like you did), I recommend enqueuing one JS file.
So try to replace your JS code with something like this:
```
jQuery(document).ready(function($){
// your default code
$( '#add-row' ).on('click', function() {
var row = $( '.empty-row.screen-reader-text' ).clone(true);
row.removeClass( 'empty-row screen-reader-text' );
row.insertBefore( '#repeatable-fieldset-one tbody>tr:last' );
return false;
});
$( '.remove-row' ).on('click', function() {
$(this).parents('tr').remove();
return false;
});
//changed to be used on dynamic field which gets added and removed from DOM
//if the element with the class .my-custom-datepicker-field gets focus, add datepicker
$(document).on('focus', '.my-custom-datepicker-field', function(){
$(this).datepicker({
dateFormat: 'dd-mm-yy', //maybe you want something like this
showButtonPanel: true
});
});
});
```
After I fixed these things and enqueued the JS file with the code like WordPress wants it to, it is now working. |
272,526 | <p>Can anybody tell me that how to check if someone created his site using wordpress?</p>
| [
{
"answer_id": 272527,
"author": "Community",
"author_id": -1,
"author_profile": "https://wordpress.stackexchange.com/users/-1",
"pm_score": 2,
"selected": true,
"text": "<p>Yes Probably.<br>\nJust Type <code>wp-admin</code> at the end of your domain like following:</p>\n\n<pre><code>http://example.com/wp-admin\n</code></pre>\n"
},
{
"answer_id": 272528,
"author": "Patrice Poliquin",
"author_id": 32365,
"author_profile": "https://wordpress.stackexchange.com/users/32365",
"pm_score": 0,
"selected": false,
"text": "<p>Simple way to check it :</p>\n\n<ul>\n<li>As @nman said, you can try to type <code>/wp-admin</code></li>\n<li>You can open source code and search for <code>/wp-content/themes/theme_name</code></li>\n</ul>\n"
},
{
"answer_id": 272531,
"author": "Den Isahac",
"author_id": 113233,
"author_profile": "https://wordpress.stackexchange.com/users/113233",
"pm_score": 0,
"selected": false,
"text": "<h1><a href=\"https://wappalyzer.com/\" rel=\"nofollow noreferrer\"><code>Wappalyzer</code></a></h1>\n\n<blockquote>\n <p>Wappalyzer is a cross-platform utility that uncovers the technologies used on websites. It detects content management systems, ecommerce platforms, web frameworks, server software, analytics tools and many more.</p>\n</blockquote>\n\n<p>The tool is available as a browser extension.</p>\n\n<p>Though the results aren't always accurate, and since <strong>WordPress</strong> can be easily identified by scanning the <em>HTML</em> contents then <strong>99%</strong> of a time it gets <strong>WordPress</strong> easily.</p>\n"
}
]
| 2017/07/06 | [
"https://wordpress.stackexchange.com/questions/272526",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/-1/"
]
| Can anybody tell me that how to check if someone created his site using wordpress? | Yes Probably.
Just Type `wp-admin` at the end of your domain like following:
```
http://example.com/wp-admin
``` |
272,552 | <p>When a post is protected, its content looks like:</p>
<pre><code>// This content is password protected. To view it please enter your password below:
// Password: [_______________] [Enter]
</code></pre>
<p>How do I add a placeholder to that <code><input></code> tag?</p>
| [
{
"answer_id": 272553,
"author": "dodov",
"author_id": 122905,
"author_profile": "https://wordpress.stackexchange.com/users/122905",
"pm_score": 1,
"selected": false,
"text": "<p>This can be achieved via a hook, called <code>the_password_form</code>:</p>\n\n<pre><code>function my_theme_password_placeholder($output) {\n $placeholder = 'Hello!';\n $search = 'type=\"password\"';\n return str_replace($search, $search . \" placeholder=\\\"$placeholder\\\"\", $output);\n}\nadd_filter('the_password_form', 'my_theme_password_placeholder');\n</code></pre>\n\n<p>A <code>str_replace</code> searches for the string <code>type=\"password\"</code> inside the output. This gives an attribute to the <code><input></code> indicating it's of type <code>password</code>. The replacement string contains the searched one <em>plus</em> the <code>placeholder</code> attribute too.</p>\n"
},
{
"answer_id": 272560,
"author": "Rick Hellewell",
"author_id": 29416,
"author_profile": "https://wordpress.stackexchange.com/users/29416",
"pm_score": 0,
"selected": false,
"text": "<p>Assuming the password field has an 'id' value, a bit of Javascript might be better. </p>\n\n<p>The wp-admin login page uses a password id of 'user-pass', so place this in your function used with the add_filter('the_password_form', 'my_theme_password_placeholder);</p>\n\n<pre><code>function my_theme_password_placeholder() {\n?>\n<script>\ndocument.getElementById(\"password-field-id\").placeholder = \"Type password here..\"; \n</script>\n<?php \nreturn;}\n\nadd_filter('the_password_form') 'my_theme_password_placeholder');\n</code></pre>\n\n<p>This will place the <code>Type password here..</code> text inside the password field.</p>\n\n<p>This will ensure that any placeholder value is the one you set, overwriting any existing placeholder value. You could adjust the function to pass a parameter containing the string to display as a placeholder.</p>\n\n<p>Of course, if the visitor has disabled JavaScript, this won't work. But that is (IMHO) a small minority of site visitors.</p>\n"
}
]
| 2017/07/06 | [
"https://wordpress.stackexchange.com/questions/272552",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/122905/"
]
| When a post is protected, its content looks like:
```
// This content is password protected. To view it please enter your password below:
// Password: [_______________] [Enter]
```
How do I add a placeholder to that `<input>` tag? | This can be achieved via a hook, called `the_password_form`:
```
function my_theme_password_placeholder($output) {
$placeholder = 'Hello!';
$search = 'type="password"';
return str_replace($search, $search . " placeholder=\"$placeholder\"", $output);
}
add_filter('the_password_form', 'my_theme_password_placeholder');
```
A `str_replace` searches for the string `type="password"` inside the output. This gives an attribute to the `<input>` indicating it's of type `password`. The replacement string contains the searched one *plus* the `placeholder` attribute too. |
272,573 | <p>I am setting a header image as a background image to the <code>.blog__header</code> block via inline styles in functions.php:</p>
<pre><code>$header_image = get_header_image();
if ( $header_image ) {
$header_image_css = "
.blog__header {
background-image: url({$header_image});
}";
wp_add_inline_style( 'theme-styles', $header_image_css );
}
</code></pre>
<p>now I want to replace this header image with a featured image if set:</p>
<pre><code>$header_image = get_header_image();
if ( has_post_thumbnail() ) {
$post_thumbnail = get_the_post_thumbnail('full');
}
if ( $header_image ) {
$header_image_css = "
.blog__header {
background-image: url({$header_image});
}";
wp_add_inline_style( 'theme-styles', $header_image_css );
} elseif ( has_post_thumbnail() ) {
$post_thumbnail_css = "
.blog__header {
background-image: url({$post_thumbnail});
}";
wp_add_inline_style( 'theme-styles', $post_thumbnail_css );
}
</code></pre>
<p>however it doesn't work, probaly because I have not set the post ID. Any assistance would be greatly appreciated!</p>
| [
{
"answer_id": 272603,
"author": "Junaid",
"author_id": 66571,
"author_profile": "https://wordpress.stackexchange.com/users/66571",
"pm_score": 3,
"selected": true,
"text": "<p>You did not mention or shown in the code to which hook are you hooking the above code to, but here's what I think should work. NOT TESTED</p>\n\n<pre><code>global $post;\n$header_image = '';\n\n// featured image is first priority, right?\nif ( has_post_thumbnail( $post->ID ) ) {\n $header_image = get_the_post_thumbnail_url( $post->ID, 'full' );\n} elseif ( !empty( get_header_image() ) ) {\n $header_image = get_header_image();\n}\n\n$header_image_css = \".blog__header { background-image: url({$header_image}); }\";\nwp_add_inline_style( 'theme-styles', $header_image_css );\n</code></pre>\n"
},
{
"answer_id": 411443,
"author": "Alexandru C. Vernescu",
"author_id": 227690,
"author_profile": "https://wordpress.stackexchange.com/users/227690",
"pm_score": 0,
"selected": false,
"text": "<p>In my case I have added some lines in hero-header.php:</p>\n<p>old code:</p>\n<pre><code>if ( get_header_image() ) {\n?>\n<div class="<?php echo esc_attr( 'site-hero-header-image site-hero-header-image--' . Oceanly\\Helpers::hero_header_bg_position() . ' site-hero-header-image--size-' . Oceanly\\Helpers::hero_header_bg_size() . $oceanly_hero_header_bg_fixed_class ); ?>" style="background-image: url(<?php header_image(); ?>);"></div>\n<?php\n</code></pre>\n<p>}</p>\n<p>with new code added:</p>\n<pre><code> if ( get_the_post_thumbnail($post->ID , 'full') ) {\n ?>\n <div class="<?php echo esc_attr( 'site-hero-header-image site-hero-header-image--' . Oceanly\\Helpers::hero_header_bg_position() . ' site-hero-header-image--size-' . Oceanly\\Helpers::hero_header_bg_size() . $oceanly_hero_header_bg_fixed_class ); ?>" style="background-image: url(<?php the_post_thumbnail_url(); ?>);"></div>\n <?php\n} elseif ( get_header_image() ) {\n ?>\n <div class="<?php echo esc_attr( 'site-hero-header-image site-hero-header-image--' . Oceanly\\Helpers::hero_header_bg_position() . ' site-hero-header-image--size-' . Oceanly\\Helpers::hero_header_bg_size() . $oceanly_hero_header_bg_fixed_class ); ?>" style="background-image: url(<?php header_image(); ?>);"></div>\n <?php\n}\n</code></pre>\n"
}
]
| 2017/07/06 | [
"https://wordpress.stackexchange.com/questions/272573",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/103046/"
]
| I am setting a header image as a background image to the `.blog__header` block via inline styles in functions.php:
```
$header_image = get_header_image();
if ( $header_image ) {
$header_image_css = "
.blog__header {
background-image: url({$header_image});
}";
wp_add_inline_style( 'theme-styles', $header_image_css );
}
```
now I want to replace this header image with a featured image if set:
```
$header_image = get_header_image();
if ( has_post_thumbnail() ) {
$post_thumbnail = get_the_post_thumbnail('full');
}
if ( $header_image ) {
$header_image_css = "
.blog__header {
background-image: url({$header_image});
}";
wp_add_inline_style( 'theme-styles', $header_image_css );
} elseif ( has_post_thumbnail() ) {
$post_thumbnail_css = "
.blog__header {
background-image: url({$post_thumbnail});
}";
wp_add_inline_style( 'theme-styles', $post_thumbnail_css );
}
```
however it doesn't work, probaly because I have not set the post ID. Any assistance would be greatly appreciated! | You did not mention or shown in the code to which hook are you hooking the above code to, but here's what I think should work. NOT TESTED
```
global $post;
$header_image = '';
// featured image is first priority, right?
if ( has_post_thumbnail( $post->ID ) ) {
$header_image = get_the_post_thumbnail_url( $post->ID, 'full' );
} elseif ( !empty( get_header_image() ) ) {
$header_image = get_header_image();
}
$header_image_css = ".blog__header { background-image: url({$header_image}); }";
wp_add_inline_style( 'theme-styles', $header_image_css );
``` |
272,585 | <p>I have a custom post type product (wine). Each of the following is a custom taxonomy:</p>
<ul>
<li>Vintage (Year of harvesting) [only one per wine]</li>
<li>Family (Grape variety) [may be more than one]</li>
<li>Size (Bottle Size) [only one per product]</li>
</ul>
<p>In the single product view of a wine I want to do the following queries: </p>
<p>1) Find all wines which have the <strong>same family</strong>, <strong>same size</strong> but are from a <strong>different vintage</strong></p>
<p>2) Find all wines (post type: product) which are in the <strong>same family</strong> AND have the <strong>same vintage</strong> AND have a <strong>different size</strong>.</p>
<p>Now the problem: The <strong>numeric year</strong> is a custom term meta property of the <strong>vintage term</strong>. The <strong>numeric bottle size</strong> is a custom term meta property of the size term.</p>
<p>For the first query I have tried the following:</p>
<pre><code> $other_years = get_posts(array(
'post_type' => 'product',
'numberposts' => -1,
'tax_query' => array(
array(
'taxonomy' => 'family',
'field' => 'id',
'terms' => $family->term_id, // Where term_id of Term 1 is "1".
'include_children' => false
),
array(
'taxonomy' => 'size',
'field' => 'id',
'terms' => $size->term_id, // Where term_id of Term 1 is "1".
'include_children' => false
),
array(
'taxonomy' => 'vintage',
'field' => 'id',
'terms' => array($vintage->term_id), // Where term_id of Term 1 is "1".
'include_children' => false,
'operator' => 'NOT IN'
),
)
));
</code></pre>
<p><strong>It works.</strong> However: Instead of comparing the <strong><em>term_id</em></strong> (here: term id of vintage) I would like to compare if the term custom meta value (year_numeric) is different.</p>
<p>Is there any possibility to do such a query?</p>
| [
{
"answer_id": 272587,
"author": "Nick M.",
"author_id": 122778,
"author_profile": "https://wordpress.stackexchange.com/users/122778",
"pm_score": 0,
"selected": false,
"text": "<p>I believe you are checking for when a meta key does not exist. </p>\n\n<p>Please refer to this similar question: <a href=\"https://wordpress.stackexchange.com/questions/80303/query-all-posts-where-a-meta-key-does-not-exist\">query all posts where a meta key does not exist</a></p>\n"
},
{
"answer_id": 272589,
"author": "jgangso",
"author_id": 104184,
"author_profile": "https://wordpress.stackexchange.com/users/104184",
"pm_score": 4,
"selected": true,
"text": "<p>AFAIK there's no way to achieve that within a single WP_Query, so you'll have to first get a list of term_ids which have a <strong>different year</strong> than the one in question.</p>\n\n<p>I think with the following you'll come quite close. (don't have a env to test right away) </p>\n\n<pre><code>$other_years_terms = get_terms(\n 'taxonomy' => 'vintage',\n 'meta_key' => 'year_numeric',\n 'meta_value' => $the_current_wine_year, // You'll have to figure that out\n 'meta_compare' => '!=',\n 'fields' => 'ids'\n);\n\n$other_years_posts = get_posts(array(\n 'post_type' => 'product',\n 'numberposts' => -1,\n 'tax_query' => array(\n array(\n 'taxonomy' => 'family',\n 'field' => 'id',\n 'terms' => $family->term_id, // Where term_id of Term 1 is \"1\".\n 'include_children' => false\n ),\n array(\n 'taxonomy' => 'size',\n 'field' => 'id',\n 'terms' => $size->term_id, // Where term_id of Term 1 is \"1\".\n 'include_children' => false\n ),\n array(\n 'taxonomy' => 'vintage',\n 'field' => 'term_id',\n 'terms' => $other_years_terms,\n ),\n )\n ));\n</code></pre>\n"
}
]
| 2017/07/06 | [
"https://wordpress.stackexchange.com/questions/272585",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/12035/"
]
| I have a custom post type product (wine). Each of the following is a custom taxonomy:
* Vintage (Year of harvesting) [only one per wine]
* Family (Grape variety) [may be more than one]
* Size (Bottle Size) [only one per product]
In the single product view of a wine I want to do the following queries:
1) Find all wines which have the **same family**, **same size** but are from a **different vintage**
2) Find all wines (post type: product) which are in the **same family** AND have the **same vintage** AND have a **different size**.
Now the problem: The **numeric year** is a custom term meta property of the **vintage term**. The **numeric bottle size** is a custom term meta property of the size term.
For the first query I have tried the following:
```
$other_years = get_posts(array(
'post_type' => 'product',
'numberposts' => -1,
'tax_query' => array(
array(
'taxonomy' => 'family',
'field' => 'id',
'terms' => $family->term_id, // Where term_id of Term 1 is "1".
'include_children' => false
),
array(
'taxonomy' => 'size',
'field' => 'id',
'terms' => $size->term_id, // Where term_id of Term 1 is "1".
'include_children' => false
),
array(
'taxonomy' => 'vintage',
'field' => 'id',
'terms' => array($vintage->term_id), // Where term_id of Term 1 is "1".
'include_children' => false,
'operator' => 'NOT IN'
),
)
));
```
**It works.** However: Instead of comparing the ***term\_id*** (here: term id of vintage) I would like to compare if the term custom meta value (year\_numeric) is different.
Is there any possibility to do such a query? | AFAIK there's no way to achieve that within a single WP\_Query, so you'll have to first get a list of term\_ids which have a **different year** than the one in question.
I think with the following you'll come quite close. (don't have a env to test right away)
```
$other_years_terms = get_terms(
'taxonomy' => 'vintage',
'meta_key' => 'year_numeric',
'meta_value' => $the_current_wine_year, // You'll have to figure that out
'meta_compare' => '!=',
'fields' => 'ids'
);
$other_years_posts = get_posts(array(
'post_type' => 'product',
'numberposts' => -1,
'tax_query' => array(
array(
'taxonomy' => 'family',
'field' => 'id',
'terms' => $family->term_id, // Where term_id of Term 1 is "1".
'include_children' => false
),
array(
'taxonomy' => 'size',
'field' => 'id',
'terms' => $size->term_id, // Where term_id of Term 1 is "1".
'include_children' => false
),
array(
'taxonomy' => 'vintage',
'field' => 'term_id',
'terms' => $other_years_terms,
),
)
));
``` |
272,613 | <p>I'm trying to create a page on WordPress with a grid which contains al my posts. </p>
<p>The grid works well until when I add the <code>the_excerpt();</code> for my post. The grid became a mess. The rows are not correct anymore. </p>
<p>This is what I have without <code>the_excerpt();</code>:</p>
<p><a href="https://i.stack.imgur.com/cGyA5.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/cGyA5.png" alt="enter image description here"></a></p>
<p>and this is what happens with <code>the_excerpt();</code>:</p>
<p><a href="https://i.stack.imgur.com/WxXGq.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WxXGq.png" alt="enter image description here"></a></p>
<p>Here my code of page-post.php:</p>
<pre><code><?php /* Template Name: Blog-3 */ ?>
<?php get_header(); ?>
<div>
<div class="container">
<?php query_posts('post_type=post&post_status=publish&posts_per_page=10&paged='. get_query_var('paged')); ?>
<div class="row">
<?php if( have_posts() ): ?>
<?php while( have_posts() ): the_post(); ?>
<div class="col-sm-6" style="margin-bottom: 65px;">
<p>
<?php if ( has_post_thumbnail() ) : ?>
<a href="<?php the_permalink(); ?>"><?php the_post_thumbnail( 'large' ); ?></a>
<?php endif; ?>
</p>
<h3><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3>
<p>Posted on <?php echo the_time('F jS, Y');?> by <?php the_author_posts_link(); ?> </p>
<?php the_excerpt(); ?>
</div><!-- col -->
<?php endwhile; ?>
</div><!-- row -->
</div><!-- container -->
<div>
<span><?php previous_posts_link(__('« Newer','example')) ?></span> <span class="older"><?php next_posts_link(__('Older »','example')) ?></span>
</div><!-- /.navigation -->
<?php else: ?>
<div id="post-404">
<p><?php _e('None found.','example'); ?></p>
</div><!-- /#post-404 -->
<?php endif; wp_reset_query(); ?>
</div><!-- /#content -->
<?php get_sidebar();
get_footer();?>
</code></pre>
| [
{
"answer_id": 272615,
"author": "Kieran McClung",
"author_id": 52293,
"author_profile": "https://wordpress.stackexchange.com/users/52293",
"pm_score": 2,
"selected": false,
"text": "<p>The way I tackle this issue is by closing the row every <em>nth</em> column, like so. You basically collect the total number of posts in the current loop then at the end of each loop, increment <code>$i</code> and check whether it's divisible by two wholly (I'm rubbish at explaining this part).</p>\n\n<p>Example: You could tweak this to <code>if ( $i % 3 == 0 )</code> if you were wanting rows of 3.</p>\n\n<p>The example below can replace your entire container.</p>\n\n<pre><code><div class=\"container\">\n\n <?php query_posts('post_type=post&post_status=publish&posts_per_page=10&paged='. get_query_var('paged')); ?>\n\n <?php \n // Get total posts\n $total = $wp_query->post_count;\n\n // Set indicator to 0;\n $i = 0;\n ?>\n\n <?php while( have_posts() ): the_post(); ?>\n\n <?php if ( $i == 0 ) echo '<div class=\"row\">'; ?>\n\n <div class=\"col-sm-6\" style=\"margin-bottom: 65px;\">\n\n <p>\n <?php if ( has_post_thumbnail() ) : ?>\n <a href=\"<?php the_permalink(); ?>\"><?php the_post_thumbnail( 'large' ); ?></a>\n <?php endif; ?>\n </p>\n\n <h3><a href=\"<?php the_permalink(); ?>\"><?php the_title(); ?></a></h3>\n\n <p>Posted on <?php echo the_time('F jS, Y');?> by <?php the_author_posts_link(); ?> </p>\n\n <?php the_excerpt(); ?>\n\n </div><!-- col -->\n\n <?php $i++; ?>\n\n <?php\n // if we're at the end close the row\n if ( $i == $total ) { \n echo '</div>';\n } else {\n /** \n * Perform modulus calculation to check whether $i / 2 is whole number\n * if true close row and open a new one\n */\n if ( $i % 2 == 0 ) {\n echo '</div><div class=\"row\">';\n }\n }\n ?>\n\n <?php endwhile; ?>\n\n</div><!-- container -->\n</code></pre>\n"
},
{
"answer_id": 321509,
"author": "solosik",
"author_id": 45301,
"author_profile": "https://wordpress.stackexchange.com/users/45301",
"pm_score": 0,
"selected": false,
"text": "<p>Just to mention, that since Bootstrap 4, you may use <strong>Cards columns</strong>.</p>\n\n<p><a href=\"https://getbootstrap.com/docs/4.0/components/card/#card-columns\" rel=\"nofollow noreferrer\">You can check it here.</a></p>\n\n<blockquote>\n <p>Cards can be organized into Masonry-like columns with just CSS by\n wrapping them in <code>.card-columns</code>.</p>\n</blockquote>\n\n<pre><code><div class=\"card-columns\">\n <div class=\"card\">...</div>\n <div class=\"card\">...</div>\n ...\n</div>\n</code></pre>\n"
}
]
| 2017/07/07 | [
"https://wordpress.stackexchange.com/questions/272613",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/107597/"
]
| I'm trying to create a page on WordPress with a grid which contains al my posts.
The grid works well until when I add the `the_excerpt();` for my post. The grid became a mess. The rows are not correct anymore.
This is what I have without `the_excerpt();`:
[](https://i.stack.imgur.com/cGyA5.png)
and this is what happens with `the_excerpt();`:
[](https://i.stack.imgur.com/WxXGq.png)
Here my code of page-post.php:
```
<?php /* Template Name: Blog-3 */ ?>
<?php get_header(); ?>
<div>
<div class="container">
<?php query_posts('post_type=post&post_status=publish&posts_per_page=10&paged='. get_query_var('paged')); ?>
<div class="row">
<?php if( have_posts() ): ?>
<?php while( have_posts() ): the_post(); ?>
<div class="col-sm-6" style="margin-bottom: 65px;">
<p>
<?php if ( has_post_thumbnail() ) : ?>
<a href="<?php the_permalink(); ?>"><?php the_post_thumbnail( 'large' ); ?></a>
<?php endif; ?>
</p>
<h3><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3>
<p>Posted on <?php echo the_time('F jS, Y');?> by <?php the_author_posts_link(); ?> </p>
<?php the_excerpt(); ?>
</div><!-- col -->
<?php endwhile; ?>
</div><!-- row -->
</div><!-- container -->
<div>
<span><?php previous_posts_link(__('« Newer','example')) ?></span> <span class="older"><?php next_posts_link(__('Older »','example')) ?></span>
</div><!-- /.navigation -->
<?php else: ?>
<div id="post-404">
<p><?php _e('None found.','example'); ?></p>
</div><!-- /#post-404 -->
<?php endif; wp_reset_query(); ?>
</div><!-- /#content -->
<?php get_sidebar();
get_footer();?>
``` | The way I tackle this issue is by closing the row every *nth* column, like so. You basically collect the total number of posts in the current loop then at the end of each loop, increment `$i` and check whether it's divisible by two wholly (I'm rubbish at explaining this part).
Example: You could tweak this to `if ( $i % 3 == 0 )` if you were wanting rows of 3.
The example below can replace your entire container.
```
<div class="container">
<?php query_posts('post_type=post&post_status=publish&posts_per_page=10&paged='. get_query_var('paged')); ?>
<?php
// Get total posts
$total = $wp_query->post_count;
// Set indicator to 0;
$i = 0;
?>
<?php while( have_posts() ): the_post(); ?>
<?php if ( $i == 0 ) echo '<div class="row">'; ?>
<div class="col-sm-6" style="margin-bottom: 65px;">
<p>
<?php if ( has_post_thumbnail() ) : ?>
<a href="<?php the_permalink(); ?>"><?php the_post_thumbnail( 'large' ); ?></a>
<?php endif; ?>
</p>
<h3><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3>
<p>Posted on <?php echo the_time('F jS, Y');?> by <?php the_author_posts_link(); ?> </p>
<?php the_excerpt(); ?>
</div><!-- col -->
<?php $i++; ?>
<?php
// if we're at the end close the row
if ( $i == $total ) {
echo '</div>';
} else {
/**
* Perform modulus calculation to check whether $i / 2 is whole number
* if true close row and open a new one
*/
if ( $i % 2 == 0 ) {
echo '</div><div class="row">';
}
}
?>
<?php endwhile; ?>
</div><!-- container -->
``` |
272,619 | <p>I'm trying to get a list/count of products who's has a specific attribute and value. Products are managed and setup using the WooCommerce plugin.</p>
<p>Each product has the same variation set, the product is assigned to a category, I need to retrieve only product with a specific attribute i.e "newyork" and the stock quantity that is less than i.e "20"</p>
<p>Each product variation is set to Managed stock, but not the product itself hope that makes sense. My issue at the moment is the WordPress query I have is not checking the variation name or stock at all. </p>
<p>Any help would be appreciated. </p>
<pre><code><?php
$args= array(
'post_type' => array('product', 'product_variation'),
'post_status' => 'publish',
'posts_per_page' => -1,
'meta_query' => array(
array(
'key' => '_stock',
'value' => 20,
'compare' => '<'
)
),
'tax_query' => array(
array(
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => array('cat1', 'cat2', 'cat3'),
'operator' => 'IN',
),
array(
'taxonomy' => 'pa_regions',
'field' => 'slug',
'terms' => 'newyork',
'operator' => 'IN'
),
)
);
$loop = new WP_Query($args);
$post_count = array();
while($loop->have_posts()) : $loop->the_post();
global $product; ?>
<pre style="background: #1c1c1b; color: #f7e700">
<?php $post_count[] = $product->ID ;?>
</pre>
<?php endwhile; ?>
$total = count($post_count);
</code></pre>
| [
{
"answer_id": 291998,
"author": "Minh Dao",
"author_id": 135439,
"author_profile": "https://wordpress.stackexchange.com/users/135439",
"pm_score": -1,
"selected": false,
"text": "<p>I think you has a proble on 'tax_query'.\nIf you want you query array on 'tax_query', you need flown on format <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Taxonomy_Parameters\" rel=\"nofollow noreferrer\">wordpress</a> </p>\n\n<p>And short explain for you:\nin 'tax_query' need 'relation':</p>\n\n<pre><code> 'tax_query' => array(\n 'relation'=>'AND', // 'AND' 'OR' ...\n array(\n 'taxonomy' => 'product_cat',\n 'field' => 'slug',\n 'terms' => array('cat1', 'cat2', 'cat3'),\n 'operator' => 'IN',\n ),\n array(\n 'taxonomy' => 'pa_regions',\n 'field' => 'slug',\n 'terms' => 'newyork',\n 'operator' => 'IN'\n )\n</code></pre>\n"
},
{
"answer_id": 301901,
"author": "Adrian",
"author_id": 63481,
"author_profile": "https://wordpress.stackexchange.com/users/63481",
"pm_score": 3,
"selected": false,
"text": "<p>You should use <a href=\"https://github.com/woocommerce/woocommerce/wiki/wc_get_products-and-WC_Product_Query#adding-custom-parameter-support\" rel=\"nofollow noreferrer\">wc_get_products and a custom filter</a> for adding your specific query.</p>\n<p><strong>Example</strong></p>\n<p>I want to find products containing a specific attribute value "table-filter".</p>\n<pre><code> $args = array(\n 'table-filter' => array(1,2,3)\n );\n $products = wc_get_products($args);\n</code></pre>\n<p>Than I have a filter for this:</p>\n<pre><code>add_filter('woocommerce_product_data_store_cpt_get_products_query', 'my_handle_custom_query_var', 10, 2);\n\nfunction my_handle_custom_query_var($query, $query_vars) {\n if (!empty($query_vars['table-filter'])) {\n $query['tax_query'][] = array(\n 'taxonomy' => 'pa_table-filter',\n 'field' => 'term_id', //default\n 'terms' => $query_vars['table-filter'],\n 'operator' => 'IN',\n );\n }\n return $query;\n}\n</code></pre>\n<p><strong>Hint:</strong> The generated attribute taxonomy from WooCommerce is always prefixed with "pa_", so if you attributes slug is "table-filter", the taxonomy will be "pa_table-filter".</p>\n"
}
]
| 2017/07/07 | [
"https://wordpress.stackexchange.com/questions/272619",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/120173/"
]
| I'm trying to get a list/count of products who's has a specific attribute and value. Products are managed and setup using the WooCommerce plugin.
Each product has the same variation set, the product is assigned to a category, I need to retrieve only product with a specific attribute i.e "newyork" and the stock quantity that is less than i.e "20"
Each product variation is set to Managed stock, but not the product itself hope that makes sense. My issue at the moment is the WordPress query I have is not checking the variation name or stock at all.
Any help would be appreciated.
```
<?php
$args= array(
'post_type' => array('product', 'product_variation'),
'post_status' => 'publish',
'posts_per_page' => -1,
'meta_query' => array(
array(
'key' => '_stock',
'value' => 20,
'compare' => '<'
)
),
'tax_query' => array(
array(
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => array('cat1', 'cat2', 'cat3'),
'operator' => 'IN',
),
array(
'taxonomy' => 'pa_regions',
'field' => 'slug',
'terms' => 'newyork',
'operator' => 'IN'
),
)
);
$loop = new WP_Query($args);
$post_count = array();
while($loop->have_posts()) : $loop->the_post();
global $product; ?>
<pre style="background: #1c1c1b; color: #f7e700">
<?php $post_count[] = $product->ID ;?>
</pre>
<?php endwhile; ?>
$total = count($post_count);
``` | You should use [wc\_get\_products and a custom filter](https://github.com/woocommerce/woocommerce/wiki/wc_get_products-and-WC_Product_Query#adding-custom-parameter-support) for adding your specific query.
**Example**
I want to find products containing a specific attribute value "table-filter".
```
$args = array(
'table-filter' => array(1,2,3)
);
$products = wc_get_products($args);
```
Than I have a filter for this:
```
add_filter('woocommerce_product_data_store_cpt_get_products_query', 'my_handle_custom_query_var', 10, 2);
function my_handle_custom_query_var($query, $query_vars) {
if (!empty($query_vars['table-filter'])) {
$query['tax_query'][] = array(
'taxonomy' => 'pa_table-filter',
'field' => 'term_id', //default
'terms' => $query_vars['table-filter'],
'operator' => 'IN',
);
}
return $query;
}
```
**Hint:** The generated attribute taxonomy from WooCommerce is always prefixed with "pa\_", so if you attributes slug is "table-filter", the taxonomy will be "pa\_table-filter". |
272,620 | <p>I want disable one specific page of the default css, and i want use my css on the specific page. I don't know it is posibble?</p>
<p>I use Blank State plugin, for create blank page, but css its on the blank pages, but i want my css use on the specific blank pages.</p>
<p><a href="https://wordpress.org/plugins/blank-slate/" rel="nofollow noreferrer">https://wordpress.org/plugins/blank-slate/</a></p>
<p>So, i have one page, that name: test-area-7
Code:</p>
<pre><code>add_action('wp_enqueue_scripts', 'my_script', 99);
function my_script()
{
if(is_page( 'test-area-7' )){
wp_dequeue_script('fpw_styles_css');
}
}
</code></pre>
<p>EDITED</p>
<pre><code> add_action('wp_enqueue_scripts', 'my_script', 99);
function my_script()
{
if(is_page( 'test-area-7' )){
wp_dequeue_script('/wp-content/themes/colormag/style.css');
}
}
</code></pre>
| [
{
"answer_id": 291998,
"author": "Minh Dao",
"author_id": 135439,
"author_profile": "https://wordpress.stackexchange.com/users/135439",
"pm_score": -1,
"selected": false,
"text": "<p>I think you has a proble on 'tax_query'.\nIf you want you query array on 'tax_query', you need flown on format <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Taxonomy_Parameters\" rel=\"nofollow noreferrer\">wordpress</a> </p>\n\n<p>And short explain for you:\nin 'tax_query' need 'relation':</p>\n\n<pre><code> 'tax_query' => array(\n 'relation'=>'AND', // 'AND' 'OR' ...\n array(\n 'taxonomy' => 'product_cat',\n 'field' => 'slug',\n 'terms' => array('cat1', 'cat2', 'cat3'),\n 'operator' => 'IN',\n ),\n array(\n 'taxonomy' => 'pa_regions',\n 'field' => 'slug',\n 'terms' => 'newyork',\n 'operator' => 'IN'\n )\n</code></pre>\n"
},
{
"answer_id": 301901,
"author": "Adrian",
"author_id": 63481,
"author_profile": "https://wordpress.stackexchange.com/users/63481",
"pm_score": 3,
"selected": false,
"text": "<p>You should use <a href=\"https://github.com/woocommerce/woocommerce/wiki/wc_get_products-and-WC_Product_Query#adding-custom-parameter-support\" rel=\"nofollow noreferrer\">wc_get_products and a custom filter</a> for adding your specific query.</p>\n<p><strong>Example</strong></p>\n<p>I want to find products containing a specific attribute value "table-filter".</p>\n<pre><code> $args = array(\n 'table-filter' => array(1,2,3)\n );\n $products = wc_get_products($args);\n</code></pre>\n<p>Than I have a filter for this:</p>\n<pre><code>add_filter('woocommerce_product_data_store_cpt_get_products_query', 'my_handle_custom_query_var', 10, 2);\n\nfunction my_handle_custom_query_var($query, $query_vars) {\n if (!empty($query_vars['table-filter'])) {\n $query['tax_query'][] = array(\n 'taxonomy' => 'pa_table-filter',\n 'field' => 'term_id', //default\n 'terms' => $query_vars['table-filter'],\n 'operator' => 'IN',\n );\n }\n return $query;\n}\n</code></pre>\n<p><strong>Hint:</strong> The generated attribute taxonomy from WooCommerce is always prefixed with "pa_", so if you attributes slug is "table-filter", the taxonomy will be "pa_table-filter".</p>\n"
}
]
| 2017/07/07 | [
"https://wordpress.stackexchange.com/questions/272620",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/123365/"
]
| I want disable one specific page of the default css, and i want use my css on the specific page. I don't know it is posibble?
I use Blank State plugin, for create blank page, but css its on the blank pages, but i want my css use on the specific blank pages.
<https://wordpress.org/plugins/blank-slate/>
So, i have one page, that name: test-area-7
Code:
```
add_action('wp_enqueue_scripts', 'my_script', 99);
function my_script()
{
if(is_page( 'test-area-7' )){
wp_dequeue_script('fpw_styles_css');
}
}
```
EDITED
```
add_action('wp_enqueue_scripts', 'my_script', 99);
function my_script()
{
if(is_page( 'test-area-7' )){
wp_dequeue_script('/wp-content/themes/colormag/style.css');
}
}
``` | You should use [wc\_get\_products and a custom filter](https://github.com/woocommerce/woocommerce/wiki/wc_get_products-and-WC_Product_Query#adding-custom-parameter-support) for adding your specific query.
**Example**
I want to find products containing a specific attribute value "table-filter".
```
$args = array(
'table-filter' => array(1,2,3)
);
$products = wc_get_products($args);
```
Than I have a filter for this:
```
add_filter('woocommerce_product_data_store_cpt_get_products_query', 'my_handle_custom_query_var', 10, 2);
function my_handle_custom_query_var($query, $query_vars) {
if (!empty($query_vars['table-filter'])) {
$query['tax_query'][] = array(
'taxonomy' => 'pa_table-filter',
'field' => 'term_id', //default
'terms' => $query_vars['table-filter'],
'operator' => 'IN',
);
}
return $query;
}
```
**Hint:** The generated attribute taxonomy from WooCommerce is always prefixed with "pa\_", so if you attributes slug is "table-filter", the taxonomy will be "pa\_table-filter". |
272,659 | <p>I am trying to write a simple plugin that fetches some data from an API endpoint. I am planning to read the api key from a shortcode, but didn't get that far yet.</p>
<p>I wrote the following piece of code. The noob question I have is how do I even trigger the code so that I could debug it to see what happens ?</p>
<p>If that's a simple question, the follow up would be how to read the api key from a shortcode? </p>
<pre><code>class DATA_PARSING
{
private static $instance;
/**
* Initializes the plugin and read some data
*
* @access private
*/
private function __construct()
{
add_action('data', [$this, 'fetchData']);
}
/**
* Creates an instance of this class
*
* @access public
* @return DATA_PARSING An instance of this class
*/
public function get_instance()
{
if (null == self::$instance) {
self::$instance = new self;
}
return self::$instance;
}
private function fetchData($apiKey)
{
$url = 'https://api.website.com/data';
$args = [
'id' => 1234,
'fields' => '*'
];
$method = 'GET';
$headers = array(
'Authorization' => 'Bearer ' . $apiKey,
'Accept' => 'application/vnd.website.v1+json',
'content-type' => 'application/json',
);
$request = array(
'headers' => $headers,
'method' => $method,
);
if ($method == 'GET' && !empty($args) && is_array($args)) {
$url = add_query_arg($args, $url);
} else {
$request['body'] = json_encode($args);
}
$response = wp_remote_request($url, $request);
try {
$json = json_decode($response['body']);
} catch (Exception $e) {
$json = null;
}
return $json;
}
}
</code></pre>
| [
{
"answer_id": 291998,
"author": "Minh Dao",
"author_id": 135439,
"author_profile": "https://wordpress.stackexchange.com/users/135439",
"pm_score": -1,
"selected": false,
"text": "<p>I think you has a proble on 'tax_query'.\nIf you want you query array on 'tax_query', you need flown on format <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Taxonomy_Parameters\" rel=\"nofollow noreferrer\">wordpress</a> </p>\n\n<p>And short explain for you:\nin 'tax_query' need 'relation':</p>\n\n<pre><code> 'tax_query' => array(\n 'relation'=>'AND', // 'AND' 'OR' ...\n array(\n 'taxonomy' => 'product_cat',\n 'field' => 'slug',\n 'terms' => array('cat1', 'cat2', 'cat3'),\n 'operator' => 'IN',\n ),\n array(\n 'taxonomy' => 'pa_regions',\n 'field' => 'slug',\n 'terms' => 'newyork',\n 'operator' => 'IN'\n )\n</code></pre>\n"
},
{
"answer_id": 301901,
"author": "Adrian",
"author_id": 63481,
"author_profile": "https://wordpress.stackexchange.com/users/63481",
"pm_score": 3,
"selected": false,
"text": "<p>You should use <a href=\"https://github.com/woocommerce/woocommerce/wiki/wc_get_products-and-WC_Product_Query#adding-custom-parameter-support\" rel=\"nofollow noreferrer\">wc_get_products and a custom filter</a> for adding your specific query.</p>\n<p><strong>Example</strong></p>\n<p>I want to find products containing a specific attribute value "table-filter".</p>\n<pre><code> $args = array(\n 'table-filter' => array(1,2,3)\n );\n $products = wc_get_products($args);\n</code></pre>\n<p>Than I have a filter for this:</p>\n<pre><code>add_filter('woocommerce_product_data_store_cpt_get_products_query', 'my_handle_custom_query_var', 10, 2);\n\nfunction my_handle_custom_query_var($query, $query_vars) {\n if (!empty($query_vars['table-filter'])) {\n $query['tax_query'][] = array(\n 'taxonomy' => 'pa_table-filter',\n 'field' => 'term_id', //default\n 'terms' => $query_vars['table-filter'],\n 'operator' => 'IN',\n );\n }\n return $query;\n}\n</code></pre>\n<p><strong>Hint:</strong> The generated attribute taxonomy from WooCommerce is always prefixed with "pa_", so if you attributes slug is "table-filter", the taxonomy will be "pa_table-filter".</p>\n"
}
]
| 2017/07/07 | [
"https://wordpress.stackexchange.com/questions/272659",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/123390/"
]
| I am trying to write a simple plugin that fetches some data from an API endpoint. I am planning to read the api key from a shortcode, but didn't get that far yet.
I wrote the following piece of code. The noob question I have is how do I even trigger the code so that I could debug it to see what happens ?
If that's a simple question, the follow up would be how to read the api key from a shortcode?
```
class DATA_PARSING
{
private static $instance;
/**
* Initializes the plugin and read some data
*
* @access private
*/
private function __construct()
{
add_action('data', [$this, 'fetchData']);
}
/**
* Creates an instance of this class
*
* @access public
* @return DATA_PARSING An instance of this class
*/
public function get_instance()
{
if (null == self::$instance) {
self::$instance = new self;
}
return self::$instance;
}
private function fetchData($apiKey)
{
$url = 'https://api.website.com/data';
$args = [
'id' => 1234,
'fields' => '*'
];
$method = 'GET';
$headers = array(
'Authorization' => 'Bearer ' . $apiKey,
'Accept' => 'application/vnd.website.v1+json',
'content-type' => 'application/json',
);
$request = array(
'headers' => $headers,
'method' => $method,
);
if ($method == 'GET' && !empty($args) && is_array($args)) {
$url = add_query_arg($args, $url);
} else {
$request['body'] = json_encode($args);
}
$response = wp_remote_request($url, $request);
try {
$json = json_decode($response['body']);
} catch (Exception $e) {
$json = null;
}
return $json;
}
}
``` | You should use [wc\_get\_products and a custom filter](https://github.com/woocommerce/woocommerce/wiki/wc_get_products-and-WC_Product_Query#adding-custom-parameter-support) for adding your specific query.
**Example**
I want to find products containing a specific attribute value "table-filter".
```
$args = array(
'table-filter' => array(1,2,3)
);
$products = wc_get_products($args);
```
Than I have a filter for this:
```
add_filter('woocommerce_product_data_store_cpt_get_products_query', 'my_handle_custom_query_var', 10, 2);
function my_handle_custom_query_var($query, $query_vars) {
if (!empty($query_vars['table-filter'])) {
$query['tax_query'][] = array(
'taxonomy' => 'pa_table-filter',
'field' => 'term_id', //default
'terms' => $query_vars['table-filter'],
'operator' => 'IN',
);
}
return $query;
}
```
**Hint:** The generated attribute taxonomy from WooCommerce is always prefixed with "pa\_", so if you attributes slug is "table-filter", the taxonomy will be "pa\_table-filter". |
272,675 | <p>I am working on a WordPress theme offline in localhost It's a blog theme: <a href="http://preview.themeforest.net/item/paperback-magazine-wordpress-theme/full_screen_preview/13511026" rel="nofollow noreferrer">http://preview.themeforest.net/item/paperback-magazine-wordpress-theme/full_screen_preview/13511026</a> . I need to create a profile header in such a way that these writers would be able to put in their bio, a background picture, profile picture and links to their social networks. Something similar to this:</p>
<p><a href="http://thoughtcatalog.com/rania-naim/" rel="nofollow noreferrer">http://thoughtcatalog.com/rania-naim/</a> </p>
<p>I am just starting out theme development and don't know my way around this. Will be grateful for any help. Thanks</p>
| [
{
"answer_id": 291998,
"author": "Minh Dao",
"author_id": 135439,
"author_profile": "https://wordpress.stackexchange.com/users/135439",
"pm_score": -1,
"selected": false,
"text": "<p>I think you has a proble on 'tax_query'.\nIf you want you query array on 'tax_query', you need flown on format <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Taxonomy_Parameters\" rel=\"nofollow noreferrer\">wordpress</a> </p>\n\n<p>And short explain for you:\nin 'tax_query' need 'relation':</p>\n\n<pre><code> 'tax_query' => array(\n 'relation'=>'AND', // 'AND' 'OR' ...\n array(\n 'taxonomy' => 'product_cat',\n 'field' => 'slug',\n 'terms' => array('cat1', 'cat2', 'cat3'),\n 'operator' => 'IN',\n ),\n array(\n 'taxonomy' => 'pa_regions',\n 'field' => 'slug',\n 'terms' => 'newyork',\n 'operator' => 'IN'\n )\n</code></pre>\n"
},
{
"answer_id": 301901,
"author": "Adrian",
"author_id": 63481,
"author_profile": "https://wordpress.stackexchange.com/users/63481",
"pm_score": 3,
"selected": false,
"text": "<p>You should use <a href=\"https://github.com/woocommerce/woocommerce/wiki/wc_get_products-and-WC_Product_Query#adding-custom-parameter-support\" rel=\"nofollow noreferrer\">wc_get_products and a custom filter</a> for adding your specific query.</p>\n<p><strong>Example</strong></p>\n<p>I want to find products containing a specific attribute value "table-filter".</p>\n<pre><code> $args = array(\n 'table-filter' => array(1,2,3)\n );\n $products = wc_get_products($args);\n</code></pre>\n<p>Than I have a filter for this:</p>\n<pre><code>add_filter('woocommerce_product_data_store_cpt_get_products_query', 'my_handle_custom_query_var', 10, 2);\n\nfunction my_handle_custom_query_var($query, $query_vars) {\n if (!empty($query_vars['table-filter'])) {\n $query['tax_query'][] = array(\n 'taxonomy' => 'pa_table-filter',\n 'field' => 'term_id', //default\n 'terms' => $query_vars['table-filter'],\n 'operator' => 'IN',\n );\n }\n return $query;\n}\n</code></pre>\n<p><strong>Hint:</strong> The generated attribute taxonomy from WooCommerce is always prefixed with "pa_", so if you attributes slug is "table-filter", the taxonomy will be "pa_table-filter".</p>\n"
}
]
| 2017/07/07 | [
"https://wordpress.stackexchange.com/questions/272675",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/119981/"
]
| I am working on a WordPress theme offline in localhost It's a blog theme: <http://preview.themeforest.net/item/paperback-magazine-wordpress-theme/full_screen_preview/13511026> . I need to create a profile header in such a way that these writers would be able to put in their bio, a background picture, profile picture and links to their social networks. Something similar to this:
<http://thoughtcatalog.com/rania-naim/>
I am just starting out theme development and don't know my way around this. Will be grateful for any help. Thanks | You should use [wc\_get\_products and a custom filter](https://github.com/woocommerce/woocommerce/wiki/wc_get_products-and-WC_Product_Query#adding-custom-parameter-support) for adding your specific query.
**Example**
I want to find products containing a specific attribute value "table-filter".
```
$args = array(
'table-filter' => array(1,2,3)
);
$products = wc_get_products($args);
```
Than I have a filter for this:
```
add_filter('woocommerce_product_data_store_cpt_get_products_query', 'my_handle_custom_query_var', 10, 2);
function my_handle_custom_query_var($query, $query_vars) {
if (!empty($query_vars['table-filter'])) {
$query['tax_query'][] = array(
'taxonomy' => 'pa_table-filter',
'field' => 'term_id', //default
'terms' => $query_vars['table-filter'],
'operator' => 'IN',
);
}
return $query;
}
```
**Hint:** The generated attribute taxonomy from WooCommerce is always prefixed with "pa\_", so if you attributes slug is "table-filter", the taxonomy will be "pa\_table-filter". |
272,682 | <p>A client is using the WordPress REST JSON API with some WordPress data models. We need to hit the WordPress API from the frontend and retreive a few hundred custom posts.</p>
<p>Wordpress has a <a href="https://developer.wordpress.org/reference/classes/wp_rest_controller/get_collection_params/" rel="nofollow noreferrer">hard limit of 100 custom posts</a>.</p>
<p>I would like to change this limit to a much higher number for this use case. I read that you cannot monkey patch in PHP. </p>
<p>Is there any way to adjust the <code>per_page->maximum</code> value to, say, 10000?</p>
| [
{
"answer_id": 272724,
"author": "kero",
"author_id": 108180,
"author_profile": "https://wordpress.stackexchange.com/users/108180",
"pm_score": 1,
"selected": false,
"text": "<p>You cannot get over that limit of 100 posts per requests in WordPress for default requests. One way to still retrieve all posts would be to query that interface until you have all posts. Another would be a custom endpoint.</p>\n\n<p>If you can, I suggest creating your own REST endpoint. This will already work and return all posts</p>\n\n<pre><code>add_action('rest_api_init', 'my_more_posts');\n\nfunction my_more_posts() {\n register_rest_route('myplugin/v1', '/myposts', array(\n 'methods' => 'GET',\n 'callback' => 'my_more_posts_callback',\n ));\n}\n\nfunction my_more_posts_callback( WP_REST_Request $request ) {\n $args = array(\n 'posts_per_page' => -1,\n );\n return get_posts($args);\n}\n</code></pre>\n\n<p>More info on <a href=\"https://developer.wordpress.org/rest-api/extending-the-rest-api/adding-custom-endpoints/\" rel=\"nofollow noreferrer\">creating your own endpoint can be found here</a>, whereas the <a href=\"https://codex.wordpress.org/Template_Tags/get_posts\" rel=\"nofollow noreferrer\">arguments of <code>get_posts()</code> are explained here</a>.</p>\n\n<hr>\n\n<p>For a pure JavaScript solution in the frontend, you can utilize the <code>x-wp-totalpages</code> header which tells the total amount of pages. Unless this page is reached, we know we need to query again. So a basic recursive version like this works:</p>\n\n<pre><code>var allPosts = [];\n\nfunction retrievePosts(opt) {\n if (typeof opt === 'undefined')\n opt = {};\n\n var options = $.extend({\n per_page: 100,\n page: 1\n }, opt);\n var url = 'https://example.com/wp-json/wp/v2/posts';\n var uri = url + '?per_page=' + options.per_page + '&page=' + options.page;\n\n $.getJSON(uri, function(data, status, jqXHR) {\n var totalpages = jqXHR.getResponseHeader('x-wp-totalpages');\n\n allPosts = allPosts.concat( data );\n\n // here the magic happens\n // if we are not done\n if (options.page < totalpages) {\n // request again, but for the next page\n retrievePosts({\n per_page: options.per_page,\n page: options.page + 1\n });\n } else {\n\n // WE ARE DONE\n // posts are in allPosts\n\n }\n });\n};\nretrievePosts();\n</code></pre>\n"
},
{
"answer_id": 372436,
"author": "Nabil Freeman",
"author_id": 192716,
"author_profile": "https://wordpress.stackexchange.com/users/192716",
"pm_score": 0,
"selected": false,
"text": "<p>This is still a problem in 2020, so I just edited the Wordpress source code on our server.</p>\n<p><a href=\"https://core.trac.wordpress.org/browser/trunk/src/wp-includes/rest-api/endpoints/class-wp-rest-controller.php\" rel=\"nofollow noreferrer\">https://core.trac.wordpress.org/browser/trunk/src/wp-includes/rest-api/endpoints/class-wp-rest-controller.php</a></p>\n<p>In this file if you search for "100" you can easily find the configuration. I changed mine to 500.</p>\n<p>I think Wordpress are right that this can cause front-end speed issues, but for those of us running Wordpress as a headless CMS to render another app (static site in our case) this is really annoying that you can't easily edit it.</p>\n"
},
{
"answer_id": 388576,
"author": "Jake Gillikin",
"author_id": 206749,
"author_profile": "https://wordpress.stackexchange.com/users/206749",
"pm_score": 0,
"selected": false,
"text": "<p>There is a hook that can manipulate the per page maximum. The dynamic portion of the hook name, $post_type, refers to the post type slug</p>\n<pre class=\"lang-js prettyprint-override\"><code>function increase_per_page_max($params){\n $params['per_page']['maximum'] = 1000;\n return $params;\n}\n\nadd_filter('rest_{$post_type}_collection_params', 'increase_per_page_max');\n</code></pre>\n<p>Credit to <a href=\"https://wildwolf.name/how-to-increase-per_page-limit-in-wordpress-rest-api/\" rel=\"nofollow noreferrer\">https://wildwolf.name/how-to-increase-per_page-limit-in-wordpress-rest-api/</a></p>\n"
}
]
| 2017/07/07 | [
"https://wordpress.stackexchange.com/questions/272682",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/52128/"
]
| A client is using the WordPress REST JSON API with some WordPress data models. We need to hit the WordPress API from the frontend and retreive a few hundred custom posts.
Wordpress has a [hard limit of 100 custom posts](https://developer.wordpress.org/reference/classes/wp_rest_controller/get_collection_params/).
I would like to change this limit to a much higher number for this use case. I read that you cannot monkey patch in PHP.
Is there any way to adjust the `per_page->maximum` value to, say, 10000? | You cannot get over that limit of 100 posts per requests in WordPress for default requests. One way to still retrieve all posts would be to query that interface until you have all posts. Another would be a custom endpoint.
If you can, I suggest creating your own REST endpoint. This will already work and return all posts
```
add_action('rest_api_init', 'my_more_posts');
function my_more_posts() {
register_rest_route('myplugin/v1', '/myposts', array(
'methods' => 'GET',
'callback' => 'my_more_posts_callback',
));
}
function my_more_posts_callback( WP_REST_Request $request ) {
$args = array(
'posts_per_page' => -1,
);
return get_posts($args);
}
```
More info on [creating your own endpoint can be found here](https://developer.wordpress.org/rest-api/extending-the-rest-api/adding-custom-endpoints/), whereas the [arguments of `get_posts()` are explained here](https://codex.wordpress.org/Template_Tags/get_posts).
---
For a pure JavaScript solution in the frontend, you can utilize the `x-wp-totalpages` header which tells the total amount of pages. Unless this page is reached, we know we need to query again. So a basic recursive version like this works:
```
var allPosts = [];
function retrievePosts(opt) {
if (typeof opt === 'undefined')
opt = {};
var options = $.extend({
per_page: 100,
page: 1
}, opt);
var url = 'https://example.com/wp-json/wp/v2/posts';
var uri = url + '?per_page=' + options.per_page + '&page=' + options.page;
$.getJSON(uri, function(data, status, jqXHR) {
var totalpages = jqXHR.getResponseHeader('x-wp-totalpages');
allPosts = allPosts.concat( data );
// here the magic happens
// if we are not done
if (options.page < totalpages) {
// request again, but for the next page
retrievePosts({
per_page: options.per_page,
page: options.page + 1
});
} else {
// WE ARE DONE
// posts are in allPosts
}
});
};
retrievePosts();
``` |
272,717 | <p>I am newbie in wordpress but not very new.</p>
<p>When I came to know that wordpress have inbuilt shortcodes like audio, video, gallery, playlist.</p>
<p>I have searched for a list of inbuilt shortcodes that WordPress provides but I did not get anything except above can anybody provide me a link which has a list of inbuilt wp shortcodes.</p>
<p>And</p>
<p>one more thing if WordPress provide more inbuilt shortcodes are they only work in wordpress.com</p>
<p>I know that you guys may thing I am a fool or idiot but I want to know.</p>
| [
{
"answer_id": 272721,
"author": "Milo",
"author_id": 4771,
"author_profile": "https://wordpress.stackexchange.com/users/4771",
"pm_score": 2,
"selected": false,
"text": "<p>You got almost all of them:</p>\n\n<pre><code>caption\ngallery\naudio\nvideo\nplaylist\nembed\n</code></pre>\n\n<p>You can see their associated functions in <a href=\"https://github.com/WordPress/WordPress/blob/master/wp-includes/media.php\" rel=\"nofollow noreferrer\"><code>wp-includes/media.php</code></a> and <a href=\"https://github.com/WordPress/WordPress/blob/master/wp-includes/class-wp-embed.php\" rel=\"nofollow noreferrer\"><code>wp-includes/class-wp-embed.php</code></a>.</p>\n\n<p>I don't know if there's a list somewhere, I just searched WordPress source code for <code>add_shortcode</code>.</p>\n"
},
{
"answer_id": 272725,
"author": "Erbilacx",
"author_id": 119537,
"author_profile": "https://wordpress.stackexchange.com/users/119537",
"pm_score": 4,
"selected": true,
"text": "<p>You can actually list all of the available shortcodes for your WordPress installation by using the following code:</p>\n\n<pre><code><?php\nglobal $shortcode_tags;\necho '<pre>'; \nprint_r($shortcode_tags); \necho '</pre>';\n?>\n</code></pre>\n\n<p>It will show the main WordPress shortcodes plus any shortcodes for installed plugins which can be handy too!</p>\n"
}
]
| 2017/07/08 | [
"https://wordpress.stackexchange.com/questions/272717",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/123366/"
]
| I am newbie in wordpress but not very new.
When I came to know that wordpress have inbuilt shortcodes like audio, video, gallery, playlist.
I have searched for a list of inbuilt shortcodes that WordPress provides but I did not get anything except above can anybody provide me a link which has a list of inbuilt wp shortcodes.
And
one more thing if WordPress provide more inbuilt shortcodes are they only work in wordpress.com
I know that you guys may thing I am a fool or idiot but I want to know. | You can actually list all of the available shortcodes for your WordPress installation by using the following code:
```
<?php
global $shortcode_tags;
echo '<pre>';
print_r($shortcode_tags);
echo '</pre>';
?>
```
It will show the main WordPress shortcodes plus any shortcodes for installed plugins which can be handy too! |
272,760 | <p>I have done some weird things with a few custom theme pages. Namely, i have bypassed the wp_query and obtained data from a different db. I populate the post object with custom data and then inject this into my theme. Since the toolbar shows up fine normally, there must be some sort of trigger that i am bypassing by not calling the wordpress DB. I am 100% sure the theme is not the cause of the issue here, it is the messing that i have done. However, there are no errors in the code, everything works good. What does the admin toolbar require in order to load? Is there some hook i can call manually in order to make it render?</p>
<p>I have tried messing around with the code and info from the wordpress docs <a href="https://codex.wordpress.org/Function_Reference/show_admin_bar" rel="nofollow noreferrer">https://codex.wordpress.org/Function_Reference/show_admin_bar</a></p>
| [
{
"answer_id": 272721,
"author": "Milo",
"author_id": 4771,
"author_profile": "https://wordpress.stackexchange.com/users/4771",
"pm_score": 2,
"selected": false,
"text": "<p>You got almost all of them:</p>\n\n<pre><code>caption\ngallery\naudio\nvideo\nplaylist\nembed\n</code></pre>\n\n<p>You can see their associated functions in <a href=\"https://github.com/WordPress/WordPress/blob/master/wp-includes/media.php\" rel=\"nofollow noreferrer\"><code>wp-includes/media.php</code></a> and <a href=\"https://github.com/WordPress/WordPress/blob/master/wp-includes/class-wp-embed.php\" rel=\"nofollow noreferrer\"><code>wp-includes/class-wp-embed.php</code></a>.</p>\n\n<p>I don't know if there's a list somewhere, I just searched WordPress source code for <code>add_shortcode</code>.</p>\n"
},
{
"answer_id": 272725,
"author": "Erbilacx",
"author_id": 119537,
"author_profile": "https://wordpress.stackexchange.com/users/119537",
"pm_score": 4,
"selected": true,
"text": "<p>You can actually list all of the available shortcodes for your WordPress installation by using the following code:</p>\n\n<pre><code><?php\nglobal $shortcode_tags;\necho '<pre>'; \nprint_r($shortcode_tags); \necho '</pre>';\n?>\n</code></pre>\n\n<p>It will show the main WordPress shortcodes plus any shortcodes for installed plugins which can be handy too!</p>\n"
}
]
| 2017/07/09 | [
"https://wordpress.stackexchange.com/questions/272760",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/190834/"
]
| I have done some weird things with a few custom theme pages. Namely, i have bypassed the wp\_query and obtained data from a different db. I populate the post object with custom data and then inject this into my theme. Since the toolbar shows up fine normally, there must be some sort of trigger that i am bypassing by not calling the wordpress DB. I am 100% sure the theme is not the cause of the issue here, it is the messing that i have done. However, there are no errors in the code, everything works good. What does the admin toolbar require in order to load? Is there some hook i can call manually in order to make it render?
I have tried messing around with the code and info from the wordpress docs <https://codex.wordpress.org/Function_Reference/show_admin_bar> | You can actually list all of the available shortcodes for your WordPress installation by using the following code:
```
<?php
global $shortcode_tags;
echo '<pre>';
print_r($shortcode_tags);
echo '</pre>';
?>
```
It will show the main WordPress shortcodes plus any shortcodes for installed plugins which can be handy too! |
272,772 | <p>I have a WP installation with 6 categories and I want 3 of them to use a custom Category Archive Page called "category-special.php" (default page is the "category.php").
I found the code below that looks to be close to my query, how can I modify and make it work for me, so categories 31,40 and 55 to load the above specific page?</p>
<pre><code>add_filter( 'template_include', 'wpsites_photo_page_template', 99 );
function wpsites_photo_page_template( $template ) {
if ( is_category('33') ) {
$new_template = locate_template( array( 'photo.php' ) );
if ( '' != $new_template ) {
return $new_template ;
}
}
return $template;
}
</code></pre>
<p>Thank you.</p>
| [
{
"answer_id": 272721,
"author": "Milo",
"author_id": 4771,
"author_profile": "https://wordpress.stackexchange.com/users/4771",
"pm_score": 2,
"selected": false,
"text": "<p>You got almost all of them:</p>\n\n<pre><code>caption\ngallery\naudio\nvideo\nplaylist\nembed\n</code></pre>\n\n<p>You can see their associated functions in <a href=\"https://github.com/WordPress/WordPress/blob/master/wp-includes/media.php\" rel=\"nofollow noreferrer\"><code>wp-includes/media.php</code></a> and <a href=\"https://github.com/WordPress/WordPress/blob/master/wp-includes/class-wp-embed.php\" rel=\"nofollow noreferrer\"><code>wp-includes/class-wp-embed.php</code></a>.</p>\n\n<p>I don't know if there's a list somewhere, I just searched WordPress source code for <code>add_shortcode</code>.</p>\n"
},
{
"answer_id": 272725,
"author": "Erbilacx",
"author_id": 119537,
"author_profile": "https://wordpress.stackexchange.com/users/119537",
"pm_score": 4,
"selected": true,
"text": "<p>You can actually list all of the available shortcodes for your WordPress installation by using the following code:</p>\n\n<pre><code><?php\nglobal $shortcode_tags;\necho '<pre>'; \nprint_r($shortcode_tags); \necho '</pre>';\n?>\n</code></pre>\n\n<p>It will show the main WordPress shortcodes plus any shortcodes for installed plugins which can be handy too!</p>\n"
}
]
| 2017/07/09 | [
"https://wordpress.stackexchange.com/questions/272772",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/117746/"
]
| I have a WP installation with 6 categories and I want 3 of them to use a custom Category Archive Page called "category-special.php" (default page is the "category.php").
I found the code below that looks to be close to my query, how can I modify and make it work for me, so categories 31,40 and 55 to load the above specific page?
```
add_filter( 'template_include', 'wpsites_photo_page_template', 99 );
function wpsites_photo_page_template( $template ) {
if ( is_category('33') ) {
$new_template = locate_template( array( 'photo.php' ) );
if ( '' != $new_template ) {
return $new_template ;
}
}
return $template;
}
```
Thank you. | You can actually list all of the available shortcodes for your WordPress installation by using the following code:
```
<?php
global $shortcode_tags;
echo '<pre>';
print_r($shortcode_tags);
echo '</pre>';
?>
```
It will show the main WordPress shortcodes plus any shortcodes for installed plugins which can be handy too! |
272,787 | <p>The permalink structure has changed with old entries as well as any new entry (post, object, etc) from THEN to NOW </p>
<p>THEN: </p>
<blockquote>
<p>constructstudies.com/(page slug or object label)</p>
</blockquote>
<p>NOW: </p>
<blockquote>
<p>constructstudies.com/disability-application/disability-benefits-application/disability-application/(page
slug or object label)</p>
</blockquote>
<p>The redundant parent labels cannot be altered under permalinks settings, nor with the 4 custom permalink plugins I have tried. The structure is embedded deeper than these settings allow. </p>
<p>It should be noted that in attempts to better my link structure, I have created and subsequently deleted 3 versions of similar parent pages with no more than one present at any given time. Two were labeled disability application and the other disability benefits application. </p>
<p>Why have these old titles carried over into the permanent URL structure and how can I fix this? Ive deleted revisions with WP optimize, gone into <code>myphpadmin</code> and deleted old like entries from the <code>wp_febe_posts</code> table, cleared all cache, tried to delete and recreate pages, alter the <code>.htaccess</code> file to reflect a single-label permalink structure, and searched endlessly on forums and google. </p>
<p>I'm uncertain whether deleting the old parent page entries and revisions in <code>wp_febe_posts</code> table via <code>myphpadmin</code> is the same as doing so in WP_pages via FTP, as I have searched endlessly for this to no avail so I cannot confirm. </p>
<p>My strongest suspicion is something awry in my <code>.htaccess</code> file, as I have made several changes to it over the past couple of weeks and have limited knowledge of the changes beyond what was explained in the articles which accompanied respective modules i copy pasted. </p>
<p>Below is the contents of <code>.htaccess files.</code> This file in the root directory is identical to the entry within my <code>public_html-->constructstudies</code> directory</p>
<p>-Please help me remedy this befuddlement and get me back to work. Thank you.-</p>
<p><strong>EDIT</strong>:I returned to my site to find a fourth /disability-application appended to the permalink structure. As suggested on worpress.org forums, i have deleted my htaccess file as it was indicated there were redundancies within it. Also, I read that my results could be produced by a command but i have no recollection of this nor is it found in any of the basic editor phps within dashboard. just thought it may be worth noting.</p>
<p>.htaccess: (any general suggestions welcomed as well)</p>
<pre><code> <IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule ^sitemap(-+([a-zA-Z0-9_-]+))?\.xml(\.gz)?$ /public_html/constructstudies/sitemap$1.xml$2 [L]
</IfModule>
# BEGIN W3TC CDN
<FilesMatch "\.(asf|asx|wax|wmv|wmx|avi|bmp|class|divx|doc|docx|eot|exe|gif|gz|gzip|ico|jpg|jpeg|jpe|webp|json|mdb|mid|midi|mov|qt|mp3|m4a|mp4|m4v|mpeg|mpg|mpe|mpp|otf|_otf|odb|odc|odf|odg|odp|ods|odt|ogg|pdf|png|pot|pps|ppt|pptx|ra|ram|svg|svgz|swf|tar|tif|tiff|ttf|ttc|_ttf|wav|wma|wri|woff|woff2|xla|xls|xlsx|xlt|xlw|zip|ASF|ASX|WAX|WMV|WMX|AVI|BMP|CLASS|DIVX|DOC|DOCX|EOT|EXE|GIF|GZ|GZIP|ICO|JPG|JPEG|JPE|WEBP|JSON|MDB|MID|MIDI|MOV|QT|MP3|M4A|MP4|M4V|MPEG|MPG|MPE|MPP|OTF|_OTF|ODB|ODC|ODF|ODG|ODP|ODS|ODT|OGG|PDF|PNG|POT|PPS|PPT|PPTX|RA|RAM|SVG|SVGZ|SWF|TAR|TIF|TIFF|TTF|TTC|_TTF|WAV|WMA|WRI|WOFF|WOFF2|XLA|XLS|XLSX|XLT|XLW|ZIP)$">
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule .* - [E=CANONICAL:http://www.constructstudies.com%{REQUEST_URI},NE]
RewriteCond %{HTTPS} =on
RewriteRule .* - [E=CANONICAL:https://www.constructstudies.com%{REQUEST_URI},NE]
</IfModule>
<IfModule mod_headers.c>
Header set Link "<%{CANONICAL}e>; rel=\"canonical\""
</IfModule>
</FilesMatch>
<FilesMatch "\.(ttf|ttc|otf|eot|woff|woff2|font.css)$">
<IfModule mod_headers.c>
Header set Access-Control-Allow-Origin "*"
</IfModule>
</FilesMatch>
# END W3TC CDN
# BEGIN WordPress
AddHandler application/x-httpd-php70s .php
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /disability-application
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /disability-application/index.php [L]
</IfModule>
# END WordPress
AddHandler application/x-httpd-php70s .php
<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
# Wordfence WAF
<Files ".user.ini">
<IfModule mod_authz_core.c>
Require all denied
</IfModule>
<IfModule !mod_authz_core.c>
Order deny,allow
Deny from all
</IfModule>
</Files>
# END Wordfence WAF
</code></pre>
| [
{
"answer_id": 272721,
"author": "Milo",
"author_id": 4771,
"author_profile": "https://wordpress.stackexchange.com/users/4771",
"pm_score": 2,
"selected": false,
"text": "<p>You got almost all of them:</p>\n\n<pre><code>caption\ngallery\naudio\nvideo\nplaylist\nembed\n</code></pre>\n\n<p>You can see their associated functions in <a href=\"https://github.com/WordPress/WordPress/blob/master/wp-includes/media.php\" rel=\"nofollow noreferrer\"><code>wp-includes/media.php</code></a> and <a href=\"https://github.com/WordPress/WordPress/blob/master/wp-includes/class-wp-embed.php\" rel=\"nofollow noreferrer\"><code>wp-includes/class-wp-embed.php</code></a>.</p>\n\n<p>I don't know if there's a list somewhere, I just searched WordPress source code for <code>add_shortcode</code>.</p>\n"
},
{
"answer_id": 272725,
"author": "Erbilacx",
"author_id": 119537,
"author_profile": "https://wordpress.stackexchange.com/users/119537",
"pm_score": 4,
"selected": true,
"text": "<p>You can actually list all of the available shortcodes for your WordPress installation by using the following code:</p>\n\n<pre><code><?php\nglobal $shortcode_tags;\necho '<pre>'; \nprint_r($shortcode_tags); \necho '</pre>';\n?>\n</code></pre>\n\n<p>It will show the main WordPress shortcodes plus any shortcodes for installed plugins which can be handy too!</p>\n"
}
]
| 2017/07/09 | [
"https://wordpress.stackexchange.com/questions/272787",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/123480/"
]
| The permalink structure has changed with old entries as well as any new entry (post, object, etc) from THEN to NOW
THEN:
>
> constructstudies.com/(page slug or object label)
>
>
>
NOW:
>
> constructstudies.com/disability-application/disability-benefits-application/disability-application/(page
> slug or object label)
>
>
>
The redundant parent labels cannot be altered under permalinks settings, nor with the 4 custom permalink plugins I have tried. The structure is embedded deeper than these settings allow.
It should be noted that in attempts to better my link structure, I have created and subsequently deleted 3 versions of similar parent pages with no more than one present at any given time. Two were labeled disability application and the other disability benefits application.
Why have these old titles carried over into the permanent URL structure and how can I fix this? Ive deleted revisions with WP optimize, gone into `myphpadmin` and deleted old like entries from the `wp_febe_posts` table, cleared all cache, tried to delete and recreate pages, alter the `.htaccess` file to reflect a single-label permalink structure, and searched endlessly on forums and google.
I'm uncertain whether deleting the old parent page entries and revisions in `wp_febe_posts` table via `myphpadmin` is the same as doing so in WP\_pages via FTP, as I have searched endlessly for this to no avail so I cannot confirm.
My strongest suspicion is something awry in my `.htaccess` file, as I have made several changes to it over the past couple of weeks and have limited knowledge of the changes beyond what was explained in the articles which accompanied respective modules i copy pasted.
Below is the contents of `.htaccess files.` This file in the root directory is identical to the entry within my `public_html-->constructstudies` directory
-Please help me remedy this befuddlement and get me back to work. Thank you.-
**EDIT**:I returned to my site to find a fourth /disability-application appended to the permalink structure. As suggested on worpress.org forums, i have deleted my htaccess file as it was indicated there were redundancies within it. Also, I read that my results could be produced by a command but i have no recollection of this nor is it found in any of the basic editor phps within dashboard. just thought it may be worth noting.
.htaccess: (any general suggestions welcomed as well)
```
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule ^sitemap(-+([a-zA-Z0-9_-]+))?\.xml(\.gz)?$ /public_html/constructstudies/sitemap$1.xml$2 [L]
</IfModule>
# BEGIN W3TC CDN
<FilesMatch "\.(asf|asx|wax|wmv|wmx|avi|bmp|class|divx|doc|docx|eot|exe|gif|gz|gzip|ico|jpg|jpeg|jpe|webp|json|mdb|mid|midi|mov|qt|mp3|m4a|mp4|m4v|mpeg|mpg|mpe|mpp|otf|_otf|odb|odc|odf|odg|odp|ods|odt|ogg|pdf|png|pot|pps|ppt|pptx|ra|ram|svg|svgz|swf|tar|tif|tiff|ttf|ttc|_ttf|wav|wma|wri|woff|woff2|xla|xls|xlsx|xlt|xlw|zip|ASF|ASX|WAX|WMV|WMX|AVI|BMP|CLASS|DIVX|DOC|DOCX|EOT|EXE|GIF|GZ|GZIP|ICO|JPG|JPEG|JPE|WEBP|JSON|MDB|MID|MIDI|MOV|QT|MP3|M4A|MP4|M4V|MPEG|MPG|MPE|MPP|OTF|_OTF|ODB|ODC|ODF|ODG|ODP|ODS|ODT|OGG|PDF|PNG|POT|PPS|PPT|PPTX|RA|RAM|SVG|SVGZ|SWF|TAR|TIF|TIFF|TTF|TTC|_TTF|WAV|WMA|WRI|WOFF|WOFF2|XLA|XLS|XLSX|XLT|XLW|ZIP)$">
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule .* - [E=CANONICAL:http://www.constructstudies.com%{REQUEST_URI},NE]
RewriteCond %{HTTPS} =on
RewriteRule .* - [E=CANONICAL:https://www.constructstudies.com%{REQUEST_URI},NE]
</IfModule>
<IfModule mod_headers.c>
Header set Link "<%{CANONICAL}e>; rel=\"canonical\""
</IfModule>
</FilesMatch>
<FilesMatch "\.(ttf|ttc|otf|eot|woff|woff2|font.css)$">
<IfModule mod_headers.c>
Header set Access-Control-Allow-Origin "*"
</IfModule>
</FilesMatch>
# END W3TC CDN
# BEGIN WordPress
AddHandler application/x-httpd-php70s .php
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /disability-application
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /disability-application/index.php [L]
</IfModule>
# END WordPress
AddHandler application/x-httpd-php70s .php
<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
# Wordfence WAF
<Files ".user.ini">
<IfModule mod_authz_core.c>
Require all denied
</IfModule>
<IfModule !mod_authz_core.c>
Order deny,allow
Deny from all
</IfModule>
</Files>
# END Wordfence WAF
``` | You can actually list all of the available shortcodes for your WordPress installation by using the following code:
```
<?php
global $shortcode_tags;
echo '<pre>';
print_r($shortcode_tags);
echo '</pre>';
?>
```
It will show the main WordPress shortcodes plus any shortcodes for installed plugins which can be handy too! |
272,797 | <p>I have Wordpress menus that is seems are put together in the backend somehow. I used <a href="https://developer.wordpress.org/reference/functions/wp_nav_menu/" rel="nofollow noreferrer">wp_nav_menu()</a> to customize the wrap of the menu items slightly.</p>
<p>My issue is I have found no direct access to access the menu items, and add a custom field to them. They are all categories, and I want a specific icon for each category. </p>
<p>This is my code in the functions.php to customize the menu:</p>
<pre><code>function custom_novice_menu($args) {
$args['container'] = false;
$args['container_id'] = 'my_primary_menu';
$args['link_before'] = '<div class="topic-card"><div class="topic-circle"></div><h3>';
$args['link_after'] = '</h3></div>';
return $args;
}
</code></pre>
<p>Does anyone know a way I could add a unique icon to each menu item?</p>
| [
{
"answer_id": 272721,
"author": "Milo",
"author_id": 4771,
"author_profile": "https://wordpress.stackexchange.com/users/4771",
"pm_score": 2,
"selected": false,
"text": "<p>You got almost all of them:</p>\n\n<pre><code>caption\ngallery\naudio\nvideo\nplaylist\nembed\n</code></pre>\n\n<p>You can see their associated functions in <a href=\"https://github.com/WordPress/WordPress/blob/master/wp-includes/media.php\" rel=\"nofollow noreferrer\"><code>wp-includes/media.php</code></a> and <a href=\"https://github.com/WordPress/WordPress/blob/master/wp-includes/class-wp-embed.php\" rel=\"nofollow noreferrer\"><code>wp-includes/class-wp-embed.php</code></a>.</p>\n\n<p>I don't know if there's a list somewhere, I just searched WordPress source code for <code>add_shortcode</code>.</p>\n"
},
{
"answer_id": 272725,
"author": "Erbilacx",
"author_id": 119537,
"author_profile": "https://wordpress.stackexchange.com/users/119537",
"pm_score": 4,
"selected": true,
"text": "<p>You can actually list all of the available shortcodes for your WordPress installation by using the following code:</p>\n\n<pre><code><?php\nglobal $shortcode_tags;\necho '<pre>'; \nprint_r($shortcode_tags); \necho '</pre>';\n?>\n</code></pre>\n\n<p>It will show the main WordPress shortcodes plus any shortcodes for installed plugins which can be handy too!</p>\n"
}
]
| 2017/07/09 | [
"https://wordpress.stackexchange.com/questions/272797",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/123346/"
]
| I have Wordpress menus that is seems are put together in the backend somehow. I used [wp\_nav\_menu()](https://developer.wordpress.org/reference/functions/wp_nav_menu/) to customize the wrap of the menu items slightly.
My issue is I have found no direct access to access the menu items, and add a custom field to them. They are all categories, and I want a specific icon for each category.
This is my code in the functions.php to customize the menu:
```
function custom_novice_menu($args) {
$args['container'] = false;
$args['container_id'] = 'my_primary_menu';
$args['link_before'] = '<div class="topic-card"><div class="topic-circle"></div><h3>';
$args['link_after'] = '</h3></div>';
return $args;
}
```
Does anyone know a way I could add a unique icon to each menu item? | You can actually list all of the available shortcodes for your WordPress installation by using the following code:
```
<?php
global $shortcode_tags;
echo '<pre>';
print_r($shortcode_tags);
echo '</pre>';
?>
```
It will show the main WordPress shortcodes plus any shortcodes for installed plugins which can be handy too! |
272,801 | <p>I come from a Laravel background which means I am used to using database migrations and seedings to keep content on dev / staging sites in sync with my local environment.</p>
<p>I'm starting my first project in WordPress and was wondering how to go about doing the same. Essentially I'm building the site on my local environment and through the use of plugins such as Advanced Custom Fields I will create the content for the site. I need an easy was of ensuring the dev / staging sites have the same content as my local environment. I only want to sync content such as posts, pages, custom post types, and any associated media.</p>
<p>Deployment of code itself is not an issue as the code is kept under version control and I can create a webhook to auto deploy the code.</p>
<p>I have read up on plugins such as <a href="https://en-gb.wordpress.org/plugins/wp-migrate-db/" rel="nofollow noreferrer">WP Migrate DB</a> but I'm not sure this is the tool for the job.</p>
<p>Can anyone advise the best way to accomplish this?</p>
| [
{
"answer_id": 272721,
"author": "Milo",
"author_id": 4771,
"author_profile": "https://wordpress.stackexchange.com/users/4771",
"pm_score": 2,
"selected": false,
"text": "<p>You got almost all of them:</p>\n\n<pre><code>caption\ngallery\naudio\nvideo\nplaylist\nembed\n</code></pre>\n\n<p>You can see their associated functions in <a href=\"https://github.com/WordPress/WordPress/blob/master/wp-includes/media.php\" rel=\"nofollow noreferrer\"><code>wp-includes/media.php</code></a> and <a href=\"https://github.com/WordPress/WordPress/blob/master/wp-includes/class-wp-embed.php\" rel=\"nofollow noreferrer\"><code>wp-includes/class-wp-embed.php</code></a>.</p>\n\n<p>I don't know if there's a list somewhere, I just searched WordPress source code for <code>add_shortcode</code>.</p>\n"
},
{
"answer_id": 272725,
"author": "Erbilacx",
"author_id": 119537,
"author_profile": "https://wordpress.stackexchange.com/users/119537",
"pm_score": 4,
"selected": true,
"text": "<p>You can actually list all of the available shortcodes for your WordPress installation by using the following code:</p>\n\n<pre><code><?php\nglobal $shortcode_tags;\necho '<pre>'; \nprint_r($shortcode_tags); \necho '</pre>';\n?>\n</code></pre>\n\n<p>It will show the main WordPress shortcodes plus any shortcodes for installed plugins which can be handy too!</p>\n"
}
]
| 2017/07/09 | [
"https://wordpress.stackexchange.com/questions/272801",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/62933/"
]
| I come from a Laravel background which means I am used to using database migrations and seedings to keep content on dev / staging sites in sync with my local environment.
I'm starting my first project in WordPress and was wondering how to go about doing the same. Essentially I'm building the site on my local environment and through the use of plugins such as Advanced Custom Fields I will create the content for the site. I need an easy was of ensuring the dev / staging sites have the same content as my local environment. I only want to sync content such as posts, pages, custom post types, and any associated media.
Deployment of code itself is not an issue as the code is kept under version control and I can create a webhook to auto deploy the code.
I have read up on plugins such as [WP Migrate DB](https://en-gb.wordpress.org/plugins/wp-migrate-db/) but I'm not sure this is the tool for the job.
Can anyone advise the best way to accomplish this? | You can actually list all of the available shortcodes for your WordPress installation by using the following code:
```
<?php
global $shortcode_tags;
echo '<pre>';
print_r($shortcode_tags);
echo '</pre>';
?>
```
It will show the main WordPress shortcodes plus any shortcodes for installed plugins which can be handy too! |
272,844 | <p>I am clicking on the link define in the anchor tag and fetching the url. I want to pass this url in url_to_postid($_POST['url']) which returns me ID.</p>
<p>What I have done till far now is everything working except the ajax call on admin-ajax to pass url to fetch ID</p>
<p>Step 1 : Created a widget in widget() function</p>
<p>Step 2 : Calling get_prev_ajax_handler() function on click and want to get the
post ID of that link using url_to_postid($_POST['url']); </p>
<pre><code> function Reco_load_widget() {
register_widget( 'Reco_Person' );
}
add_action( 'widgets_init', 'Reco_load_widget' );
class Reco_Person extends WP_Widget {
function __construct() {
parent::__construct(
'wpb_widget_per',
__('Reco Personalisation','wpb_widget_per_person'),
array( 'description' => __( 'Content widget', 'wpb_widget_per_person' ), )
);
}
public function widget( $args, $instance ) { ?>
<script>
jQuery(function(){
jQuery('a').click(function(){
var url = jQuery(this).attr('href');
jQuery.ajax({
url: '<?php echo admin_url('admin-ajax.php'); ?>',
method: "POST",
contentType: 'application/json',
data: ({
action: "get_prev_ajax_handler",
url: url
}),
success: function (response){
console.log(response);
}
});
});
});
</script>
<?php }
public function get_prev_ajax_handler() {
return url_to_postid($_POST["url"]);
}
}
add_action('wp_ajax_get_prev', 'get_prev_ajax_handler'); // add action for logged users
add_action( 'wp_ajax_nopriv_get_prev', 'get_prev_ajax_handler' );
</code></pre>
<p>But this hook is not working. Did I invoke add_action at wrong place with wrong parameter? </p>
| [
{
"answer_id": 272883,
"author": "Aniruddha Gawade",
"author_id": 101818,
"author_profile": "https://wordpress.stackexchange.com/users/101818",
"pm_score": 0,
"selected": false,
"text": "<p>Your <code>action</code> in JQuery and and hook action is not matching.\nIt should be:</p>\n\n<pre><code>add_action('wp_ajax_get_prev_ajax_handler', 'get_prev_ajax_handler'); \nadd_action( 'wp_ajax_nopriv_get_prev_ajax_handler', 'get_prev_ajax_handler' );\n</code></pre>\n\n<p>Also get <code>get_prev_ajax_handler</code> function outside <code>Reco_Person</code> class.</p>\n"
},
{
"answer_id": 272885,
"author": "Aamer Shahzad",
"author_id": 42772,
"author_profile": "https://wordpress.stackexchange.com/users/42772",
"pm_score": 1,
"selected": false,
"text": "<p>the another way to get the <code>post_id</code> by clicking on the <code>link</code> is to add a <code>data-attribute</code> to the link. e.g; <code>data-post-id=\"'.get_the_ID().'\"</code></p>\n\n<p>your html code should look like</p>\n\n<pre><code><a href=\"#link\" data-post-id=\"47\">Link</a>\n</code></pre>\n\n<p>then in your js code above the ajax call</p>\n\n<pre><code>var post_id = jQuery(this).attr('data-post-id');\n</code></pre>\n\n<p>and pass this in your <code>data</code> object to the ajax call.</p>\n\n<pre><code>data: ({\n action: \"get_prev_ajax_handler\",\n url: url,\n post_id: post_id,\n}),\n</code></pre>\n\n<p>now you can get the <code>post_id</code> with <code>$_POST['post_id']</code> or <code>print_r()</code> the <code>$_POST</code> <code>array()</code></p>\n"
}
]
| 2017/07/10 | [
"https://wordpress.stackexchange.com/questions/272844",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/123508/"
]
| I am clicking on the link define in the anchor tag and fetching the url. I want to pass this url in url\_to\_postid($\_POST['url']) which returns me ID.
What I have done till far now is everything working except the ajax call on admin-ajax to pass url to fetch ID
Step 1 : Created a widget in widget() function
Step 2 : Calling get\_prev\_ajax\_handler() function on click and want to get the
post ID of that link using url\_to\_postid($\_POST['url']);
```
function Reco_load_widget() {
register_widget( 'Reco_Person' );
}
add_action( 'widgets_init', 'Reco_load_widget' );
class Reco_Person extends WP_Widget {
function __construct() {
parent::__construct(
'wpb_widget_per',
__('Reco Personalisation','wpb_widget_per_person'),
array( 'description' => __( 'Content widget', 'wpb_widget_per_person' ), )
);
}
public function widget( $args, $instance ) { ?>
<script>
jQuery(function(){
jQuery('a').click(function(){
var url = jQuery(this).attr('href');
jQuery.ajax({
url: '<?php echo admin_url('admin-ajax.php'); ?>',
method: "POST",
contentType: 'application/json',
data: ({
action: "get_prev_ajax_handler",
url: url
}),
success: function (response){
console.log(response);
}
});
});
});
</script>
<?php }
public function get_prev_ajax_handler() {
return url_to_postid($_POST["url"]);
}
}
add_action('wp_ajax_get_prev', 'get_prev_ajax_handler'); // add action for logged users
add_action( 'wp_ajax_nopriv_get_prev', 'get_prev_ajax_handler' );
```
But this hook is not working. Did I invoke add\_action at wrong place with wrong parameter? | the another way to get the `post_id` by clicking on the `link` is to add a `data-attribute` to the link. e.g; `data-post-id="'.get_the_ID().'"`
your html code should look like
```
<a href="#link" data-post-id="47">Link</a>
```
then in your js code above the ajax call
```
var post_id = jQuery(this).attr('data-post-id');
```
and pass this in your `data` object to the ajax call.
```
data: ({
action: "get_prev_ajax_handler",
url: url,
post_id: post_id,
}),
```
now you can get the `post_id` with `$_POST['post_id']` or `print_r()` the `$_POST` `array()` |
272,858 | <p>Can anyone help me how to add custom css file in wordpress.</p>
<p>I followed the below link,
<a href="https://wordpress.stackexchange.com/questions/258226/where-are-additional-css-files-stored">Where are Additional CSS files stored</a>.
But it shows only adding additional css, but i want to add css file and calling,</p>
<p>Thanks </p>
| [
{
"answer_id": 272860,
"author": "Jignesh Patel",
"author_id": 111556,
"author_profile": "https://wordpress.stackexchange.com/users/111556",
"pm_score": 2,
"selected": false,
"text": "<p>Put this code in functions.php file for add new css file (more info <a href=\"https://developer.wordpress.org/reference/functions/wp_enqueue_style/\" rel=\"nofollow noreferrer\">here</a>).</p>\n\n<pre><code>add_action( 'wp_enqueue_scripts', 'enqueue_my_styles' );\nfunction enqueue_my_styles() {\n wp_enqueue_style( 'my-theme-ie', get_stylesheet_directory_uri() . \"/css/ie.css\");\n}\n</code></pre>\n\n<ol>\n<li>if using a parent theme then put code in parent theme function.php file and use <code>get_template_directory_uri()</code></li>\n<li>if using a child theme then put code in child theme function.php file and use <code>get_stylesheet_directory_uri()</code></li>\n</ol>\n\n<p>Note: Relative CSS path must be correct.</p>\n"
},
{
"answer_id": 272908,
"author": "Rick Hellewell",
"author_id": 29416,
"author_profile": "https://wordpress.stackexchange.com/users/29416",
"pm_score": 0,
"selected": false,
"text": "<p>Since you don't want to mess with the theme code/css (unless it's your own), it's best to create a child theme. Then you can put your additional CSS in the child theme's CSS file. Any CSS in there will override your parent theme's CSS.</p>\n\n<p>Since you aren't changing the theme code/CSS (never a good idea), your changes will be kept when the theme has an update.</p>\n\n<p>Many tutorials for creating and using a Child theme. Here's one ( a video) <a href=\"http://www.wpbeginner.com/wp-themes/how-to-create-a-wordpress-child-theme-video/\" rel=\"nofollow noreferrer\">http://www.wpbeginner.com/wp-themes/how-to-create-a-wordpress-child-theme-video/</a> ; the googles will help you find other tutorials.</p>\n"
}
]
| 2017/07/10 | [
"https://wordpress.stackexchange.com/questions/272858",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/122737/"
]
| Can anyone help me how to add custom css file in wordpress.
I followed the below link,
[Where are Additional CSS files stored](https://wordpress.stackexchange.com/questions/258226/where-are-additional-css-files-stored).
But it shows only adding additional css, but i want to add css file and calling,
Thanks | Put this code in functions.php file for add new css file (more info [here](https://developer.wordpress.org/reference/functions/wp_enqueue_style/)).
```
add_action( 'wp_enqueue_scripts', 'enqueue_my_styles' );
function enqueue_my_styles() {
wp_enqueue_style( 'my-theme-ie', get_stylesheet_directory_uri() . "/css/ie.css");
}
```
1. if using a parent theme then put code in parent theme function.php file and use `get_template_directory_uri()`
2. if using a child theme then put code in child theme function.php file and use `get_stylesheet_directory_uri()`
Note: Relative CSS path must be correct. |
272,879 | <p>I create custom field type select</p>
<p><a href="https://i.stack.imgur.com/bofha.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/bofha.png" alt="enter image description here"></a> </p>
<p>Need display <code>values</code> from custom field outside <code><?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?></code> like <a href="https://v4-alpha.getbootstrap.com/components/navs/#tabs" rel="nofollow noreferrer">bootstrap tabs</a>.</p>
<p>Code 1:</p>
<pre><code><?php
global $wp_query;
$postid = $wp_query->post->ID;
var_dump($postid);
echo get_post_meta($postid, 'employee_category', true);
wp_reset_query();
?>
</code></pre>
<p>return - <code>int(269)</code> - id page.</p>
<p>Code 2:</p>
<pre><code><?php
$value = get_field( "employee_category" );
if( $value ) {
echo $value;
} else {
echo 'empty';
}
?>
</code></pre>
<p>return - <code>empty</code>.</p>
<p>Code 2 inside loop work correctly.</p>
<p>How display values outside loop?</p>
<p><strong>UPD</strong></p>
<p>Need to display all categorys.</p>
<p>This code </p>
<pre><code><?php
global $wp_query;
$postid = $wp_query->post->ID;
$value = get_field( "employee_category", 269 );
var_dump($value);
if( $value ) {
echo $value;
} else {
echo 'empty';
}
wp_reset_query();
?>
</code></pre>
<p>return <code>null</code></p>
| [
{
"answer_id": 272880,
"author": "Aniruddha Gawade",
"author_id": 101818,
"author_profile": "https://wordpress.stackexchange.com/users/101818",
"pm_score": 2,
"selected": false,
"text": "<p>You need to pass <code>$postid</code> to your <code>get_field</code> function.</p>\n\n<pre><code><?php\n $value = get_field( \"employee_category\", $postid );\n if( $value ) {\n echo $value;\n } else {\n echo 'empty';\n }\n?>\n</code></pre>\n\n<p>See docs: <a href=\"https://www.advancedcustomfields.com/resources/get_field/\" rel=\"nofollow noreferrer\">https://www.advancedcustomfields.com/resources/get_field/</a></p>\n"
},
{
"answer_id": 272881,
"author": "Erbilacx",
"author_id": 119537,
"author_profile": "https://wordpress.stackexchange.com/users/119537",
"pm_score": 1,
"selected": false,
"text": "<p>You can access a custom field by supplying the post ID in the second arguement.</p>\n\n<pre><code>get_field($selector, [$post_id]);\n</code></pre>\n\n<p>So in your case you would do the following:</p>\n\n<pre><code>$value = get_field( \"employee_category\", $postid );\n</code></pre>\n\n<p>You can view the full documentation here: <a href=\"https://www.advancedcustomfields.com/resources/get_field/\" rel=\"nofollow noreferrer\">https://www.advancedcustomfields.com/resources/get_field/</a></p>\n"
},
{
"answer_id": 272886,
"author": "mrben522",
"author_id": 84703,
"author_profile": "https://wordpress.stackexchange.com/users/84703",
"pm_score": 0,
"selected": false,
"text": "<p>If you are trying to echo out all of the choices for that ACF select field you need to use <code>get_field_object('employee_category')</code>not <code>get_field()</code></p>\n\n<pre><code><?php\n $value = get_field_object(\"employee_category\");\n if( $value['choices'] ) {\n echo $value['choices'];\n } else {\n echo 'empty';\n }\n?>\n</code></pre>\n\n<p><a href=\"https://www.advancedcustomfields.com/resources/get_field_object/\" rel=\"nofollow noreferrer\">https://www.advancedcustomfields.com/resources/get_field_object/</a></p>\n"
},
{
"answer_id": 272967,
"author": "siberian",
"author_id": 120398,
"author_profile": "https://wordpress.stackexchange.com/users/120398",
"pm_score": 2,
"selected": true,
"text": "<p>I make this:</p>\n\n<pre><code><ul class=\"nav nav-tabs d-flex justify-content-center flex-wrap team-navs\">\n <?php $loop = new WP_Query( array( 'post_type' => 'employee', 'post_status'=>'publish', 'posts_per_page' => -1 ) ); ?>\n <?php\n $counter = 0;\n while ( $loop->have_posts() ) : $loop->the_post();\n $counter++;\n $value = get_field( \"employee_category\" );\n ?>\n <li class=\"nav-item post-<?php the_ID(); ?> <?=($counter == 1) ? 'active' : ''?>\">\n <a class=\"nav-link\" role=\"tab\" href=\"#<?php echo $value; ?>\" aria-controls=\"home\" role=\"tab\" data-toggle=\"tab\"><?php echo $value; ?></a>\n </li>\n <?php endwhile; wp_reset_query(); ?>\n </ul>\n</code></pre>\n\n<p>This code display category. But at the same time its dublicates tabs, if if there is post of the same category. And need to make switching tabs...</p>\n"
}
]
| 2017/07/10 | [
"https://wordpress.stackexchange.com/questions/272879",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/120398/"
]
| I create custom field type select
[](https://i.stack.imgur.com/bofha.png)
Need display `values` from custom field outside `<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>` like [bootstrap tabs](https://v4-alpha.getbootstrap.com/components/navs/#tabs).
Code 1:
```
<?php
global $wp_query;
$postid = $wp_query->post->ID;
var_dump($postid);
echo get_post_meta($postid, 'employee_category', true);
wp_reset_query();
?>
```
return - `int(269)` - id page.
Code 2:
```
<?php
$value = get_field( "employee_category" );
if( $value ) {
echo $value;
} else {
echo 'empty';
}
?>
```
return - `empty`.
Code 2 inside loop work correctly.
How display values outside loop?
**UPD**
Need to display all categorys.
This code
```
<?php
global $wp_query;
$postid = $wp_query->post->ID;
$value = get_field( "employee_category", 269 );
var_dump($value);
if( $value ) {
echo $value;
} else {
echo 'empty';
}
wp_reset_query();
?>
```
return `null` | I make this:
```
<ul class="nav nav-tabs d-flex justify-content-center flex-wrap team-navs">
<?php $loop = new WP_Query( array( 'post_type' => 'employee', 'post_status'=>'publish', 'posts_per_page' => -1 ) ); ?>
<?php
$counter = 0;
while ( $loop->have_posts() ) : $loop->the_post();
$counter++;
$value = get_field( "employee_category" );
?>
<li class="nav-item post-<?php the_ID(); ?> <?=($counter == 1) ? 'active' : ''?>">
<a class="nav-link" role="tab" href="#<?php echo $value; ?>" aria-controls="home" role="tab" data-toggle="tab"><?php echo $value; ?></a>
</li>
<?php endwhile; wp_reset_query(); ?>
</ul>
```
This code display category. But at the same time its dublicates tabs, if if there is post of the same category. And need to make switching tabs... |
272,887 | <p>First apologies if this is a stupid question I can imagine there is an easy way to do this but would like to ask anyhow.</p>
<p>I have setup a js framework that I am trying to integrate into a WordPress plugin. Currently if works like this.</p>
<pre><code>example("div").media({
plugins: {
modal : true
},
options : {
opts: 1
}
});
</code></pre>
<p>I am not sure how to set this up with shortcode without having hundreds of params.</p>
<pre><code>[example div="div" plugins="???" options="???"]
</code></pre>
<p>Can't find anything here <a href="https://codex.wordpress.org/Shortcode_API" rel="nofollow noreferrer">https://codex.wordpress.org/Shortcode_API</a></p>
<p>Thanks</p>
| [
{
"answer_id": 272880,
"author": "Aniruddha Gawade",
"author_id": 101818,
"author_profile": "https://wordpress.stackexchange.com/users/101818",
"pm_score": 2,
"selected": false,
"text": "<p>You need to pass <code>$postid</code> to your <code>get_field</code> function.</p>\n\n<pre><code><?php\n $value = get_field( \"employee_category\", $postid );\n if( $value ) {\n echo $value;\n } else {\n echo 'empty';\n }\n?>\n</code></pre>\n\n<p>See docs: <a href=\"https://www.advancedcustomfields.com/resources/get_field/\" rel=\"nofollow noreferrer\">https://www.advancedcustomfields.com/resources/get_field/</a></p>\n"
},
{
"answer_id": 272881,
"author": "Erbilacx",
"author_id": 119537,
"author_profile": "https://wordpress.stackexchange.com/users/119537",
"pm_score": 1,
"selected": false,
"text": "<p>You can access a custom field by supplying the post ID in the second arguement.</p>\n\n<pre><code>get_field($selector, [$post_id]);\n</code></pre>\n\n<p>So in your case you would do the following:</p>\n\n<pre><code>$value = get_field( \"employee_category\", $postid );\n</code></pre>\n\n<p>You can view the full documentation here: <a href=\"https://www.advancedcustomfields.com/resources/get_field/\" rel=\"nofollow noreferrer\">https://www.advancedcustomfields.com/resources/get_field/</a></p>\n"
},
{
"answer_id": 272886,
"author": "mrben522",
"author_id": 84703,
"author_profile": "https://wordpress.stackexchange.com/users/84703",
"pm_score": 0,
"selected": false,
"text": "<p>If you are trying to echo out all of the choices for that ACF select field you need to use <code>get_field_object('employee_category')</code>not <code>get_field()</code></p>\n\n<pre><code><?php\n $value = get_field_object(\"employee_category\");\n if( $value['choices'] ) {\n echo $value['choices'];\n } else {\n echo 'empty';\n }\n?>\n</code></pre>\n\n<p><a href=\"https://www.advancedcustomfields.com/resources/get_field_object/\" rel=\"nofollow noreferrer\">https://www.advancedcustomfields.com/resources/get_field_object/</a></p>\n"
},
{
"answer_id": 272967,
"author": "siberian",
"author_id": 120398,
"author_profile": "https://wordpress.stackexchange.com/users/120398",
"pm_score": 2,
"selected": true,
"text": "<p>I make this:</p>\n\n<pre><code><ul class=\"nav nav-tabs d-flex justify-content-center flex-wrap team-navs\">\n <?php $loop = new WP_Query( array( 'post_type' => 'employee', 'post_status'=>'publish', 'posts_per_page' => -1 ) ); ?>\n <?php\n $counter = 0;\n while ( $loop->have_posts() ) : $loop->the_post();\n $counter++;\n $value = get_field( \"employee_category\" );\n ?>\n <li class=\"nav-item post-<?php the_ID(); ?> <?=($counter == 1) ? 'active' : ''?>\">\n <a class=\"nav-link\" role=\"tab\" href=\"#<?php echo $value; ?>\" aria-controls=\"home\" role=\"tab\" data-toggle=\"tab\"><?php echo $value; ?></a>\n </li>\n <?php endwhile; wp_reset_query(); ?>\n </ul>\n</code></pre>\n\n<p>This code display category. But at the same time its dublicates tabs, if if there is post of the same category. And need to make switching tabs...</p>\n"
}
]
| 2017/07/10 | [
"https://wordpress.stackexchange.com/questions/272887",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/83641/"
]
| First apologies if this is a stupid question I can imagine there is an easy way to do this but would like to ask anyhow.
I have setup a js framework that I am trying to integrate into a WordPress plugin. Currently if works like this.
```
example("div").media({
plugins: {
modal : true
},
options : {
opts: 1
}
});
```
I am not sure how to set this up with shortcode without having hundreds of params.
```
[example div="div" plugins="???" options="???"]
```
Can't find anything here <https://codex.wordpress.org/Shortcode_API>
Thanks | I make this:
```
<ul class="nav nav-tabs d-flex justify-content-center flex-wrap team-navs">
<?php $loop = new WP_Query( array( 'post_type' => 'employee', 'post_status'=>'publish', 'posts_per_page' => -1 ) ); ?>
<?php
$counter = 0;
while ( $loop->have_posts() ) : $loop->the_post();
$counter++;
$value = get_field( "employee_category" );
?>
<li class="nav-item post-<?php the_ID(); ?> <?=($counter == 1) ? 'active' : ''?>">
<a class="nav-link" role="tab" href="#<?php echo $value; ?>" aria-controls="home" role="tab" data-toggle="tab"><?php echo $value; ?></a>
</li>
<?php endwhile; wp_reset_query(); ?>
</ul>
```
This code display category. But at the same time its dublicates tabs, if if there is post of the same category. And need to make switching tabs... |
272,902 | <p>I am trying to upload many hundreds of images daily from a folder on the server to the media library using the following script that is scheduled via CRON:</p>
<pre><code><?php
require_once('../../../../public/wordpress/wp-load.php');
require_once('../../../../public/wordpress/wp-admin/includes/image.php');
function importImage($imagePath, $postId)
{
$succeededFileCount = 0;
$failedFileCount = 0;
$files = scandir($imagePath);
foreach ($files as $file) {
if (in_array($file, ['.', '..'])) {
continue;
}
$newPath = $imagePath . "/" . $file;
$filePath = realpath($newPath);
if (is_dir($newPath) && $item != '.' && $item != '..' && $item != 'failed_files') {
importImage($newPath, $postId);
} elseif ($item != '.' && $item != '..' && $item != 'failed_files') {
$filename = basename($file);
$uploadFile = wp_upload_bits($filename, null, file_get_contents($filePath));
$wp_upload_dir = wp_upload_dir();
if (! $uploadFile['error']) {
$fileType = wp_check_filetype($filename, null);
$attachment = [
'guid' => $wp_upload_dir['url'] . '/' . basename( $filename ),
'post_mime_type' => $fileType['type'],
'post_parent' => $postId,
'post_title' => preg_replace('/\.[^.]+$/', '', $filename),
'post_content' => '',
'post_status' => 'inherit'
];
$attachmentId = wp_insert_attachment($attachment, $uploadFile['file'], $postId);
if (! is_wp_error($attachmentId)) {
$attachmentData = wp_generate_attachment_metadata($attachmentId, $uploadFile['file']);
wp_update_attachment_metadata($attachmentId, $attachmentData);
}
} else {
echo '<span style="color: red; font-weight: bold;">Error: ' . $uploadFile['error'] . '</span>';
}
if ($attachmentId > 0) {
$succeededFileCount++;
echo '<span style="color: green; font-weight: normal;">File import succeeded: ' . $filePath . "</span><br />";
if (! unlink($filePath)) {
echo '<span style="color: red; font-weight: bold;">Unable to delete file ' . $filePath . " after import.</span><br />";
}
$page = get_post($postId);
if ($page->post_content) {
$content = $page->post_content;
$start = strpos($content, "[gallery ") + strlen("[gallery ");
$end = strpos(substr($content, $start), "]");
$shortcode = substr($content, $start, $end);
$attrs = shortcode_parse_atts($shortcode);
$attrs["ids"] .= "," . $attachmentId;
$tempIds = explode(",", $attrs["ids"]);
$tempIds = array_filter($tempIds);
rsort($tempIds);
$attrs["ids"] = implode(",", $tempIds);
$shortcode = "";
foreach ($attrs as $key => $value) {
if (strlen($shortcode) > 0) {
$shortcode .= " ";
}
$shortcode .= $key . "=\"" . $value . "\"";
}
$newContent = substr($content, 0, $start);
$newContent .= $shortcode;
$newContent .= substr($content, $start + $end, strlen($content));
$page->post_content = $newContent;
wp_update_post($page);
}
}
}
}
echo $succeededFileCount . " files uploaded and imported successfully. <br />";
echo $failedFileCount . " files failed to uploaded or import successfully.";
}
get_header();
if (get_option('rmm_image_importer_key') != urldecode($_GET['key'])) {
echo '<div id="message" class="error">';
echo "<p><strong>Incorrect authentication key: you are not allowed to import images into this site.</strong></p></div>";
} else {
echo '<br /><br />';
$mtime = microtime();
$mtime = explode(" ", $mtime);
$mtime = $mtime[1] + $mtime[0];
$starttime = $mtime;
$dataset = get_option('rmm_image_importer_settings');
if (is_array($dataset)) {
foreach ($dataset as $data) {
if (isset($data['folder'])
|| isset($data['page'])) {
?>
<h2>Import from folder: <?php echo $data['folder']; ?></h2>
<p>
<?php
importImage(realpath(str_replace('//', '/', ABSPATH . '../../' . $data['folder'])), $data['page']); ?>
</p>
<?php
}
}
}
$mtime = microtime();
$mtime = explode(" ", $mtime);
$mtime = $mtime[1] + $mtime[0];
$endtime = $mtime;
$totaltime = ($endtime - $starttime);
echo 'Files imported to media library over ' . $totaltime . ' seconds.<br /><br />';
}
get_footer();
</code></pre>
<p>The problem is that no matter what I do, the script fails after just two images with this error:</p>
<blockquote>
<p>Fatal error: Allowed memory size of 1073741824 bytes exhausted (tried
to allocate 28672 bytes) in
/home/forge/morselandcompany.com/public/wordpress/wp-includes/wp-db.php
on line 1841</p>
</blockquote>
<p>I have the memory limit set to 1024M in wordpress, as well as PHP. I don't see why this script should need more than 128M, really. How can this script be optimized to work properly? (Average image size is 800kB.)</p>
<p>Some initial debugging with BlackFire.io suggests the following memory hogs:
- wpdb->query: 3.2MB, called 31 times
- mysqli_fetch_object: 1.89MB, called 595 times
- run_init() in wp-settings.php: 5.4MB, called once
In total blackfire suggests that over 8MB is required to run this script!</p>
<p>I have also tested with all plugins disabled, and that ended with the same result.</p>
<p>I am running on
- PHP 7.1<br>
- Ubuntu 16.04<br>
- DigitalOcean VPS (1 CPU, 1GB RAM)<br>
- Wordpress 4.8<br>
- NGINX 1.11.5 </p>
<p>Thanks for any help!</p>
<p><strong>Update:</strong> in the interest of completeness so that others may utilize the solution for memory leaks associated with get_post and wp_update_post, I have posted the finalized code that solved the problem above. As you can see, the solution was to write my own queries using $wpdb instead of relying on the two WP methods causing the memory leaks:</p>
<pre><code><?php
require_once('../../../../public/wordpress/wp-load.php');
require_once(ABSPATH . 'wp-admin/includes/media.php');
require_once(ABSPATH . 'wp-admin/includes/file.php');
require_once(ABSPATH . 'wp-admin/includes/image.php');
function importImage($imagePath, $postId)
{
$succeededFileCount = 0;
$failedFileCount = 0;
$files = scandir($imagePath);
foreach ($files as $file) {
if (in_array($file, ['.', '..'])) {
continue;
}
$newPath = $imagePath . "/" . $file;
$filePath = realpath($newPath);
if (is_dir($newPath) && $file != 'failed_files') {
importImage($newPath, $postId);
} elseif ($file != 'failed_files') {
$webPath = str_replace($_SERVER['DOCUMENT_ROOT'], '', $imagePath);
$imageUrl = str_replace('/wordpress', '', get_site_url(null, "{$webPath}/" . urlencode($file)));
$imageUrl = str_replace(':8000', '', $imageUrl);
$attachmentId = media_sideload_image($imageUrl, 0, '', 'id');
if ($attachmentId > 0) {
$succeededFileCount++;
echo '<span style="color: green; font-weight: normal;">File import succeeded: ' . $filePath . "</span><br />";
if (! unlink($filePath)) {
echo '<span style="color: red; font-weight: bold;">Unable to delete file ' . $filePath . " after import.</span><br />";
}
global $wpdb;
$page = $wpdb->get_results("SELECT * FROM wp_posts WHERE ID = {$postId}")[0];
if (is_array($page)) {
$page = $page[0];
}
if ($page->post_content) {
$content = $page->post_content;
$start = strpos($content, "[gallery ") + strlen("[gallery ");
$end = strpos(substr($content, $start), "]");
$shortcode = substr($content, $start, $end);
$attrs = shortcode_parse_atts($shortcode);
$attrs["ids"] .= "," . $attachmentId;
$tempIds = explode(",", $attrs["ids"]);
$tempIds = array_filter($tempIds);
rsort($tempIds);
$attrs["ids"] = implode(",", $tempIds);
$shortcode = "";
foreach ($attrs as $key => $value) {
if (strlen($shortcode) > 0) {
$shortcode .= " ";
}
$shortcode .= $key . "=\"" . $value . "\"";
}
$newContent = substr($content, 0, $start);
$newContent .= $shortcode;
$newContent .= substr($content, $start + $end, strlen($content));
$wpdb->update(
'post_content',
['post_content' => $newContent],
['ID' => $postId]
);
}
}
}
}
echo $succeededFileCount . " files uploaded and imported successfully. <br />";
echo $failedFileCount . " files failed to uploaded or import successfully.";
}
get_header();
if (get_option('rmm_image_importer_key') != urldecode($_GET['key'])) {
echo '<div id="message" class="error">';
echo "<p><strong>Incorrect authentication key: you are not allowed to import images into this site.</strong></p></div>";
} else {
echo '<br /><br />';
$mtime = microtime();
$mtime = explode(" ", $mtime);
$mtime = $mtime[1] + $mtime[0];
$starttime = $mtime;
$dataset = get_option('rmm_image_importer_settings');
if (is_array($dataset)) {
foreach ($dataset as $data) {
if (isset($data['folder'])
|| isset($data['page'])) {
?>
<h2>Import from folder: <?php echo $data['folder']; ?></h2>
<p>
<?php
importImage(realpath(str_replace('//', '/', ABSPATH . '../../' . $data['folder'])), $data['page']); ?>
</p>
<?php
}
}
}
$mtime = microtime();
$mtime = explode(" ", $mtime);
$mtime = $mtime[1] + $mtime[0];
$endtime = $mtime;
$totaltime = ($endtime - $starttime);
echo 'Files imported to media library over ' . $totaltime . ' seconds.<br /><br />';
}
get_footer();
</code></pre>
| [
{
"answer_id": 273298,
"author": "Johansson",
"author_id": 94498,
"author_profile": "https://wordpress.stackexchange.com/users/94498",
"pm_score": 2,
"selected": false,
"text": "<p>There is already a built-in function created just for that purpose. You don't need to write walls of codes to uploads images from your disk. You can use <a href=\"https://codex.wordpress.org/Function_Reference/media_sideload_image\" rel=\"nofollow noreferrer\"><code>media_sideload_image</code></a> instead.</p>\n\n<p>This function will upload your files, take care of the file name, date, ID and the rest of the stuff. </p>\n\n<p>I haven't tested this with absolute path (It needs the URL), but it would be easy to convert absolute path to URLs, based on your skill in writing the above script.</p>\n\n<pre><code>// Set the directory\n$dir = ABSPATH .'/wpse';\n// Define the file type\n$images = glob($directory . \"*.jpg\");\n// Run a loop and upload every file to media library\nforeach($images as $image) {\n // Upload a single image\n media_sideload_image($image,'SOME POST ID HERE');\n}\n</code></pre>\n\n<p>That's all you need. Images must be attached to a post, but you can detach them afterward.</p>\n"
},
{
"answer_id": 273453,
"author": "Debbie Kurth",
"author_id": 119560,
"author_profile": "https://wordpress.stackexchange.com/users/119560",
"pm_score": -1,
"selected": false,
"text": "<p>Your server may also be limiting the total upload capacity, it not just what you set in the code. check with your provider or if you have access to the WHM, change the maxium php upload for the account (usually that is 8GB) and you will have to change the php.ini . The following URL was helpful to me when I had to do the same thing:</p>\n\n<p><a href=\"http://www.wpbeginner.com/wp-tutorials/how-to-increase-the-maximum-file-upload-size-in-wordpress/\" rel=\"nofollow noreferrer\">http://www.wpbeginner.com/wp-tutorials/how-to-increase-the-maximum-file-upload-size-in-wordpress/</a></p>\n\n<p>However, it is not a complete solution if the server you are on has a limit.</p>\n"
},
{
"answer_id": 273456,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 3,
"selected": true,
"text": "<p>A few things</p>\n\n<ul>\n<li>Use <code>media_handle_sideload</code> so that WordPress moves the files to the right location and validates them for you, creates the attachment post etc, none of this manual stuff</li>\n<li>Don't run this once and expect it to do everything. You're just going to run into the same problem but further into the import. If you give it infinite memory you'll have a time limit execution problem where the script simply runs out of time</li>\n<li>Process 5 files at a time, and repeatedly call run it until nothing is left to process</li>\n<li>Use a WP CLI command, don't bootstrap WordPress and call it from the GUI. Call it from Cron directly and skip the pinging a URL business. CLI commands get unlimited time to do their job, and you can't call them from the browser. The GET variable with the key becomes completely unnecessary.</li>\n<li>Escape escape escape, you're echoing out these arrays and values, assuming what they contain is safe, but what if I snuck a script tag in there? <code>Unable to delete file <script>...</script> after import.</code>. Biggest security step you can take that makes the most difference yet the least used</li>\n</ul>\n\n<h2>A Prototype WP CLI command</h2>\n\n<p>Here is a simple WP CLI command that should do the trick. I've not tested it but all the important parts are there, I trust you're not a complete novice when it comes to PHP and can tighten any loose screws or minor mistakes, no additional API knowledge necessary.</p>\n\n<p>You'll want to only include it when in a WP CLI context, for example:</p>\n\n<pre><code>if ( defined( 'WP_CLI' ) && WP_CLI ) {\n require_once dirname( __FILE__ ) . '/inc/class-plugin-cli-command.php';\n}\n</code></pre>\n\n<p>Modify accordingly, dumping the command in <code>functions.php</code> of a theme and expecting it all to work will cause errors as WP CLI classes are only loaded on the command line, never when handling a browser request.</p>\n\n<p>Usage:</p>\n\n<p><code>wp mbimport run</code></p>\n\n<p>Class:</p>\n\n<pre><code><?php\n/**\n * Implements image importer command.\n */\nclass MBronner_Import_Images extends WP_CLI_Command {\n\n /**\n * Runs the import script and imports several images\n *\n * ## EXAMPLES\n *\n * wp mbimport run\n *\n * @when after_wp_load\n */\n function run( $args, $assoc_args ) {\n if ( !function_exists('media_handle_upload') ) {\n require_once(ABSPATH . \"wp-admin\" . '/includes/image.php');\n require_once(ABSPATH . \"wp-admin\" . '/includes/file.php');\n require_once(ABSPATH . \"wp-admin\" . '/includes/media.php');\n }\n\n // Set the directory\n $dir = ABSPATH .'/wpse';\n // Define the file type\n $images = glob( $dir . \"*.jpg\" );\n if ( empty( $images ) {\n WP_CLI::success( 'no images to import' );\n exit;\n }\n // Run a loop and transfer every file to media library\n // $count = 0;\n foreach ( $images as $image ) {\n $file_array = array();\n $file_array['name'] = $image;\n $file_array['tmp_name'] = $image;\n\n $id = media_handle_sideload( $file_array, 0 );\n if ( is_wp_error( $id ) ) {\n WP_CLI::error( \"failed to sideload \".$image );\n exit;\n }\n\n // only do 5 at a time, dont worry we can run this\n // several times till they're all done\n $count++;\n if ( $count === 5 ) {\n break; \n }\n }\n WP_CLI::success( \"import ran\" );\n }\n}\n\nWP_CLI::add_command( 'mbimport', 'MBronner_Import_Images' );\n</code></pre>\n\n<p>Call repeatedly from a real cron job. If you can't, then either use WP Cron, or have a hook on <code>admin_init</code> that checks for a GET variable. Use the code inside the <code>run</code> command with some modifications.</p>\n\n<h2>When WP CLI Isn't An Option</h2>\n\n<p>Using a standalone PHP file that bootstraps WP is a security risk and a great target for attackers if they want to exhaust your server resources ( or trigger duplication issues by hitting the URL multiple times all at once ).</p>\n\n<p>For example:</p>\n\n<pre><code>// example.com/?mbimport=true\nadd_action( 'init', function() {\n if ( $_GET['action'] !== 'mbimport' ) {\n return;\n }\n if ( $_GET['key'] !== get_option('key thing' ) ) {\n return;\n }\n // the code from the run function in the CLI command, but with the WP_CLI::success bits swapped out\n // ...\n exit;\n}\n</code></pre>\n\n<h3>Repeated Calling</h3>\n\n<p>It might be that your external service can't call this repeatedly. To which I say:</p>\n\n<ul>\n<li>Don't rely on the external service, have your own server call it regardless, even if there's no work to do</li>\n<li>A standard WP Cron task would also work</li>\n<li>Run it every 5 minutes</li>\n<li><p>Make the task call itself if there's still stuff to do, using a nonblocking request. This way it'll keep spawning new instances until it's finished e.g.</p>\n\n<pre><code> if ( $count === 5 ) {\n wp_remote_get( home_url('?mbimport=true&key=abc'), [ 'blocking' => false ]);\n exit;\n )\n</code></pre></li>\n</ul>\n\n<h2>GUI?</h2>\n\n<p>If you want a progress meter for a UI in the dashboard, just count how many jpeg files are left in the folder to import. If you need to configure it, then build a UI and save the settings in options, then pull from options in the CLI script.</p>\n\n<h2>Have You Considered Using the REST API?</h2>\n\n<p>Sidestep the entire process and add the files via the REST API. You can do a POST request to <code>example.com/wp-json/wp/v2/media</code> to upload the jpegs. No code on your site necessary</p>\n\n<p><a href=\"https://stackoverflow.com/questions/37432114/wp-rest-api-upload-image\">https://stackoverflow.com/questions/37432114/wp-rest-api-upload-image</a></p>\n"
}
]
| 2017/07/10 | [
"https://wordpress.stackexchange.com/questions/272902",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/87803/"
]
| I am trying to upload many hundreds of images daily from a folder on the server to the media library using the following script that is scheduled via CRON:
```
<?php
require_once('../../../../public/wordpress/wp-load.php');
require_once('../../../../public/wordpress/wp-admin/includes/image.php');
function importImage($imagePath, $postId)
{
$succeededFileCount = 0;
$failedFileCount = 0;
$files = scandir($imagePath);
foreach ($files as $file) {
if (in_array($file, ['.', '..'])) {
continue;
}
$newPath = $imagePath . "/" . $file;
$filePath = realpath($newPath);
if (is_dir($newPath) && $item != '.' && $item != '..' && $item != 'failed_files') {
importImage($newPath, $postId);
} elseif ($item != '.' && $item != '..' && $item != 'failed_files') {
$filename = basename($file);
$uploadFile = wp_upload_bits($filename, null, file_get_contents($filePath));
$wp_upload_dir = wp_upload_dir();
if (! $uploadFile['error']) {
$fileType = wp_check_filetype($filename, null);
$attachment = [
'guid' => $wp_upload_dir['url'] . '/' . basename( $filename ),
'post_mime_type' => $fileType['type'],
'post_parent' => $postId,
'post_title' => preg_replace('/\.[^.]+$/', '', $filename),
'post_content' => '',
'post_status' => 'inherit'
];
$attachmentId = wp_insert_attachment($attachment, $uploadFile['file'], $postId);
if (! is_wp_error($attachmentId)) {
$attachmentData = wp_generate_attachment_metadata($attachmentId, $uploadFile['file']);
wp_update_attachment_metadata($attachmentId, $attachmentData);
}
} else {
echo '<span style="color: red; font-weight: bold;">Error: ' . $uploadFile['error'] . '</span>';
}
if ($attachmentId > 0) {
$succeededFileCount++;
echo '<span style="color: green; font-weight: normal;">File import succeeded: ' . $filePath . "</span><br />";
if (! unlink($filePath)) {
echo '<span style="color: red; font-weight: bold;">Unable to delete file ' . $filePath . " after import.</span><br />";
}
$page = get_post($postId);
if ($page->post_content) {
$content = $page->post_content;
$start = strpos($content, "[gallery ") + strlen("[gallery ");
$end = strpos(substr($content, $start), "]");
$shortcode = substr($content, $start, $end);
$attrs = shortcode_parse_atts($shortcode);
$attrs["ids"] .= "," . $attachmentId;
$tempIds = explode(",", $attrs["ids"]);
$tempIds = array_filter($tempIds);
rsort($tempIds);
$attrs["ids"] = implode(",", $tempIds);
$shortcode = "";
foreach ($attrs as $key => $value) {
if (strlen($shortcode) > 0) {
$shortcode .= " ";
}
$shortcode .= $key . "=\"" . $value . "\"";
}
$newContent = substr($content, 0, $start);
$newContent .= $shortcode;
$newContent .= substr($content, $start + $end, strlen($content));
$page->post_content = $newContent;
wp_update_post($page);
}
}
}
}
echo $succeededFileCount . " files uploaded and imported successfully. <br />";
echo $failedFileCount . " files failed to uploaded or import successfully.";
}
get_header();
if (get_option('rmm_image_importer_key') != urldecode($_GET['key'])) {
echo '<div id="message" class="error">';
echo "<p><strong>Incorrect authentication key: you are not allowed to import images into this site.</strong></p></div>";
} else {
echo '<br /><br />';
$mtime = microtime();
$mtime = explode(" ", $mtime);
$mtime = $mtime[1] + $mtime[0];
$starttime = $mtime;
$dataset = get_option('rmm_image_importer_settings');
if (is_array($dataset)) {
foreach ($dataset as $data) {
if (isset($data['folder'])
|| isset($data['page'])) {
?>
<h2>Import from folder: <?php echo $data['folder']; ?></h2>
<p>
<?php
importImage(realpath(str_replace('//', '/', ABSPATH . '../../' . $data['folder'])), $data['page']); ?>
</p>
<?php
}
}
}
$mtime = microtime();
$mtime = explode(" ", $mtime);
$mtime = $mtime[1] + $mtime[0];
$endtime = $mtime;
$totaltime = ($endtime - $starttime);
echo 'Files imported to media library over ' . $totaltime . ' seconds.<br /><br />';
}
get_footer();
```
The problem is that no matter what I do, the script fails after just two images with this error:
>
> Fatal error: Allowed memory size of 1073741824 bytes exhausted (tried
> to allocate 28672 bytes) in
> /home/forge/morselandcompany.com/public/wordpress/wp-includes/wp-db.php
> on line 1841
>
>
>
I have the memory limit set to 1024M in wordpress, as well as PHP. I don't see why this script should need more than 128M, really. How can this script be optimized to work properly? (Average image size is 800kB.)
Some initial debugging with BlackFire.io suggests the following memory hogs:
- wpdb->query: 3.2MB, called 31 times
- mysqli\_fetch\_object: 1.89MB, called 595 times
- run\_init() in wp-settings.php: 5.4MB, called once
In total blackfire suggests that over 8MB is required to run this script!
I have also tested with all plugins disabled, and that ended with the same result.
I am running on
- PHP 7.1
- Ubuntu 16.04
- DigitalOcean VPS (1 CPU, 1GB RAM)
- Wordpress 4.8
- NGINX 1.11.5
Thanks for any help!
**Update:** in the interest of completeness so that others may utilize the solution for memory leaks associated with get\_post and wp\_update\_post, I have posted the finalized code that solved the problem above. As you can see, the solution was to write my own queries using $wpdb instead of relying on the two WP methods causing the memory leaks:
```
<?php
require_once('../../../../public/wordpress/wp-load.php');
require_once(ABSPATH . 'wp-admin/includes/media.php');
require_once(ABSPATH . 'wp-admin/includes/file.php');
require_once(ABSPATH . 'wp-admin/includes/image.php');
function importImage($imagePath, $postId)
{
$succeededFileCount = 0;
$failedFileCount = 0;
$files = scandir($imagePath);
foreach ($files as $file) {
if (in_array($file, ['.', '..'])) {
continue;
}
$newPath = $imagePath . "/" . $file;
$filePath = realpath($newPath);
if (is_dir($newPath) && $file != 'failed_files') {
importImage($newPath, $postId);
} elseif ($file != 'failed_files') {
$webPath = str_replace($_SERVER['DOCUMENT_ROOT'], '', $imagePath);
$imageUrl = str_replace('/wordpress', '', get_site_url(null, "{$webPath}/" . urlencode($file)));
$imageUrl = str_replace(':8000', '', $imageUrl);
$attachmentId = media_sideload_image($imageUrl, 0, '', 'id');
if ($attachmentId > 0) {
$succeededFileCount++;
echo '<span style="color: green; font-weight: normal;">File import succeeded: ' . $filePath . "</span><br />";
if (! unlink($filePath)) {
echo '<span style="color: red; font-weight: bold;">Unable to delete file ' . $filePath . " after import.</span><br />";
}
global $wpdb;
$page = $wpdb->get_results("SELECT * FROM wp_posts WHERE ID = {$postId}")[0];
if (is_array($page)) {
$page = $page[0];
}
if ($page->post_content) {
$content = $page->post_content;
$start = strpos($content, "[gallery ") + strlen("[gallery ");
$end = strpos(substr($content, $start), "]");
$shortcode = substr($content, $start, $end);
$attrs = shortcode_parse_atts($shortcode);
$attrs["ids"] .= "," . $attachmentId;
$tempIds = explode(",", $attrs["ids"]);
$tempIds = array_filter($tempIds);
rsort($tempIds);
$attrs["ids"] = implode(",", $tempIds);
$shortcode = "";
foreach ($attrs as $key => $value) {
if (strlen($shortcode) > 0) {
$shortcode .= " ";
}
$shortcode .= $key . "=\"" . $value . "\"";
}
$newContent = substr($content, 0, $start);
$newContent .= $shortcode;
$newContent .= substr($content, $start + $end, strlen($content));
$wpdb->update(
'post_content',
['post_content' => $newContent],
['ID' => $postId]
);
}
}
}
}
echo $succeededFileCount . " files uploaded and imported successfully. <br />";
echo $failedFileCount . " files failed to uploaded or import successfully.";
}
get_header();
if (get_option('rmm_image_importer_key') != urldecode($_GET['key'])) {
echo '<div id="message" class="error">';
echo "<p><strong>Incorrect authentication key: you are not allowed to import images into this site.</strong></p></div>";
} else {
echo '<br /><br />';
$mtime = microtime();
$mtime = explode(" ", $mtime);
$mtime = $mtime[1] + $mtime[0];
$starttime = $mtime;
$dataset = get_option('rmm_image_importer_settings');
if (is_array($dataset)) {
foreach ($dataset as $data) {
if (isset($data['folder'])
|| isset($data['page'])) {
?>
<h2>Import from folder: <?php echo $data['folder']; ?></h2>
<p>
<?php
importImage(realpath(str_replace('//', '/', ABSPATH . '../../' . $data['folder'])), $data['page']); ?>
</p>
<?php
}
}
}
$mtime = microtime();
$mtime = explode(" ", $mtime);
$mtime = $mtime[1] + $mtime[0];
$endtime = $mtime;
$totaltime = ($endtime - $starttime);
echo 'Files imported to media library over ' . $totaltime . ' seconds.<br /><br />';
}
get_footer();
``` | A few things
* Use `media_handle_sideload` so that WordPress moves the files to the right location and validates them for you, creates the attachment post etc, none of this manual stuff
* Don't run this once and expect it to do everything. You're just going to run into the same problem but further into the import. If you give it infinite memory you'll have a time limit execution problem where the script simply runs out of time
* Process 5 files at a time, and repeatedly call run it until nothing is left to process
* Use a WP CLI command, don't bootstrap WordPress and call it from the GUI. Call it from Cron directly and skip the pinging a URL business. CLI commands get unlimited time to do their job, and you can't call them from the browser. The GET variable with the key becomes completely unnecessary.
* Escape escape escape, you're echoing out these arrays and values, assuming what they contain is safe, but what if I snuck a script tag in there? `Unable to delete file <script>...</script> after import.`. Biggest security step you can take that makes the most difference yet the least used
A Prototype WP CLI command
--------------------------
Here is a simple WP CLI command that should do the trick. I've not tested it but all the important parts are there, I trust you're not a complete novice when it comes to PHP and can tighten any loose screws or minor mistakes, no additional API knowledge necessary.
You'll want to only include it when in a WP CLI context, for example:
```
if ( defined( 'WP_CLI' ) && WP_CLI ) {
require_once dirname( __FILE__ ) . '/inc/class-plugin-cli-command.php';
}
```
Modify accordingly, dumping the command in `functions.php` of a theme and expecting it all to work will cause errors as WP CLI classes are only loaded on the command line, never when handling a browser request.
Usage:
`wp mbimport run`
Class:
```
<?php
/**
* Implements image importer command.
*/
class MBronner_Import_Images extends WP_CLI_Command {
/**
* Runs the import script and imports several images
*
* ## EXAMPLES
*
* wp mbimport run
*
* @when after_wp_load
*/
function run( $args, $assoc_args ) {
if ( !function_exists('media_handle_upload') ) {
require_once(ABSPATH . "wp-admin" . '/includes/image.php');
require_once(ABSPATH . "wp-admin" . '/includes/file.php');
require_once(ABSPATH . "wp-admin" . '/includes/media.php');
}
// Set the directory
$dir = ABSPATH .'/wpse';
// Define the file type
$images = glob( $dir . "*.jpg" );
if ( empty( $images ) {
WP_CLI::success( 'no images to import' );
exit;
}
// Run a loop and transfer every file to media library
// $count = 0;
foreach ( $images as $image ) {
$file_array = array();
$file_array['name'] = $image;
$file_array['tmp_name'] = $image;
$id = media_handle_sideload( $file_array, 0 );
if ( is_wp_error( $id ) ) {
WP_CLI::error( "failed to sideload ".$image );
exit;
}
// only do 5 at a time, dont worry we can run this
// several times till they're all done
$count++;
if ( $count === 5 ) {
break;
}
}
WP_CLI::success( "import ran" );
}
}
WP_CLI::add_command( 'mbimport', 'MBronner_Import_Images' );
```
Call repeatedly from a real cron job. If you can't, then either use WP Cron, or have a hook on `admin_init` that checks for a GET variable. Use the code inside the `run` command with some modifications.
When WP CLI Isn't An Option
---------------------------
Using a standalone PHP file that bootstraps WP is a security risk and a great target for attackers if they want to exhaust your server resources ( or trigger duplication issues by hitting the URL multiple times all at once ).
For example:
```
// example.com/?mbimport=true
add_action( 'init', function() {
if ( $_GET['action'] !== 'mbimport' ) {
return;
}
if ( $_GET['key'] !== get_option('key thing' ) ) {
return;
}
// the code from the run function in the CLI command, but with the WP_CLI::success bits swapped out
// ...
exit;
}
```
### Repeated Calling
It might be that your external service can't call this repeatedly. To which I say:
* Don't rely on the external service, have your own server call it regardless, even if there's no work to do
* A standard WP Cron task would also work
* Run it every 5 minutes
* Make the task call itself if there's still stuff to do, using a nonblocking request. This way it'll keep spawning new instances until it's finished e.g.
```
if ( $count === 5 ) {
wp_remote_get( home_url('?mbimport=true&key=abc'), [ 'blocking' => false ]);
exit;
)
```
GUI?
----
If you want a progress meter for a UI in the dashboard, just count how many jpeg files are left in the folder to import. If you need to configure it, then build a UI and save the settings in options, then pull from options in the CLI script.
Have You Considered Using the REST API?
---------------------------------------
Sidestep the entire process and add the files via the REST API. You can do a POST request to `example.com/wp-json/wp/v2/media` to upload the jpegs. No code on your site necessary
<https://stackoverflow.com/questions/37432114/wp-rest-api-upload-image> |
272,925 | <p>I've read a bunch of articles about <a href="https://docs.woocommerce.com/document/template-structure/" rel="nofollow noreferrer">overriding the default /woocommerce/ templates</a> and tried implementing the following (which were the best/most relevant that I could find all to no avail):</p>
<ul>
<li><a href="https://wordpress.stackexchange.com/questions/110602/load-woocommerce-templates-from-my-plugin-folder-first">Load WooCommerce templates from my plugin folder first</a> </li>
<li><a href="https://www.skyverge.com/blog/override-woocommerce-template-file-within-a-plugin/" rel="nofollow noreferrer">Override WooCommerce Template File Within a Plugin</a></li>
</ul>
<p>Essentially, what I would like to accomplish is: load all template files (for archives and posts not just template parts) from ~/wp-content/my-plugin/templates/woocommerce/* UNLESS the files are in my theme (and I don't have to override each file instance in my function) . For instance:</p>
<ul>
<li><code>~/wp-content/my-plugin/templates/woocommerce/single-product.php</code> <em>(this seems like it just doesn't want to load via plugin)</em></li>
<li><code>~/wp-content/my-plugin/templates/woocommerce/archive-products.php</code> <em>(this seems like it just doesn't want to load via plugin)</em></li>
<li><code>~/wp-content/my-plugin/templates/woocommerce-pdf-invoices-packing-slips/*</code> <em>(I also want to be able to <strong>override other plugin extension templates</strong> just like I would be able to in my child theme)</em></li>
</ul>
<p><strong>EDIT:</strong></p>
<p>The friendly folks at <a href="https://www.skyverge.com/blog/override-woocommerce-template-file-within-a-plugin/" rel="nofollow noreferrer">SkyVerge</a> sent me the following code, which I tested and confirm that it works for template <em>parts</em>.</p>
<pre><code>// Locate the template in a plugin
function myplugin_woocommerce_locate_template( $template, $template_name, $template_path ) {
$_template = $template;
if ( ! $template_path ) {
$template_path = WC()->template_path();
}
$plugin_path = myplugin_plugin_path() . '/templates/';
// Look within passed path within the theme - this is priority
$template = locate_template(
array(
trailingslashit( $template_path ) . $template_name,
$template_name
)
);
// Modification: Get the template from this plugin, if it exists
if ( ! $template && file_exists( $plugin_path . $template_name ) ) {
$template = $plugin_path . $template_name;
}
// Use default template
if ( ! $template ) {
$template = $_template;
}
return $template;
}
add_filter( 'woocommerce_locate_template', 'myplugin_woocommerce_locate_template', 10, 3 );
// Helper to get the plugin's path on the server
function myplugin_plugin_path() {
// gets the absolute path to this plugin directory
return untrailingslashit( plugin_dir_path( __FILE__ ) );
}
</code></pre>
<p>The above code works for something like:</p>
<ul>
<li><code>~/myplugin/templates/single-product/product-image.php</code></li>
</ul>
<p>But does NOT work for: </p>
<ul>
<li><code>~/myplugin/templates/single-product.php</code></li>
</ul>
<p>Where I'm getting stuck:</p>
<ul>
<li>There are solutions to override bits and pieces of WC templates, but there I've not found / been able to create a solution that does <em>comprehensive</em> overrides (i.e. overriding ability just like a child theme would)</li>
<li>I can't seem to find the right combination of filter hooks; single-product.php and archive-product.php seem to be controlled by functions outside the standard WC template functions</li>
</ul>
<p>Thanks in advance!</p>
| [
{
"answer_id": 272930,
"author": "Syed Abuthahir M",
"author_id": 112046,
"author_profile": "https://wordpress.stackexchange.com/users/112046",
"pm_score": 0,
"selected": false,
"text": "<p>In this scenario you can use the following filter wc_get_template_part.</p>\n\n<p>Hook reference link: \n<a href=\"https://docs.woocommerce.com/wc-apidocs/source-function-wc_get_template_part.html#142-175\" rel=\"nofollow noreferrer\">wc_get_template_part</a></p>\n\n<p>If you don't know how to use filters read this article <a href=\"http://docs.presscustomizr.com/article/26-wordpress-actions-filters-and-hooks-a-guide-for-non-developers\" rel=\"nofollow noreferrer\">wordpress hooks for non developers</a></p>\n"
},
{
"answer_id": 273032,
"author": "Syed Abuthahir M",
"author_id": 112046,
"author_profile": "https://wordpress.stackexchange.com/users/112046",
"pm_score": 2,
"selected": false,
"text": "<pre><code>function woo_template_replace( $located, $template_name, $args, $template_path, $default_path ) {\n\nif( file_exists( plugin_dir_path(__FILE__) . 'templates/' . $template_name ) ) {\n $located = plugin_dir_path(__FILE__) . 'templates/' . $template_name;\n}\n\nreturn $located;\n}\n\n\nfunction woo_get_template_part( $template , $slug , $name ) {\n\nif( empty( $name ) ) {\n if( file_exists( plugin_dir_path(__FILE__) . \"/templates/{$slug}.php\" ) ) {\n $template = plugin_dir_path(__FILE__) . \"/templates/{$slug}.php\";\n }\n} else {\n if( file_exists( plugin_dir_path(__FILE__) . \"/templates/{$slug}-{$name}.php\" ) ) {\n $template = plugin_dir_path(__FILE__) . \"/templates/{$slug}-{$name}.php\";\n }\nreturn $template;\n}\n\nadd_filter( 'wc_get_template' , 'woo_template_replace' , 10 , 5 );\n\nadd_filter( 'wc_get_template_part' , 'woo_get_template_part' , 10 , 3 );\n</code></pre>\n\n<p>You can use this snippet in your plugin root file and place your all woocommerce templates file in templates directory.</p>\n\n<p>Plugin structure for reference</p>\n\n<pre><code>plugins\n woo-template-replace (plugin root folder)\n woo-template-replace.php (plugin root file)\n templates (folder)\n single-content.php (woocommerce template file)\n searchform.php (woocommerce template file)\n</code></pre>\n"
},
{
"answer_id": 344299,
"author": "Maher Aldous",
"author_id": 172281,
"author_profile": "https://wordpress.stackexchange.com/users/172281",
"pm_score": -1,
"selected": false,
"text": "<p>If you want to overriding the templates for WooCommerce, then I have your answer.\nI just have created a complate WooCommerce Theme to my client and Support Everthing in WooCommerce so let's get started.</p>\n\n<p>First of all before doing anything this page is very good if you read it slowly <a href=\"https://docs.woocommerce.com/document/template-structure/\" rel=\"nofollow noreferrer\">WooCommerce Overriding the plugins templates</a>.</p>\n\n<p>Step 1:\nIn the functions.php add the WooCommerce Support</p>\n\n<pre><code>if (!function_exists( 'albadrbakelser_setup')) :\n function albadrbakelser_setup() {\n\n // Add Woocommerce Support\n add_theme_support(\n 'woocommerce', array(\n //'thumbnail_image_width' => 150,\n // 'gallery_thumbnail_image_width' => 100,\n //'single_image_width' => 300,\n\n 'product_grid' => array(\n 'default_rows' => 5,\n 'min_rows' => 1,\n 'max_rows' => 10,\n 'default_columns' => 4,\n 'min_columns' => 1,\n 'max_columns' => 4,\n ),\n )\n );\n add_theme_support( 'wc-product-gallery-zoom' );\n add_theme_support( 'wc-product-gallery-lightbox' );\n add_theme_support( 'wc-product-gallery-slider' );\n\n\n }\nendif;\nadd_action( 'after_setup_theme', 'albadrbakelser_setup' );\n</code></pre>\n\n<p>OR you can use just this if you don't want everythings</p>\n\n<pre><code>function mytheme_add_woocommerce_support() {\n add_theme_support( 'woocommerce' );\n}\nadd_action( 'after_setup_theme', 'mytheme_add_woocommerce_support' );\n</code></pre>\n\n<p>Step 2:\nOverride something.</p>\n\n<p>Example: To add \"Hello\" to the single product title\ncopy: <code>wp-content/plugins/woocommerce/single-product/title.php</code> <strong>to</strong> <code>wp-content/themes/yourtheme/woocommerce/single-product/title.php</code></p>\n\n<p>Then Open the title.php that you have copied in this direction <code>wp-content/themes/yourtheme/woocommerce/single-product/title.php</code> and write Hello between the <code>h1 html tag</code> like this <code><h1>Hello</h1></code>. Then save the file</p>\n\n<p>Last Step:\nGo to the single product in your site to check if the Hello is there.\nMake sure you have created a product to visit.</p>\n\n<p><strong>Results</strong>:</p>\n\n<p><a href=\"https://i.stack.imgur.com/429Xc.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/429Xc.jpg\" alt=\"Results\"></a></p>\n\n<p><strong>Note</strong>:</p>\n\n<p>In case nothings work try to create woocommerce.php file in your root by following this page <a href=\"https://docs.woocommerce.com/document/third-party-custom-theme-compatibility/\" rel=\"nofollow noreferrer\">https://docs.woocommerce.com/document/third-party-custom-theme-compatibility/</a></p>\n\n<p>This is the page to start with\nthe add support <a href=\"https://github.com/woocommerce/woocommerce/wiki/Declaring-WooCommerce-support-in-themes\" rel=\"nofollow noreferrer\">https://github.com/woocommerce/woocommerce/wiki/Declaring-WooCommerce-support-in-themes</a></p>\n"
},
{
"answer_id": 344376,
"author": "Sally CJ",
"author_id": 137402,
"author_profile": "https://wordpress.stackexchange.com/users/137402",
"pm_score": 2,
"selected": false,
"text": "<p>WooCommerce uses the <code>template_include</code> filter/hook to load main templates like <code>archive-product.php</code> and <code>single-product.php</code>. And <a href=\"https://docs.woocommerce.com/wc-apidocs/class-WC_Template_Loader.html\" rel=\"nofollow noreferrer\">here's</a> the class which handles main templates.</p>\n\n<p>And there's a filter in that class which you can use to capture the default file (name) which WooCommerce loads based on the current request/page — e.g. <code>single-product.php</code> for single product pages.</p>\n\n<p>You can't, however, simply hook to that filter, return a custom template path and expect it to be used (because the path has to be relative to the active theme folder). But you can do something like in the second snippet below (which is tried & tested working on WordPress 5.2.2 with WooCommerce 3.6.5, the latest version as of writing):</p>\n\n<ol>\n<li><p>First, a helper function:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>// Helper function to load a WooCommerce template or template part file from the\n// active theme or a plugin folder.\nfunction my_load_wc_template_file( $template_name ) {\n // Check theme folder first - e.g. wp-content/themes/my-theme/woocommerce.\n $file = get_stylesheet_directory() . '/woocommerce/' . $template_name;\n if ( @file_exists( $file ) ) {\n return $file;\n }\n\n // Now check plugin folder - e.g. wp-content/plugins/my-plugin/woocommerce.\n $file = 'full/path/to/your/plugin/' . 'woocommerce/' . $template_name;\n if ( @file_exists( $file ) ) {\n return $file;\n }\n}\n</code></pre></li>\n<li><p>To override main WooCommerce templates (e.g. <code>single-product.php</code>):</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>add_filter( 'woocommerce_template_loader_files', function( $templates, $template_name ){\n // Capture/cache the $template_name which is a file name like single-product.php\n wp_cache_set( 'my_wc_main_template', $template_name ); // cache the template name\n return $templates;\n}, 10, 2 );\n\nadd_filter( 'template_include', function( $template ){\n if ( $template_name = wp_cache_get( 'my_wc_main_template' ) ) {\n wp_cache_delete( 'my_wc_main_template' ); // delete the cache\n if ( $file = my_load_wc_template_file( $template_name ) ) {\n return $file;\n }\n }\n return $template;\n}, 11 );\n</code></pre></li>\n<li><p>To override WooCommerce template parts (retrieved using <code>wc_get_template_part()</code>):</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>add_filter( 'wc_get_template_part', function( $template, $slug, $name ){\n $file = my_load_wc_template_file( \"{$slug}-{$name}.php\" );\n return $file ? $file : $template;\n}, 10, 3 );\n</code></pre></li>\n<li><p>To override other WooCommerce templates (retrieved using <code>wc_get_template()</code> or <code>wc_locate_template()</code>):</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>add_filter( 'woocommerce_locate_template', function( $template, $template_name ){\n $file = my_load_wc_template_file( $template_name );\n return $file ? $file : $template;\n}, 10, 2 );\n</code></pre></li>\n</ol>\n\n<p>Btw, there's also the <code>woocommerce_template_path</code> filter for those of you who're just looking to change the default WooCommerce templates folder (<code>woocommerce</code>) <em>in the active theme folder</em>.</p>\n"
}
]
| 2017/07/10 | [
"https://wordpress.stackexchange.com/questions/272925",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/47880/"
]
| I've read a bunch of articles about [overriding the default /woocommerce/ templates](https://docs.woocommerce.com/document/template-structure/) and tried implementing the following (which were the best/most relevant that I could find all to no avail):
* [Load WooCommerce templates from my plugin folder first](https://wordpress.stackexchange.com/questions/110602/load-woocommerce-templates-from-my-plugin-folder-first)
* [Override WooCommerce Template File Within a Plugin](https://www.skyverge.com/blog/override-woocommerce-template-file-within-a-plugin/)
Essentially, what I would like to accomplish is: load all template files (for archives and posts not just template parts) from ~/wp-content/my-plugin/templates/woocommerce/\* UNLESS the files are in my theme (and I don't have to override each file instance in my function) . For instance:
* `~/wp-content/my-plugin/templates/woocommerce/single-product.php` *(this seems like it just doesn't want to load via plugin)*
* `~/wp-content/my-plugin/templates/woocommerce/archive-products.php` *(this seems like it just doesn't want to load via plugin)*
* `~/wp-content/my-plugin/templates/woocommerce-pdf-invoices-packing-slips/*` *(I also want to be able to **override other plugin extension templates** just like I would be able to in my child theme)*
**EDIT:**
The friendly folks at [SkyVerge](https://www.skyverge.com/blog/override-woocommerce-template-file-within-a-plugin/) sent me the following code, which I tested and confirm that it works for template *parts*.
```
// Locate the template in a plugin
function myplugin_woocommerce_locate_template( $template, $template_name, $template_path ) {
$_template = $template;
if ( ! $template_path ) {
$template_path = WC()->template_path();
}
$plugin_path = myplugin_plugin_path() . '/templates/';
// Look within passed path within the theme - this is priority
$template = locate_template(
array(
trailingslashit( $template_path ) . $template_name,
$template_name
)
);
// Modification: Get the template from this plugin, if it exists
if ( ! $template && file_exists( $plugin_path . $template_name ) ) {
$template = $plugin_path . $template_name;
}
// Use default template
if ( ! $template ) {
$template = $_template;
}
return $template;
}
add_filter( 'woocommerce_locate_template', 'myplugin_woocommerce_locate_template', 10, 3 );
// Helper to get the plugin's path on the server
function myplugin_plugin_path() {
// gets the absolute path to this plugin directory
return untrailingslashit( plugin_dir_path( __FILE__ ) );
}
```
The above code works for something like:
* `~/myplugin/templates/single-product/product-image.php`
But does NOT work for:
* `~/myplugin/templates/single-product.php`
Where I'm getting stuck:
* There are solutions to override bits and pieces of WC templates, but there I've not found / been able to create a solution that does *comprehensive* overrides (i.e. overriding ability just like a child theme would)
* I can't seem to find the right combination of filter hooks; single-product.php and archive-product.php seem to be controlled by functions outside the standard WC template functions
Thanks in advance! | ```
function woo_template_replace( $located, $template_name, $args, $template_path, $default_path ) {
if( file_exists( plugin_dir_path(__FILE__) . 'templates/' . $template_name ) ) {
$located = plugin_dir_path(__FILE__) . 'templates/' . $template_name;
}
return $located;
}
function woo_get_template_part( $template , $slug , $name ) {
if( empty( $name ) ) {
if( file_exists( plugin_dir_path(__FILE__) . "/templates/{$slug}.php" ) ) {
$template = plugin_dir_path(__FILE__) . "/templates/{$slug}.php";
}
} else {
if( file_exists( plugin_dir_path(__FILE__) . "/templates/{$slug}-{$name}.php" ) ) {
$template = plugin_dir_path(__FILE__) . "/templates/{$slug}-{$name}.php";
}
return $template;
}
add_filter( 'wc_get_template' , 'woo_template_replace' , 10 , 5 );
add_filter( 'wc_get_template_part' , 'woo_get_template_part' , 10 , 3 );
```
You can use this snippet in your plugin root file and place your all woocommerce templates file in templates directory.
Plugin structure for reference
```
plugins
woo-template-replace (plugin root folder)
woo-template-replace.php (plugin root file)
templates (folder)
single-content.php (woocommerce template file)
searchform.php (woocommerce template file)
``` |
272,928 | <p>I've managed to get the behaviour I want by modifying some plugin code. However, I would like to move my modifications outside of the plugin code using the provided hook, but I can't seem make it work. The hook uses do_action_ref_array.</p>
<p>The situation is not helped by the fact that the only way I can find to access the php vars is by sending error messages to the debug.log file.</p>
<p>(like so):</p>
<pre><code>function ra_func1($args) {
$str = print_r($args, true);
error_log($str);
}
add_action ( 'bookly_validate_custom_field', 'ra_func1', 10, 3);
</code></pre>
<p>Trouble is there's a mixture of objects and arrays and I'm now really stuck, having spent a lot of time trying to get this working. If anyone could provide a working callback that does what I want I would be very grateful.</p>
<p>Original plugin code:</p>
<pre><code>public function validateCustomFields( $value, $form_id, $cart_key )
{
$decoded_value = json_decode( $value );
$fields = array();
foreach ( json_decode( get_option( 'bookly_custom_fields' ) ) as $field ) {
$fields[ $field->id ] = $field;
}
foreach ( $decoded_value as $field ) {
if ( isset( $fields[ $field->id ] ) ) {
if ( ( $fields[ $field->id ]->type == 'captcha' ) && ! Captcha\Captcha::validate( $form_id, $field->value ) ) {
$this->errors['custom_fields'][ $cart_key ][ $field->id ] = __( 'Incorrect code', 'bookly' );
} elseif ( $fields[ $field->id ]->required && empty ( $field->value ) && $field->value != '0' ) {
$this->errors['custom_fields'][ $cart_key ][ $field->id ] = __( 'Required', 'bookly' );
} else {
/**
* Custom field validation for a third party,
* if the value is not valid then please add an error message like in the above example.
*
* @param \stdClass
* @param ref array
* @param string
* @param \stdClass
*/
do_action_ref_array( 'bookly_validate_custom_field', array( $field, &$this->errors, $cart_key, $fields[ $field->id ] ) );
}
}
}
}
</code></pre>
<p>Code with the beginnings of the functionality I want to add via an external callback:</p>
<pre><code>public function validateCustomFields( $value, $form_id, $cart_key )
{
$decoded_value = json_decode( $value );
$fields = array();
foreach ( json_decode( get_option( 'bookly_custom_fields' ) ) as $field ) {
$fields[ $field->id ] = $field;
}
foreach ( $decoded_value as $field ) {
if ( isset( $fields[ $field->id ] ) ) {
if ( ( $fields[ $field->id ]->type == 'captcha' ) && ! Captcha\Captcha::validate( $form_id, $field->value ) ) {
$this->errors['custom_fields'][ $cart_key ][ $field->id ] = __( 'Incorrect code', 'bookly' );
} elseif ( $fields[ $field->id ]->required && empty ( $field->value ) && $field->value != '0' ) {
$this->errors['custom_fields'][ $cart_key ][ $field->id ] = __( 'Required', 'bookly' );
} else {
/**
* Custom field validation for a third party,
* if the value is not valid then please add an error message like in the above example.
*
* @param \stdClass
* @param ref array
* @param string
* @param \stdClass
*/
//
if ($fields[$field->id]->id == 12372){
$this->errors['custom_fields'][ $cart_key ][ $field->id ] = __( 'Post Code Error', 'bookly' );
}
}
}
}
}
</code></pre>
| [
{
"answer_id": 272934,
"author": "Syed Abuthahir M",
"author_id": 112046,
"author_profile": "https://wordpress.stackexchange.com/users/112046",
"pm_score": 0,
"selected": false,
"text": "<p>You need to write custom function in functions.php with name of <code>bookly_validate_custom_field</code> and pass 5 arguments to that function</p>\n\n<p>For example </p>\n\n<pre><code>function bookly_validate_custom_field ( $field, &$errors, $cart_key, $field_id ) {\nif ($field_id] == 12372){\n$errors['custom_fields'][ $cart_key ][ $field_id ] = __( 'Post Code Error', 'bookly' );\n}}\n</code></pre>\n\n<p><strong>Don't forget to put '&' symbol in front of errors variable.</strong></p>\n\n<p>Reference link:\n<a href=\"https://codex.wordpress.org/Function_Reference/do_action_ref_array\" rel=\"nofollow noreferrer\">do_action_ref_array</a></p>\n"
},
{
"answer_id": 273478,
"author": "rtpHarry",
"author_id": 60500,
"author_profile": "https://wordpress.stackexchange.com/users/60500",
"pm_score": 2,
"selected": true,
"text": "<p>That feature exists because I bugged them to implement it :)</p>\n\n<ul>\n<li><a href=\"https://support.booking-wp-plugin.com/hc/en-us/community/posts/207263389-Add-a-WordPress-hook-for-custom-validators-on-the-custom-fields?page=1#community_comment_115001021885\" rel=\"nofollow noreferrer\">https://support.booking-wp-plugin.com/hc/en-us/community/posts/207263389-Add-a-WordPress-hook-for-custom-validators-on-the-custom-fields?page=1#community_comment_115001021885</a></li>\n</ul>\n\n<p>Using it confused me as well but somebody finally replied to this just the other day with this snippet:</p>\n\n<pre><code>add_action( 'bookly_validate_custom_field', function ( \\stdClass $field, &$errors, $cart_key, \\stdClass $field_info ) {\n // Validation by custom_field id\n switch ( $field->id ) {\n case 'id_value':\n if ( /*$invalid == */ true ) {\n $errors['custom_fields'][ $cart_key ][ $field->id ] = __( 'Invalid', 'bookly' );\n }\n break;\n }\n}, 10, 4 );\n</code></pre>\n"
}
]
| 2017/07/10 | [
"https://wordpress.stackexchange.com/questions/272928",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/98276/"
]
| I've managed to get the behaviour I want by modifying some plugin code. However, I would like to move my modifications outside of the plugin code using the provided hook, but I can't seem make it work. The hook uses do\_action\_ref\_array.
The situation is not helped by the fact that the only way I can find to access the php vars is by sending error messages to the debug.log file.
(like so):
```
function ra_func1($args) {
$str = print_r($args, true);
error_log($str);
}
add_action ( 'bookly_validate_custom_field', 'ra_func1', 10, 3);
```
Trouble is there's a mixture of objects and arrays and I'm now really stuck, having spent a lot of time trying to get this working. If anyone could provide a working callback that does what I want I would be very grateful.
Original plugin code:
```
public function validateCustomFields( $value, $form_id, $cart_key )
{
$decoded_value = json_decode( $value );
$fields = array();
foreach ( json_decode( get_option( 'bookly_custom_fields' ) ) as $field ) {
$fields[ $field->id ] = $field;
}
foreach ( $decoded_value as $field ) {
if ( isset( $fields[ $field->id ] ) ) {
if ( ( $fields[ $field->id ]->type == 'captcha' ) && ! Captcha\Captcha::validate( $form_id, $field->value ) ) {
$this->errors['custom_fields'][ $cart_key ][ $field->id ] = __( 'Incorrect code', 'bookly' );
} elseif ( $fields[ $field->id ]->required && empty ( $field->value ) && $field->value != '0' ) {
$this->errors['custom_fields'][ $cart_key ][ $field->id ] = __( 'Required', 'bookly' );
} else {
/**
* Custom field validation for a third party,
* if the value is not valid then please add an error message like in the above example.
*
* @param \stdClass
* @param ref array
* @param string
* @param \stdClass
*/
do_action_ref_array( 'bookly_validate_custom_field', array( $field, &$this->errors, $cart_key, $fields[ $field->id ] ) );
}
}
}
}
```
Code with the beginnings of the functionality I want to add via an external callback:
```
public function validateCustomFields( $value, $form_id, $cart_key )
{
$decoded_value = json_decode( $value );
$fields = array();
foreach ( json_decode( get_option( 'bookly_custom_fields' ) ) as $field ) {
$fields[ $field->id ] = $field;
}
foreach ( $decoded_value as $field ) {
if ( isset( $fields[ $field->id ] ) ) {
if ( ( $fields[ $field->id ]->type == 'captcha' ) && ! Captcha\Captcha::validate( $form_id, $field->value ) ) {
$this->errors['custom_fields'][ $cart_key ][ $field->id ] = __( 'Incorrect code', 'bookly' );
} elseif ( $fields[ $field->id ]->required && empty ( $field->value ) && $field->value != '0' ) {
$this->errors['custom_fields'][ $cart_key ][ $field->id ] = __( 'Required', 'bookly' );
} else {
/**
* Custom field validation for a third party,
* if the value is not valid then please add an error message like in the above example.
*
* @param \stdClass
* @param ref array
* @param string
* @param \stdClass
*/
//
if ($fields[$field->id]->id == 12372){
$this->errors['custom_fields'][ $cart_key ][ $field->id ] = __( 'Post Code Error', 'bookly' );
}
}
}
}
}
``` | That feature exists because I bugged them to implement it :)
* <https://support.booking-wp-plugin.com/hc/en-us/community/posts/207263389-Add-a-WordPress-hook-for-custom-validators-on-the-custom-fields?page=1#community_comment_115001021885>
Using it confused me as well but somebody finally replied to this just the other day with this snippet:
```
add_action( 'bookly_validate_custom_field', function ( \stdClass $field, &$errors, $cart_key, \stdClass $field_info ) {
// Validation by custom_field id
switch ( $field->id ) {
case 'id_value':
if ( /*$invalid == */ true ) {
$errors['custom_fields'][ $cart_key ][ $field->id ] = __( 'Invalid', 'bookly' );
}
break;
}
}, 10, 4 );
``` |
272,936 | <p>To avoid image caching issues, I would like to get WordPress to reference my jpeg images with a URL parameter. I know in javascript I can do this: </p>
<pre><code><img id="idSigma" src="#" class="classSigma">
<script>
$(document).ready(function() {
var d = new Date();
$("#idSigma").attr("src", "images/Sigma.jpeg?t=" + d.getTime());
});
</script>
</code></pre>
<p>Is there a way I can get wordpress to do this to all of its internal links. For example, if I right click on an image in a blog post and click on open image it would already be pointing to the link with the URL parameter. This will ensure all the images are fresh since I plan on updating them daily. My first thought was to look for this code in media.php but maybe there is a better way than modifying the source code. </p>
<hr>
<p>Edit, here is what I have so far, it works in my php emulator when I set the $content variable but not doing anything in wordpress:</p>
<pre><code>function add_jpeg_params($content){
preg_match_all("/https?:\/\/[^\/\s]+\/\S+\.(jpg|jpeg)/", $content, $output_array);
$items_to_replace = array_unique($output_array[0]);
$items_to_replace = array_values($items_to_replace);
for ($j = 0; $j < sizeof($items_to_replace); $j++) {
$content = preg_replace('~' . $items_to_replace[$j] . '~', $items_to_replace[$j] . '?t=' . time(), $content);
}
return $content;
}
add_filter('the_content','add_jpeg_params');
</code></pre>
<p>I've added this in functions.php in my wordpress theme. </p>
<p>Edit 2: Solution posted below. The hook I needed was 'post_thumbnail_html'. </p>
| [
{
"answer_id": 272934,
"author": "Syed Abuthahir M",
"author_id": 112046,
"author_profile": "https://wordpress.stackexchange.com/users/112046",
"pm_score": 0,
"selected": false,
"text": "<p>You need to write custom function in functions.php with name of <code>bookly_validate_custom_field</code> and pass 5 arguments to that function</p>\n\n<p>For example </p>\n\n<pre><code>function bookly_validate_custom_field ( $field, &$errors, $cart_key, $field_id ) {\nif ($field_id] == 12372){\n$errors['custom_fields'][ $cart_key ][ $field_id ] = __( 'Post Code Error', 'bookly' );\n}}\n</code></pre>\n\n<p><strong>Don't forget to put '&' symbol in front of errors variable.</strong></p>\n\n<p>Reference link:\n<a href=\"https://codex.wordpress.org/Function_Reference/do_action_ref_array\" rel=\"nofollow noreferrer\">do_action_ref_array</a></p>\n"
},
{
"answer_id": 273478,
"author": "rtpHarry",
"author_id": 60500,
"author_profile": "https://wordpress.stackexchange.com/users/60500",
"pm_score": 2,
"selected": true,
"text": "<p>That feature exists because I bugged them to implement it :)</p>\n\n<ul>\n<li><a href=\"https://support.booking-wp-plugin.com/hc/en-us/community/posts/207263389-Add-a-WordPress-hook-for-custom-validators-on-the-custom-fields?page=1#community_comment_115001021885\" rel=\"nofollow noreferrer\">https://support.booking-wp-plugin.com/hc/en-us/community/posts/207263389-Add-a-WordPress-hook-for-custom-validators-on-the-custom-fields?page=1#community_comment_115001021885</a></li>\n</ul>\n\n<p>Using it confused me as well but somebody finally replied to this just the other day with this snippet:</p>\n\n<pre><code>add_action( 'bookly_validate_custom_field', function ( \\stdClass $field, &$errors, $cart_key, \\stdClass $field_info ) {\n // Validation by custom_field id\n switch ( $field->id ) {\n case 'id_value':\n if ( /*$invalid == */ true ) {\n $errors['custom_fields'][ $cart_key ][ $field->id ] = __( 'Invalid', 'bookly' );\n }\n break;\n }\n}, 10, 4 );\n</code></pre>\n"
}
]
| 2017/07/10 | [
"https://wordpress.stackexchange.com/questions/272936",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/123537/"
]
| To avoid image caching issues, I would like to get WordPress to reference my jpeg images with a URL parameter. I know in javascript I can do this:
```
<img id="idSigma" src="#" class="classSigma">
<script>
$(document).ready(function() {
var d = new Date();
$("#idSigma").attr("src", "images/Sigma.jpeg?t=" + d.getTime());
});
</script>
```
Is there a way I can get wordpress to do this to all of its internal links. For example, if I right click on an image in a blog post and click on open image it would already be pointing to the link with the URL parameter. This will ensure all the images are fresh since I plan on updating them daily. My first thought was to look for this code in media.php but maybe there is a better way than modifying the source code.
---
Edit, here is what I have so far, it works in my php emulator when I set the $content variable but not doing anything in wordpress:
```
function add_jpeg_params($content){
preg_match_all("/https?:\/\/[^\/\s]+\/\S+\.(jpg|jpeg)/", $content, $output_array);
$items_to_replace = array_unique($output_array[0]);
$items_to_replace = array_values($items_to_replace);
for ($j = 0; $j < sizeof($items_to_replace); $j++) {
$content = preg_replace('~' . $items_to_replace[$j] . '~', $items_to_replace[$j] . '?t=' . time(), $content);
}
return $content;
}
add_filter('the_content','add_jpeg_params');
```
I've added this in functions.php in my wordpress theme.
Edit 2: Solution posted below. The hook I needed was 'post\_thumbnail\_html'. | That feature exists because I bugged them to implement it :)
* <https://support.booking-wp-plugin.com/hc/en-us/community/posts/207263389-Add-a-WordPress-hook-for-custom-validators-on-the-custom-fields?page=1#community_comment_115001021885>
Using it confused me as well but somebody finally replied to this just the other day with this snippet:
```
add_action( 'bookly_validate_custom_field', function ( \stdClass $field, &$errors, $cart_key, \stdClass $field_info ) {
// Validation by custom_field id
switch ( $field->id ) {
case 'id_value':
if ( /*$invalid == */ true ) {
$errors['custom_fields'][ $cart_key ][ $field->id ] = __( 'Invalid', 'bookly' );
}
break;
}
}, 10, 4 );
``` |
272,962 | <p>I can't find any information anywhere about what data I need to give exactly. When I try to read the data from one of my posts with a thumbnail already I get this but there's not way you have to enter all this info just to add a featured image:</p>
<pre><code> thumbnail:
{ attachment_id: '360',
date_created_gmt: 2017-07-11T04:51:15.000Z,
parent: 245,
link: 'http://xxxxxxxxxxxx.org/wp-content/uploads/2017/07/japanese-rice-bowl-pottery.jpg',
title: 'japanese-rice-bowl-pottery.jpg',
caption: '',
description: '',
metadata: [Object],
type: 'image/jpg',
thumbnail: 'http://xxxxxxxxxxxx.org/wp-content/uploads/2017/07/japanese-rice-bowl-pottery-150x150.jpg' } }
</code></pre>
<p>An example of code I tried to use to post with Node.js</p>
<pre><code>client.editPost(posts[0].id, {thumbnail : { thumbnail : "http://xxxxxxxxxxxxx.org/wp-content/uploads/2017/07/japanese-rice-bowl-pottery-150x150.jpg" } }, function( error ) {})
</code></pre>
| [
{
"answer_id": 273086,
"author": "cooldude101",
"author_id": 123580,
"author_profile": "https://wordpress.stackexchange.com/users/123580",
"pm_score": 1,
"selected": false,
"text": "<p>I found my problem and just passing it on in case someone googles this.</p>\n\n<p>You need to pass the image id like this</p>\n\n<p>{thumbnail: 123}</p>\n\n<p>Replace 123 with your image id.</p>\n\n<p>all the extra data gets populated automatically I guess.</p>\n"
},
{
"answer_id": 300229,
"author": "TayloeD",
"author_id": 141424,
"author_profile": "https://wordpress.stackexchange.com/users/141424",
"pm_score": 2,
"selected": false,
"text": "<p>In order to have your post have a default image, you need to set your post thumbnail. In doing this you need to set the ID of the media, which isn't readily apparent.</p>\n\n<p>I do most of my work in Python, so for me, the following helps:</p>\n\n<p><strong>Step 1.</strong> Get the list of all your media so you know the IDs</p>\n\n<pre><code>##\n## Retrieve a list of media\n\n# curl -X OPTIONS -i http://demo.wp-api.org/wp-json/wp/v2/posts\nimport json\nimport pycurl\nimport re\nfrom io import BytesIO\nimport pandas as pd\nimport datetime\nimport urllib3\n\n\nwpUrl = \"https://MyWordPRessSite.COM</wp-json/wp/v2/media?page={}\"\n\nbContinue = True\npage=1\nwhile bContinue == True:\n buffer = BytesIO()\n c = pycurl.Curl()\n c.setopt(pycurl.SSL_VERIFYPEER, 0)\n c.setopt(c.WRITEDATA, buffer)\n c.setopt(c.HTTPHEADER,['Content-Type: application/json'])\n\n myUrl = wpUrl.format(page)\n #print(myUrl)\n c.setopt(c.URL,myUrl)\n c.perform()\n\n page+= 1\n if buffer != None:\n myData = json.loads(buffer.getvalue())\n for foo in myData:\n print(\"MediaID ={}, caption = {}, alt_text={}\".format(foo[\"id\"], foo[\"caption\"], foo['alt_text']))\n #print(foo)\n if len(myData) <= 0:\n bContinue = False\n else:\n bContinue = False\n c.close()\n</code></pre>\n\n<p><strong>Step 2.</strong> Create the post with the correct media ID</p>\n\n<pre><code>######################################################\n# Create A Post\n######################################################\nfrom wordpress_xmlrpc import Client, WordPressPost\nfrom wordpress_xmlrpc.methods.posts import NewPost\n\n#authenticate\nwp_url = \"https://info-qa.cloudquant.com/xmlrpc.php\"\nwp_username = \"My_User_ID_on_WP\"\nwp_password = \"My_PWD_on_WP\"\n\n\nwp = Client(wp_url, wp_username, wp_password)\n\n#post and activate new post\npost = WordPressPost()\npost.title = '3 Post'\npost.content = '<h1>heading 1</h1>Tayloe was here<br><small>here too!</small><p>New para.'\npost.post_status = 'draft'\npost.thumbnail = 50 # The ID of the image determined in Step 1\npost.slug = \"123abc\"\npost.terms_names = {\n 'post_tag': ['MyTag'],\n 'category': ['Category']\n}\nwp.call(NewPost(post))\n</code></pre>\n"
}
]
| 2017/07/11 | [
"https://wordpress.stackexchange.com/questions/272962",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/123580/"
]
| I can't find any information anywhere about what data I need to give exactly. When I try to read the data from one of my posts with a thumbnail already I get this but there's not way you have to enter all this info just to add a featured image:
```
thumbnail:
{ attachment_id: '360',
date_created_gmt: 2017-07-11T04:51:15.000Z,
parent: 245,
link: 'http://xxxxxxxxxxxx.org/wp-content/uploads/2017/07/japanese-rice-bowl-pottery.jpg',
title: 'japanese-rice-bowl-pottery.jpg',
caption: '',
description: '',
metadata: [Object],
type: 'image/jpg',
thumbnail: 'http://xxxxxxxxxxxx.org/wp-content/uploads/2017/07/japanese-rice-bowl-pottery-150x150.jpg' } }
```
An example of code I tried to use to post with Node.js
```
client.editPost(posts[0].id, {thumbnail : { thumbnail : "http://xxxxxxxxxxxxx.org/wp-content/uploads/2017/07/japanese-rice-bowl-pottery-150x150.jpg" } }, function( error ) {})
``` | In order to have your post have a default image, you need to set your post thumbnail. In doing this you need to set the ID of the media, which isn't readily apparent.
I do most of my work in Python, so for me, the following helps:
**Step 1.** Get the list of all your media so you know the IDs
```
##
## Retrieve a list of media
# curl -X OPTIONS -i http://demo.wp-api.org/wp-json/wp/v2/posts
import json
import pycurl
import re
from io import BytesIO
import pandas as pd
import datetime
import urllib3
wpUrl = "https://MyWordPRessSite.COM</wp-json/wp/v2/media?page={}"
bContinue = True
page=1
while bContinue == True:
buffer = BytesIO()
c = pycurl.Curl()
c.setopt(pycurl.SSL_VERIFYPEER, 0)
c.setopt(c.WRITEDATA, buffer)
c.setopt(c.HTTPHEADER,['Content-Type: application/json'])
myUrl = wpUrl.format(page)
#print(myUrl)
c.setopt(c.URL,myUrl)
c.perform()
page+= 1
if buffer != None:
myData = json.loads(buffer.getvalue())
for foo in myData:
print("MediaID ={}, caption = {}, alt_text={}".format(foo["id"], foo["caption"], foo['alt_text']))
#print(foo)
if len(myData) <= 0:
bContinue = False
else:
bContinue = False
c.close()
```
**Step 2.** Create the post with the correct media ID
```
######################################################
# Create A Post
######################################################
from wordpress_xmlrpc import Client, WordPressPost
from wordpress_xmlrpc.methods.posts import NewPost
#authenticate
wp_url = "https://info-qa.cloudquant.com/xmlrpc.php"
wp_username = "My_User_ID_on_WP"
wp_password = "My_PWD_on_WP"
wp = Client(wp_url, wp_username, wp_password)
#post and activate new post
post = WordPressPost()
post.title = '3 Post'
post.content = '<h1>heading 1</h1>Tayloe was here<br><small>here too!</small><p>New para.'
post.post_status = 'draft'
post.thumbnail = 50 # The ID of the image determined in Step 1
post.slug = "123abc"
post.terms_names = {
'post_tag': ['MyTag'],
'category': ['Category']
}
wp.call(NewPost(post))
``` |
272,968 | <p>I am running some calculations on custom field data using wp_query on a large number of posts and it is taking a long time to load the result. I was advised by a user here to take advantage of wp cron to run these calculations once daily.</p>
<p>What I've been unable to wrap my head around is - if I create an action which contains all of this code, set it to run once daily, and call this action in a template file, won't those queries then recalculate every time that template is loaded?</p>
<p>My intended result is for the result of the queries to display on a template, but only actually recalculate when initiated by cron.</p>
<p>I feel I'm missing something simple here but all examples of wp cron I can find don't appear to cover my use case.</p>
| [
{
"answer_id": 273086,
"author": "cooldude101",
"author_id": 123580,
"author_profile": "https://wordpress.stackexchange.com/users/123580",
"pm_score": 1,
"selected": false,
"text": "<p>I found my problem and just passing it on in case someone googles this.</p>\n\n<p>You need to pass the image id like this</p>\n\n<p>{thumbnail: 123}</p>\n\n<p>Replace 123 with your image id.</p>\n\n<p>all the extra data gets populated automatically I guess.</p>\n"
},
{
"answer_id": 300229,
"author": "TayloeD",
"author_id": 141424,
"author_profile": "https://wordpress.stackexchange.com/users/141424",
"pm_score": 2,
"selected": false,
"text": "<p>In order to have your post have a default image, you need to set your post thumbnail. In doing this you need to set the ID of the media, which isn't readily apparent.</p>\n\n<p>I do most of my work in Python, so for me, the following helps:</p>\n\n<p><strong>Step 1.</strong> Get the list of all your media so you know the IDs</p>\n\n<pre><code>##\n## Retrieve a list of media\n\n# curl -X OPTIONS -i http://demo.wp-api.org/wp-json/wp/v2/posts\nimport json\nimport pycurl\nimport re\nfrom io import BytesIO\nimport pandas as pd\nimport datetime\nimport urllib3\n\n\nwpUrl = \"https://MyWordPRessSite.COM</wp-json/wp/v2/media?page={}\"\n\nbContinue = True\npage=1\nwhile bContinue == True:\n buffer = BytesIO()\n c = pycurl.Curl()\n c.setopt(pycurl.SSL_VERIFYPEER, 0)\n c.setopt(c.WRITEDATA, buffer)\n c.setopt(c.HTTPHEADER,['Content-Type: application/json'])\n\n myUrl = wpUrl.format(page)\n #print(myUrl)\n c.setopt(c.URL,myUrl)\n c.perform()\n\n page+= 1\n if buffer != None:\n myData = json.loads(buffer.getvalue())\n for foo in myData:\n print(\"MediaID ={}, caption = {}, alt_text={}\".format(foo[\"id\"], foo[\"caption\"], foo['alt_text']))\n #print(foo)\n if len(myData) <= 0:\n bContinue = False\n else:\n bContinue = False\n c.close()\n</code></pre>\n\n<p><strong>Step 2.</strong> Create the post with the correct media ID</p>\n\n<pre><code>######################################################\n# Create A Post\n######################################################\nfrom wordpress_xmlrpc import Client, WordPressPost\nfrom wordpress_xmlrpc.methods.posts import NewPost\n\n#authenticate\nwp_url = \"https://info-qa.cloudquant.com/xmlrpc.php\"\nwp_username = \"My_User_ID_on_WP\"\nwp_password = \"My_PWD_on_WP\"\n\n\nwp = Client(wp_url, wp_username, wp_password)\n\n#post and activate new post\npost = WordPressPost()\npost.title = '3 Post'\npost.content = '<h1>heading 1</h1>Tayloe was here<br><small>here too!</small><p>New para.'\npost.post_status = 'draft'\npost.thumbnail = 50 # The ID of the image determined in Step 1\npost.slug = \"123abc\"\npost.terms_names = {\n 'post_tag': ['MyTag'],\n 'category': ['Category']\n}\nwp.call(NewPost(post))\n</code></pre>\n"
}
]
| 2017/07/11 | [
"https://wordpress.stackexchange.com/questions/272968",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/105873/"
]
| I am running some calculations on custom field data using wp\_query on a large number of posts and it is taking a long time to load the result. I was advised by a user here to take advantage of wp cron to run these calculations once daily.
What I've been unable to wrap my head around is - if I create an action which contains all of this code, set it to run once daily, and call this action in a template file, won't those queries then recalculate every time that template is loaded?
My intended result is for the result of the queries to display on a template, but only actually recalculate when initiated by cron.
I feel I'm missing something simple here but all examples of wp cron I can find don't appear to cover my use case. | In order to have your post have a default image, you need to set your post thumbnail. In doing this you need to set the ID of the media, which isn't readily apparent.
I do most of my work in Python, so for me, the following helps:
**Step 1.** Get the list of all your media so you know the IDs
```
##
## Retrieve a list of media
# curl -X OPTIONS -i http://demo.wp-api.org/wp-json/wp/v2/posts
import json
import pycurl
import re
from io import BytesIO
import pandas as pd
import datetime
import urllib3
wpUrl = "https://MyWordPRessSite.COM</wp-json/wp/v2/media?page={}"
bContinue = True
page=1
while bContinue == True:
buffer = BytesIO()
c = pycurl.Curl()
c.setopt(pycurl.SSL_VERIFYPEER, 0)
c.setopt(c.WRITEDATA, buffer)
c.setopt(c.HTTPHEADER,['Content-Type: application/json'])
myUrl = wpUrl.format(page)
#print(myUrl)
c.setopt(c.URL,myUrl)
c.perform()
page+= 1
if buffer != None:
myData = json.loads(buffer.getvalue())
for foo in myData:
print("MediaID ={}, caption = {}, alt_text={}".format(foo["id"], foo["caption"], foo['alt_text']))
#print(foo)
if len(myData) <= 0:
bContinue = False
else:
bContinue = False
c.close()
```
**Step 2.** Create the post with the correct media ID
```
######################################################
# Create A Post
######################################################
from wordpress_xmlrpc import Client, WordPressPost
from wordpress_xmlrpc.methods.posts import NewPost
#authenticate
wp_url = "https://info-qa.cloudquant.com/xmlrpc.php"
wp_username = "My_User_ID_on_WP"
wp_password = "My_PWD_on_WP"
wp = Client(wp_url, wp_username, wp_password)
#post and activate new post
post = WordPressPost()
post.title = '3 Post'
post.content = '<h1>heading 1</h1>Tayloe was here<br><small>here too!</small><p>New para.'
post.post_status = 'draft'
post.thumbnail = 50 # The ID of the image determined in Step 1
post.slug = "123abc"
post.terms_names = {
'post_tag': ['MyTag'],
'category': ['Category']
}
wp.call(NewPost(post))
``` |
272,997 | <p>I'm trying to achieve simple result. Run main loop 2 times, but first time for the one post with different layout, and second time for the rest posts with different layout. I found that condition <strong>1 > $wp_query->current_post</strong> can show only the first post in my loop. But when I run loop again it starts with 3rd post and skipping the 2nd.</p>
<p>Here is the code:</p>
<pre><code><!-- Full Post -->
<?php if ( have_posts() ) :
while ( have_posts() ) : the_post();
// first post
if( 1 > $wp_query->current_post ):
get_template_part( 'template-parts/content', get_post_format() );
else :
break;
endif;
endwhile;
?>
<!-- Small Posts -->
<div class="row">
<?php
while( have_posts() ) : the_post();
get_template_part( 'template-parts/post-small', get_post_format() );
endwhile;
?>
</div>
</code></pre>
| [
{
"answer_id": 273086,
"author": "cooldude101",
"author_id": 123580,
"author_profile": "https://wordpress.stackexchange.com/users/123580",
"pm_score": 1,
"selected": false,
"text": "<p>I found my problem and just passing it on in case someone googles this.</p>\n\n<p>You need to pass the image id like this</p>\n\n<p>{thumbnail: 123}</p>\n\n<p>Replace 123 with your image id.</p>\n\n<p>all the extra data gets populated automatically I guess.</p>\n"
},
{
"answer_id": 300229,
"author": "TayloeD",
"author_id": 141424,
"author_profile": "https://wordpress.stackexchange.com/users/141424",
"pm_score": 2,
"selected": false,
"text": "<p>In order to have your post have a default image, you need to set your post thumbnail. In doing this you need to set the ID of the media, which isn't readily apparent.</p>\n\n<p>I do most of my work in Python, so for me, the following helps:</p>\n\n<p><strong>Step 1.</strong> Get the list of all your media so you know the IDs</p>\n\n<pre><code>##\n## Retrieve a list of media\n\n# curl -X OPTIONS -i http://demo.wp-api.org/wp-json/wp/v2/posts\nimport json\nimport pycurl\nimport re\nfrom io import BytesIO\nimport pandas as pd\nimport datetime\nimport urllib3\n\n\nwpUrl = \"https://MyWordPRessSite.COM</wp-json/wp/v2/media?page={}\"\n\nbContinue = True\npage=1\nwhile bContinue == True:\n buffer = BytesIO()\n c = pycurl.Curl()\n c.setopt(pycurl.SSL_VERIFYPEER, 0)\n c.setopt(c.WRITEDATA, buffer)\n c.setopt(c.HTTPHEADER,['Content-Type: application/json'])\n\n myUrl = wpUrl.format(page)\n #print(myUrl)\n c.setopt(c.URL,myUrl)\n c.perform()\n\n page+= 1\n if buffer != None:\n myData = json.loads(buffer.getvalue())\n for foo in myData:\n print(\"MediaID ={}, caption = {}, alt_text={}\".format(foo[\"id\"], foo[\"caption\"], foo['alt_text']))\n #print(foo)\n if len(myData) <= 0:\n bContinue = False\n else:\n bContinue = False\n c.close()\n</code></pre>\n\n<p><strong>Step 2.</strong> Create the post with the correct media ID</p>\n\n<pre><code>######################################################\n# Create A Post\n######################################################\nfrom wordpress_xmlrpc import Client, WordPressPost\nfrom wordpress_xmlrpc.methods.posts import NewPost\n\n#authenticate\nwp_url = \"https://info-qa.cloudquant.com/xmlrpc.php\"\nwp_username = \"My_User_ID_on_WP\"\nwp_password = \"My_PWD_on_WP\"\n\n\nwp = Client(wp_url, wp_username, wp_password)\n\n#post and activate new post\npost = WordPressPost()\npost.title = '3 Post'\npost.content = '<h1>heading 1</h1>Tayloe was here<br><small>here too!</small><p>New para.'\npost.post_status = 'draft'\npost.thumbnail = 50 # The ID of the image determined in Step 1\npost.slug = \"123abc\"\npost.terms_names = {\n 'post_tag': ['MyTag'],\n 'category': ['Category']\n}\nwp.call(NewPost(post))\n</code></pre>\n"
}
]
| 2017/07/11 | [
"https://wordpress.stackexchange.com/questions/272997",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/112255/"
]
| I'm trying to achieve simple result. Run main loop 2 times, but first time for the one post with different layout, and second time for the rest posts with different layout. I found that condition **1 > $wp\_query->current\_post** can show only the first post in my loop. But when I run loop again it starts with 3rd post and skipping the 2nd.
Here is the code:
```
<!-- Full Post -->
<?php if ( have_posts() ) :
while ( have_posts() ) : the_post();
// first post
if( 1 > $wp_query->current_post ):
get_template_part( 'template-parts/content', get_post_format() );
else :
break;
endif;
endwhile;
?>
<!-- Small Posts -->
<div class="row">
<?php
while( have_posts() ) : the_post();
get_template_part( 'template-parts/post-small', get_post_format() );
endwhile;
?>
</div>
``` | In order to have your post have a default image, you need to set your post thumbnail. In doing this you need to set the ID of the media, which isn't readily apparent.
I do most of my work in Python, so for me, the following helps:
**Step 1.** Get the list of all your media so you know the IDs
```
##
## Retrieve a list of media
# curl -X OPTIONS -i http://demo.wp-api.org/wp-json/wp/v2/posts
import json
import pycurl
import re
from io import BytesIO
import pandas as pd
import datetime
import urllib3
wpUrl = "https://MyWordPRessSite.COM</wp-json/wp/v2/media?page={}"
bContinue = True
page=1
while bContinue == True:
buffer = BytesIO()
c = pycurl.Curl()
c.setopt(pycurl.SSL_VERIFYPEER, 0)
c.setopt(c.WRITEDATA, buffer)
c.setopt(c.HTTPHEADER,['Content-Type: application/json'])
myUrl = wpUrl.format(page)
#print(myUrl)
c.setopt(c.URL,myUrl)
c.perform()
page+= 1
if buffer != None:
myData = json.loads(buffer.getvalue())
for foo in myData:
print("MediaID ={}, caption = {}, alt_text={}".format(foo["id"], foo["caption"], foo['alt_text']))
#print(foo)
if len(myData) <= 0:
bContinue = False
else:
bContinue = False
c.close()
```
**Step 2.** Create the post with the correct media ID
```
######################################################
# Create A Post
######################################################
from wordpress_xmlrpc import Client, WordPressPost
from wordpress_xmlrpc.methods.posts import NewPost
#authenticate
wp_url = "https://info-qa.cloudquant.com/xmlrpc.php"
wp_username = "My_User_ID_on_WP"
wp_password = "My_PWD_on_WP"
wp = Client(wp_url, wp_username, wp_password)
#post and activate new post
post = WordPressPost()
post.title = '3 Post'
post.content = '<h1>heading 1</h1>Tayloe was here<br><small>here too!</small><p>New para.'
post.post_status = 'draft'
post.thumbnail = 50 # The ID of the image determined in Step 1
post.slug = "123abc"
post.terms_names = {
'post_tag': ['MyTag'],
'category': ['Category']
}
wp.call(NewPost(post))
``` |
273,063 | <p>I don't know exactly how is the correct name, but i want to create my own table like the default wordpress table : </p>
<p><a href="https://i.stack.imgur.com/WCgaY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WCgaY.png" alt="enter image description here"></a></p>
<p>I wanted to ask, does the WordPress provide some API to create it?</p>
| [
{
"answer_id": 273068,
"author": "rudtek",
"author_id": 77767,
"author_profile": "https://wordpress.stackexchange.com/users/77767",
"pm_score": 0,
"selected": false,
"text": "<p>Did you already create your custom post type? Or were you trying to modify what appears on that page? </p>\n\n<p>If you are trying to create your own post type then you need this function: <a href=\"https://codex.wordpress.org/Function_Reference/register_post_type\" rel=\"nofollow noreferrer\" title=\"register post_types\">register_post_type</a> Wordpress creates the screen you see above (admin-edit) automatically as part of this process. You can customize what appears in the columns with manage_CPT_posts_custom_column and manage_CPT_posts_columns filters</p>\n"
},
{
"answer_id": 273081,
"author": "Lime",
"author_id": 117675,
"author_profile": "https://wordpress.stackexchange.com/users/117675",
"pm_score": 2,
"selected": true,
"text": "<p>I'm not an expert on this but I did get into it a little recently. Take a look at this tutorial: <a href=\"http://wpengineer.com/2426/wp_list_table-a-step-by-step-guide/\" rel=\"nofollow noreferrer\">http://wpengineer.com/2426/wp_list_table-a-step-by-step-guide/</a></p>\n\n<p>Basically, you'll want to create a class that extends <code>WP_List_Table</code>:</p>\n\n<pre><code>class My_List_Table extends WP_List_Table {\n // what your table is all about\n}\n\n$myListTable = new My__List_Table();\n</code></pre>\n\n<p>It is an involved process, but that tutorial seems pretty good. Good luck!</p>\n"
}
]
| 2017/07/11 | [
"https://wordpress.stackexchange.com/questions/273063",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/121651/"
]
| I don't know exactly how is the correct name, but i want to create my own table like the default wordpress table :
[](https://i.stack.imgur.com/WCgaY.png)
I wanted to ask, does the WordPress provide some API to create it? | I'm not an expert on this but I did get into it a little recently. Take a look at this tutorial: <http://wpengineer.com/2426/wp_list_table-a-step-by-step-guide/>
Basically, you'll want to create a class that extends `WP_List_Table`:
```
class My_List_Table extends WP_List_Table {
// what your table is all about
}
$myListTable = new My__List_Table();
```
It is an involved process, but that tutorial seems pretty good. Good luck! |
273,078 | <p>I'm trying to add a link to each item of the Users table in the WP Admin area and use that link to send that specific user an email. I'm most of the way there but I'm having some odd behavior that I can't figure out. Here's my code: (I describe my issues below that)</p>
<pre><code>// Adds "Send rejection email" action to Users page
function jm_send_rejection_link($actions, $user_object) {
if( ($_POST['send']) && ($_POST['email-address'] == $user_object->user_email) ) {
$sendto = $_POST['email-address'];
$sendsub = "Your registration has been rejected.";
$sendmess = "Sorry! Your registration has been rejected. I guess someone doesn't like you.";
$headers = array('From: The Company <[email protected]>');
wp_mail($sendto, $sendsub, $sendmess, $headers);
echo '<div class="updated notice"><p>Success! The rejection email has been sent to ' . $_POST['email-address'] . '.</p></div>';
}
$actions['send_rejection'] = "<form method='post' action=''>
<input type='hidden' name='email-address' value='" . $user_object->user_email . "' />
<input type='submit' name='send' value='Send Rejection' />
</form>";
return $actions;
}
add_filter('user_row_actions', 'jm_send_rejection_link', 10, 2);
</code></pre>
<p>So this code adds the action link "Send Rejection Email" to each user in the table. It also successfully sends out the email... sometimes. For the first user in the table, it seems to fail and also it appends some unexpected stuff to the URL:</p>
<pre><code>http://sampledomain.org/wp-admin/users.php?s&action=-1&new_role&paged=1&email-address=emailaddress%sampledomain.com&send=Send+Rejection&action2=-1&new_role2
</code></pre>
<p>It also does not display the success message in this case.</p>
<p>For a number of the other users it does successfully display the success message and send the email. However, not for all other users. The other users display the success message but do not receive the email. It is possible that these accounts are just catching the email in a firewall or something, although it does not appear in spam. </p>
<p>I am most concerned about whatever I'm doing wrong that is causing the issue with the first user. Any ideas?</p>
<p>PS - I do recognize that my IF statement in there is a little weird. I guess because I'm adding this to <code>user_row_actions</code> it is running for every user on the table, which is why I am making that email send only for the user whose email matches the posted address. A little backwards I know. If I should break those into two different functions, any advice as to how to make that second function run on the user page without running for each user would be much appreciated.</p>
| [
{
"answer_id": 273068,
"author": "rudtek",
"author_id": 77767,
"author_profile": "https://wordpress.stackexchange.com/users/77767",
"pm_score": 0,
"selected": false,
"text": "<p>Did you already create your custom post type? Or were you trying to modify what appears on that page? </p>\n\n<p>If you are trying to create your own post type then you need this function: <a href=\"https://codex.wordpress.org/Function_Reference/register_post_type\" rel=\"nofollow noreferrer\" title=\"register post_types\">register_post_type</a> Wordpress creates the screen you see above (admin-edit) automatically as part of this process. You can customize what appears in the columns with manage_CPT_posts_custom_column and manage_CPT_posts_columns filters</p>\n"
},
{
"answer_id": 273081,
"author": "Lime",
"author_id": 117675,
"author_profile": "https://wordpress.stackexchange.com/users/117675",
"pm_score": 2,
"selected": true,
"text": "<p>I'm not an expert on this but I did get into it a little recently. Take a look at this tutorial: <a href=\"http://wpengineer.com/2426/wp_list_table-a-step-by-step-guide/\" rel=\"nofollow noreferrer\">http://wpengineer.com/2426/wp_list_table-a-step-by-step-guide/</a></p>\n\n<p>Basically, you'll want to create a class that extends <code>WP_List_Table</code>:</p>\n\n<pre><code>class My_List_Table extends WP_List_Table {\n // what your table is all about\n}\n\n$myListTable = new My__List_Table();\n</code></pre>\n\n<p>It is an involved process, but that tutorial seems pretty good. Good luck!</p>\n"
}
]
| 2017/07/11 | [
"https://wordpress.stackexchange.com/questions/273078",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/117675/"
]
| I'm trying to add a link to each item of the Users table in the WP Admin area and use that link to send that specific user an email. I'm most of the way there but I'm having some odd behavior that I can't figure out. Here's my code: (I describe my issues below that)
```
// Adds "Send rejection email" action to Users page
function jm_send_rejection_link($actions, $user_object) {
if( ($_POST['send']) && ($_POST['email-address'] == $user_object->user_email) ) {
$sendto = $_POST['email-address'];
$sendsub = "Your registration has been rejected.";
$sendmess = "Sorry! Your registration has been rejected. I guess someone doesn't like you.";
$headers = array('From: The Company <[email protected]>');
wp_mail($sendto, $sendsub, $sendmess, $headers);
echo '<div class="updated notice"><p>Success! The rejection email has been sent to ' . $_POST['email-address'] . '.</p></div>';
}
$actions['send_rejection'] = "<form method='post' action=''>
<input type='hidden' name='email-address' value='" . $user_object->user_email . "' />
<input type='submit' name='send' value='Send Rejection' />
</form>";
return $actions;
}
add_filter('user_row_actions', 'jm_send_rejection_link', 10, 2);
```
So this code adds the action link "Send Rejection Email" to each user in the table. It also successfully sends out the email... sometimes. For the first user in the table, it seems to fail and also it appends some unexpected stuff to the URL:
```
http://sampledomain.org/wp-admin/users.php?s&action=-1&new_role&paged=1&email-address=emailaddress%sampledomain.com&send=Send+Rejection&action2=-1&new_role2
```
It also does not display the success message in this case.
For a number of the other users it does successfully display the success message and send the email. However, not for all other users. The other users display the success message but do not receive the email. It is possible that these accounts are just catching the email in a firewall or something, although it does not appear in spam.
I am most concerned about whatever I'm doing wrong that is causing the issue with the first user. Any ideas?
PS - I do recognize that my IF statement in there is a little weird. I guess because I'm adding this to `user_row_actions` it is running for every user on the table, which is why I am making that email send only for the user whose email matches the posted address. A little backwards I know. If I should break those into two different functions, any advice as to how to make that second function run on the user page without running for each user would be much appreciated. | I'm not an expert on this but I did get into it a little recently. Take a look at this tutorial: <http://wpengineer.com/2426/wp_list_table-a-step-by-step-guide/>
Basically, you'll want to create a class that extends `WP_List_Table`:
```
class My_List_Table extends WP_List_Table {
// what your table is all about
}
$myListTable = new My__List_Table();
```
It is an involved process, but that tutorial seems pretty good. Good luck! |
273,084 | <p>I have a situation where my search is working but the client just came with a request I hadn't considered. If you search by first name (eg. john) or last name (eg. doe), this will absolutely bring your result. But if you search for their full name (eg. john doe), you get 0 results.</p>
<p>I've looked around but I can't seem to find a way to compare the search to "first_name last_name".</p>
<p>I've scanned through the similar questions on the forum but they aren't helping / seem to go in a different direction entirely. If anyone has any knowledge, or can point me to the right thread, I'd be grateful.</p>
<p>Here's the summary of my code:</p>
<pre><code>$args = array(
'role' => 'Subscriber',
'meta_query' => array(
array(
'key' => 'membership_class',
'value' => 'Full',
'compare' => '=',
'type' => 'CHAR',
),
array(
'relation' => 'OR',
array(
'key' => 'first_name',
'value' => $usersearch,
'compare' => 'LIKE'
),
array(
'key' => 'last_name',
'value' => $usersearch,
'compare' => 'LIKE'
),
array(
'key' => 'personal_city',
'value' => $usersearch,
'compare' => 'LIKE',
'type' => 'CHAR',
),
array(
'key' => 'personal_province',
'value' => $usersearch,
'compare' => 'LIKE',
'type' => 'CHAR',
),
array(
'key' => 'treatments',
'value' => $usersearch,
'compare' => 'LIKE',
),
),
),
);
</code></pre>
| [
{
"answer_id": 273173,
"author": "dbeja",
"author_id": 9585,
"author_profile": "https://wordpress.stackexchange.com/users/9585",
"pm_score": 3,
"selected": true,
"text": "<p>What if you use IN operator and split the search term in a words array:</p>\n\n<pre><code>$args = array(\n 'role' => 'Subscriber',\n 'meta_query' => array(\n array(\n 'key' => 'membership_class',\n 'value' => 'Full',\n 'compare' => '=',\n 'type' => 'CHAR',\n ),\n array(\n 'relation' => 'OR',\n array(\n 'key' => 'first_name',\n 'value' => explode( ' ', $usersearch ),\n 'compare' => 'IN'\n ),\n array(\n 'key' => 'last_name',\n 'value' => explode( ' ', $usersearch ),\n 'compare' => 'IN'\n ),\n array(\n 'key' => 'personal_city',\n 'value' => $usersearch,\n 'compare' => 'LIKE',\n 'type' => 'CHAR',\n ),\n array(\n 'key' => 'personal_province',\n 'value' => $usersearch,\n 'compare' => 'LIKE',\n 'type' => 'CHAR',\n ),\n array(\n 'key' => 'treatments',\n 'value' => $usersearch,\n 'compare' => 'LIKE',\n\n ),\n\n\n\n ),\n\n ),\n);\n</code></pre>\n"
},
{
"answer_id": 273174,
"author": "Faye",
"author_id": 76600,
"author_profile": "https://wordpress.stackexchange.com/users/76600",
"pm_score": 0,
"selected": false,
"text": "<p>I hunkered down and solved this today. Hoping my success will help anyone else in the same boat.</p>\n\n<p>Because the meta query array NEEDS a true meta_key, you actually need to create one for the user and populate it with the information you want to pass. See the <a href=\"https://codex.wordpress.org/Function_Reference/add_user_meta\" rel=\"nofollow noreferrer\">add_user_meta</a> function for more info.</p>\n\n<p>So, prior to running my search, I have this:</p>\n\n<pre><code><?php \n$allusers = get_users(array(\n 'role' => 'subscriber',\n\n));\n\nforeach ($allusers as $user) {\n $firstName = get_user_meta($user->ID, 'first_name', true);\n $lastName = get_user_meta($user->ID, 'last_name', true);\n\n $full_name = $firstName . ' ' . $lastName . ' ';\n\n $uid = $user->ID;\n\n\n add_user_meta( $uid, 'full_name', $full_name );\n\n\n}\n?>\n</code></pre>\n\n<p>Here I've called all the users, and then I've defined for them all new meta user, with my custom value that includes both the first and last name of the user (ignore my use of custom variables over standard ones, I have a lot of user queries going on this page and just wanted to make sure I wasn't causing any conflicts).</p>\n\n<p>Then down in my search query I've added one more query...</p>\n\n<pre><code>array(\n 'key' => 'full_name',\n 'value' => $usersearch,\n 'compare' => 'LIKE'\n),\n</code></pre>\n\n<p>And that has my search functioning for all three, John, Doe, and John Doe.</p>\n"
}
]
| 2017/07/11 | [
"https://wordpress.stackexchange.com/questions/273084",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/76600/"
]
| I have a situation where my search is working but the client just came with a request I hadn't considered. If you search by first name (eg. john) or last name (eg. doe), this will absolutely bring your result. But if you search for their full name (eg. john doe), you get 0 results.
I've looked around but I can't seem to find a way to compare the search to "first\_name last\_name".
I've scanned through the similar questions on the forum but they aren't helping / seem to go in a different direction entirely. If anyone has any knowledge, or can point me to the right thread, I'd be grateful.
Here's the summary of my code:
```
$args = array(
'role' => 'Subscriber',
'meta_query' => array(
array(
'key' => 'membership_class',
'value' => 'Full',
'compare' => '=',
'type' => 'CHAR',
),
array(
'relation' => 'OR',
array(
'key' => 'first_name',
'value' => $usersearch,
'compare' => 'LIKE'
),
array(
'key' => 'last_name',
'value' => $usersearch,
'compare' => 'LIKE'
),
array(
'key' => 'personal_city',
'value' => $usersearch,
'compare' => 'LIKE',
'type' => 'CHAR',
),
array(
'key' => 'personal_province',
'value' => $usersearch,
'compare' => 'LIKE',
'type' => 'CHAR',
),
array(
'key' => 'treatments',
'value' => $usersearch,
'compare' => 'LIKE',
),
),
),
);
``` | What if you use IN operator and split the search term in a words array:
```
$args = array(
'role' => 'Subscriber',
'meta_query' => array(
array(
'key' => 'membership_class',
'value' => 'Full',
'compare' => '=',
'type' => 'CHAR',
),
array(
'relation' => 'OR',
array(
'key' => 'first_name',
'value' => explode( ' ', $usersearch ),
'compare' => 'IN'
),
array(
'key' => 'last_name',
'value' => explode( ' ', $usersearch ),
'compare' => 'IN'
),
array(
'key' => 'personal_city',
'value' => $usersearch,
'compare' => 'LIKE',
'type' => 'CHAR',
),
array(
'key' => 'personal_province',
'value' => $usersearch,
'compare' => 'LIKE',
'type' => 'CHAR',
),
array(
'key' => 'treatments',
'value' => $usersearch,
'compare' => 'LIKE',
),
),
),
);
``` |
273,094 | <p>I'm trying to register a new shortcode on my custom theme. </p>
<p>In functions.php I have created a basic test function as follows</p>
<pre><code>function get_second_image($atts) {
echo ‘test’;
}
</code></pre>
<p>And registered it right underneath</p>
<pre><code>add_shortcode( ‘case_study_second_image_sc’, ‘get_second_image’ );
</code></pre>
<p>Using the WYSIWYG editor I insert the shortcode [case_study_second_image_sc] but it just displays as the raw code on the page. </p>
<p>I'm calling the page content using</p>
<pre><code><?php the_content(); ?>
</code></pre>
<p>in the template file.</p>
<p>Based on info from another SE question I have searched my theme's files for any add or remove filter functions but there don't appear to be any that would be getting in the way. </p>
| [
{
"answer_id": 273096,
"author": "Rick Hellewell",
"author_id": 29416,
"author_profile": "https://wordpress.stackexchange.com/users/29416",
"pm_score": 0,
"selected": false,
"text": "<p>See the documentation here <a href=\"https://codex.wordpress.org/Shortcode_API\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Shortcode_API</a>. Your function needs to return the value you want to replace the shortcode. The '<code>echo</code>' will not display anything. You need to <code>return 'test'</code>; to insert the text '<code>test</code>' in the content.</p>\n\n<p>From the docs in the above link (emphasis added):</p>\n\n<blockquote>\n <p>When the_content is displayed, the shortcode API will parse any\n registered shortcodes such as \"[myshortcode]\", separate and parse the\n attributes and content, if any, and pass them the corresponding\n shortcode handler function. Any string <strong>returned</strong> (<strong>not echoed</strong>) by the\n shortcode handler will be inserted into the post body in place of the\n shortcode itself.</p>\n</blockquote>\n\n<p>Hope this helps.</p>\n"
},
{
"answer_id": 273098,
"author": "Dave Romsey",
"author_id": 2807,
"author_profile": "https://wordpress.stackexchange.com/users/2807",
"pm_score": 3,
"selected": true,
"text": "<p>Make sure to use straight quotes, e.g. <kbd>'</kbd> or <kbd>\"</kbd> and not curly quotes <kbd>‘</kbd>, <kbd>’</kbd>, <kbd>“</kbd>, or <kbd>”</kbd> for strings.</p>\n\n<p>Also, shortcodes should return their output, not echo it.</p>\n\n<p>When WordPress finds a shortcode without a callback, it displays the shortcode tag just as it was entered e.g. <code>[case_study_second_image_sc]</code>.</p>\n\n<p>The shortcode tag <code>‘case_study_second_image_sc’</code> and the associated <a href=\"https://codex.wordpress.org/How_to_Pass_Tag_Parameters#Callable\" rel=\"nofollow noreferrer\">callback</a> <code>‘get_second_image’</code> will be parsed as constants by PHP. This means we won't have a valid shortcode tag or callback function for our shortcode and WP will just output the shortcode as it was entered by the user.</p>\n\n<p>Turning on error reporting helps to find these tricky errors (sometimes curly quotes appear in copy/pasted code and it can be difficult to differentiate quotes in some editors). </p>\n\n<blockquote>\n<pre><code>Use of undefined constant ‘case_study_second_image_sc’ - assumed '‘case_study_second_image_sc’'\n\nUse of undefined constant ‘get_second_image’ - assumed '‘get_second_image’'\n</code></pre>\n</blockquote>\n"
}
]
| 2017/07/12 | [
"https://wordpress.stackexchange.com/questions/273094",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/123673/"
]
| I'm trying to register a new shortcode on my custom theme.
In functions.php I have created a basic test function as follows
```
function get_second_image($atts) {
echo ‘test’;
}
```
And registered it right underneath
```
add_shortcode( ‘case_study_second_image_sc’, ‘get_second_image’ );
```
Using the WYSIWYG editor I insert the shortcode [case\_study\_second\_image\_sc] but it just displays as the raw code on the page.
I'm calling the page content using
```
<?php the_content(); ?>
```
in the template file.
Based on info from another SE question I have searched my theme's files for any add or remove filter functions but there don't appear to be any that would be getting in the way. | Make sure to use straight quotes, e.g. `'` or `"` and not curly quotes `‘`, `’`, `“`, or `”` for strings.
Also, shortcodes should return their output, not echo it.
When WordPress finds a shortcode without a callback, it displays the shortcode tag just as it was entered e.g. `[case_study_second_image_sc]`.
The shortcode tag `‘case_study_second_image_sc’` and the associated [callback](https://codex.wordpress.org/How_to_Pass_Tag_Parameters#Callable) `‘get_second_image’` will be parsed as constants by PHP. This means we won't have a valid shortcode tag or callback function for our shortcode and WP will just output the shortcode as it was entered by the user.
Turning on error reporting helps to find these tricky errors (sometimes curly quotes appear in copy/pasted code and it can be difficult to differentiate quotes in some editors).
>
>
> ```
> Use of undefined constant ‘case_study_second_image_sc’ - assumed '‘case_study_second_image_sc’'
>
> Use of undefined constant ‘get_second_image’ - assumed '‘get_second_image’'
>
> ```
>
> |
273,112 | <p>I have been working on trying to get data to store and display on a CPT field. The code I have is here:</p>
<pre><code>function fhaac_subject_box_callback( $post ){
wp_nonce_field( basename(__FILE__ ), 'fhacc_subject_nounce');
$fhaac_stored_subject_meta = get_post_meta( '$post->ID' );
?>
<div>Subject name: <input type="text" name="fhaac_subject_name" id="fhaac_
subject_name" value="<?php if ( ! empty ( $fhaac_stored_subject_meta
['fhaac_subject_name']) ) echo esc_attr ( $fhaac_stored_subject_meta
['fhaac_subject_name'][0] ); ?>"/></div>
</code></pre>
<p>I have set the <code>save_post</code> into a function below: </p>
<pre><code>function fhaac_save_subject_meta( $post_id ){
//Checking save status
$is_autosave = wp_is_post_autosave( $post_id );
$is_revision = wp_is_post_revision( $post_id );
$is_valid_nonce = ( isset( $_POST[ 'fhacc_subject_nounce' ] ) &&
wp_verify_nonce( $_POST[ 'fhacc_subject_nounce' ], basename(__FILE__
)))?'true' : 'false';
//Exit scripts depending on save status
if ( $is_autosave || $is_revision || !$is_valid_nonce){
return;
}
if ( isset( $_POST['fhaac_subject_name'])){
update_post_meta( $post_id, 'fhaac_subject_name',
sanitize_text_field($_POST['fhaac_subject_name']));
}
</code></pre>
<p>But either the data isn't saving, or being returned. The issue is, I have this working on a <code>wp_editor</code> field. I'm still fairly new to this, so any help would be really appreciated. </p>
<p>Thanks in advance!</p>
| [
{
"answer_id": 273096,
"author": "Rick Hellewell",
"author_id": 29416,
"author_profile": "https://wordpress.stackexchange.com/users/29416",
"pm_score": 0,
"selected": false,
"text": "<p>See the documentation here <a href=\"https://codex.wordpress.org/Shortcode_API\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Shortcode_API</a>. Your function needs to return the value you want to replace the shortcode. The '<code>echo</code>' will not display anything. You need to <code>return 'test'</code>; to insert the text '<code>test</code>' in the content.</p>\n\n<p>From the docs in the above link (emphasis added):</p>\n\n<blockquote>\n <p>When the_content is displayed, the shortcode API will parse any\n registered shortcodes such as \"[myshortcode]\", separate and parse the\n attributes and content, if any, and pass them the corresponding\n shortcode handler function. Any string <strong>returned</strong> (<strong>not echoed</strong>) by the\n shortcode handler will be inserted into the post body in place of the\n shortcode itself.</p>\n</blockquote>\n\n<p>Hope this helps.</p>\n"
},
{
"answer_id": 273098,
"author": "Dave Romsey",
"author_id": 2807,
"author_profile": "https://wordpress.stackexchange.com/users/2807",
"pm_score": 3,
"selected": true,
"text": "<p>Make sure to use straight quotes, e.g. <kbd>'</kbd> or <kbd>\"</kbd> and not curly quotes <kbd>‘</kbd>, <kbd>’</kbd>, <kbd>“</kbd>, or <kbd>”</kbd> for strings.</p>\n\n<p>Also, shortcodes should return their output, not echo it.</p>\n\n<p>When WordPress finds a shortcode without a callback, it displays the shortcode tag just as it was entered e.g. <code>[case_study_second_image_sc]</code>.</p>\n\n<p>The shortcode tag <code>‘case_study_second_image_sc’</code> and the associated <a href=\"https://codex.wordpress.org/How_to_Pass_Tag_Parameters#Callable\" rel=\"nofollow noreferrer\">callback</a> <code>‘get_second_image’</code> will be parsed as constants by PHP. This means we won't have a valid shortcode tag or callback function for our shortcode and WP will just output the shortcode as it was entered by the user.</p>\n\n<p>Turning on error reporting helps to find these tricky errors (sometimes curly quotes appear in copy/pasted code and it can be difficult to differentiate quotes in some editors). </p>\n\n<blockquote>\n<pre><code>Use of undefined constant ‘case_study_second_image_sc’ - assumed '‘case_study_second_image_sc’'\n\nUse of undefined constant ‘get_second_image’ - assumed '‘get_second_image’'\n</code></pre>\n</blockquote>\n"
}
]
| 2017/07/12 | [
"https://wordpress.stackexchange.com/questions/273112",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/58313/"
]
| I have been working on trying to get data to store and display on a CPT field. The code I have is here:
```
function fhaac_subject_box_callback( $post ){
wp_nonce_field( basename(__FILE__ ), 'fhacc_subject_nounce');
$fhaac_stored_subject_meta = get_post_meta( '$post->ID' );
?>
<div>Subject name: <input type="text" name="fhaac_subject_name" id="fhaac_
subject_name" value="<?php if ( ! empty ( $fhaac_stored_subject_meta
['fhaac_subject_name']) ) echo esc_attr ( $fhaac_stored_subject_meta
['fhaac_subject_name'][0] ); ?>"/></div>
```
I have set the `save_post` into a function below:
```
function fhaac_save_subject_meta( $post_id ){
//Checking save status
$is_autosave = wp_is_post_autosave( $post_id );
$is_revision = wp_is_post_revision( $post_id );
$is_valid_nonce = ( isset( $_POST[ 'fhacc_subject_nounce' ] ) &&
wp_verify_nonce( $_POST[ 'fhacc_subject_nounce' ], basename(__FILE__
)))?'true' : 'false';
//Exit scripts depending on save status
if ( $is_autosave || $is_revision || !$is_valid_nonce){
return;
}
if ( isset( $_POST['fhaac_subject_name'])){
update_post_meta( $post_id, 'fhaac_subject_name',
sanitize_text_field($_POST['fhaac_subject_name']));
}
```
But either the data isn't saving, or being returned. The issue is, I have this working on a `wp_editor` field. I'm still fairly new to this, so any help would be really appreciated.
Thanks in advance! | Make sure to use straight quotes, e.g. `'` or `"` and not curly quotes `‘`, `’`, `“`, or `”` for strings.
Also, shortcodes should return their output, not echo it.
When WordPress finds a shortcode without a callback, it displays the shortcode tag just as it was entered e.g. `[case_study_second_image_sc]`.
The shortcode tag `‘case_study_second_image_sc’` and the associated [callback](https://codex.wordpress.org/How_to_Pass_Tag_Parameters#Callable) `‘get_second_image’` will be parsed as constants by PHP. This means we won't have a valid shortcode tag or callback function for our shortcode and WP will just output the shortcode as it was entered by the user.
Turning on error reporting helps to find these tricky errors (sometimes curly quotes appear in copy/pasted code and it can be difficult to differentiate quotes in some editors).
>
>
> ```
> Use of undefined constant ‘case_study_second_image_sc’ - assumed '‘case_study_second_image_sc’'
>
> Use of undefined constant ‘get_second_image’ - assumed '‘get_second_image’'
>
> ```
>
> |
273,144 | <p>Recently all of my REST-API requests suddenly turned to return a 404 error, Every request (no matter custom endpoint or built-in).</p>
<p>Then I figured it's because of permalink's structure. <code>/wp-json/</code> is not accessible under plain permalink, since there is simply no redirect rule available at the moment.</p>
<p>Is it possible to use the REST endpoints in this situation? Both custom and built-in.</p>
| [
{
"answer_id": 273147,
"author": "kraftner",
"author_id": 47733,
"author_profile": "https://wordpress.stackexchange.com/users/47733",
"pm_score": 5,
"selected": true,
"text": "<p>Yes you can. Just add the <code>rest_route</code> query parameter.</p>\n\n<p>So</p>\n\n<p><a href=\"https://wordpress.org/wp-json/\" rel=\"noreferrer\">https://wordpress.org/wp-json/</a></p>\n\n<p>would become </p>\n\n<p><a href=\"https://wordpress.org/?rest_route=/\" rel=\"noreferrer\">https://wordpress.org/?rest_route=/</a></p>\n\n<p>Or <code>https://wordpress.org/wp-json/wp/v2/</code> would become <code>https://wordpress.org/?rest_route=/wp/v2</code> to give you a more complete example.</p>\n\n<p>So you're wondering how to decide which one to use? Worry no more, there's a function for that: <a href=\"https://developer.wordpress.org/reference/functions/get_rest_url/\" rel=\"noreferrer\"><code>get_rest_url()</code></a></p>\n\n<p>Another option is the fact that by default there is a <code><link></code> in the header that gives you the API root.</p>\n\n<pre><code><link rel='https://api.w.org/' href='https://wordpress.org/wp-json/' />\n</code></pre>\n\n<p>So in case you need to figure that out from client side JS just use something along the lines of</p>\n\n<pre><code>document.querySelectorAll('link[rel=\"https://api.w.org/\"]')[0].getAttribute('href');\n</code></pre>\n\n<hr>\n\n<p>So basically you shouldn't take the <code>wp-json</code> part as given (and hardcode it) but always build it dynamically either using <code>get_rest_url()</code> or the JS approach mentioned above.</p>\n"
},
{
"answer_id": 305493,
"author": "northtree",
"author_id": 109298,
"author_profile": "https://wordpress.stackexchange.com/users/109298",
"pm_score": 1,
"selected": false,
"text": "<p>You could add one rewrite on your web server.</p>\n\n<p>E.g for nginx</p>\n\n<pre><code>location ~ ^/wp-json/ {\n rewrite ^/wp-json/(.*?)$ /?rest_route=/$1 last;\n}\n</code></pre>\n"
},
{
"answer_id": 349986,
"author": "Max Carroll",
"author_id": 173553,
"author_profile": "https://wordpress.stackexchange.com/users/173553",
"pm_score": 0,
"selected": false,
"text": "<p>The <code>rest_route</code> query parameter is the <code>Ugly</code> (Wordpress's choice of words not mine) style of Permalink. You can change the permilink style to <code>Post name</code> as illustrated in the screen shot below and the <code>wp-json</code> route should beomce accessable in the URL. It is possible that other of these permilink styles will work, but <code>Post name</code> worked for me and I didn't explore beyond that</p>\n\n<p><a href=\"https://i.stack.imgur.com/wxO3O.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/wxO3O.png\" alt=\"Picture illustrating button clicks required to change settings\"></a></p>\n"
},
{
"answer_id": 407856,
"author": "Kris Kratz",
"author_id": 224238,
"author_profile": "https://wordpress.stackexchange.com/users/224238",
"pm_score": 0,
"selected": false,
"text": "<p>Here's how I make a dynamic rest URL in PHP. Then just add on your parameters.</p>\n<pre><code>$rest_url = get_rest_url();\n$delimiter = str_contains($rest_url, '/wp-json/') ? '?' : '&';\n$api_url = $rest_url . 'my-api/v1/route' . $delimiter;\n</code></pre>\n<p><code>$delimiter</code> dynamically changes depending on <code>$rest_url</code></p>\n<p>Old question, but I think it will benefit from a more complete single answer. I was also hardcoding in "/wp-json/", and found this in my search for a solution to both plain and pretty permalink structures.</p>\n"
}
]
| 2017/07/12 | [
"https://wordpress.stackexchange.com/questions/273144",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/94498/"
]
| Recently all of my REST-API requests suddenly turned to return a 404 error, Every request (no matter custom endpoint or built-in).
Then I figured it's because of permalink's structure. `/wp-json/` is not accessible under plain permalink, since there is simply no redirect rule available at the moment.
Is it possible to use the REST endpoints in this situation? Both custom and built-in. | Yes you can. Just add the `rest_route` query parameter.
So
<https://wordpress.org/wp-json/>
would become
<https://wordpress.org/?rest_route=/>
Or `https://wordpress.org/wp-json/wp/v2/` would become `https://wordpress.org/?rest_route=/wp/v2` to give you a more complete example.
So you're wondering how to decide which one to use? Worry no more, there's a function for that: [`get_rest_url()`](https://developer.wordpress.org/reference/functions/get_rest_url/)
Another option is the fact that by default there is a `<link>` in the header that gives you the API root.
```
<link rel='https://api.w.org/' href='https://wordpress.org/wp-json/' />
```
So in case you need to figure that out from client side JS just use something along the lines of
```
document.querySelectorAll('link[rel="https://api.w.org/"]')[0].getAttribute('href');
```
---
So basically you shouldn't take the `wp-json` part as given (and hardcode it) but always build it dynamically either using `get_rest_url()` or the JS approach mentioned above. |
273,165 | <p>I am trying to display a taxonomy term's image and need the term's ID. For some reason I am having trouble getting the ID. If I hard-code the ID in place of <code>$term_id</code> everything works as expected, but of course that doesn't help in a template.</p>
<p>For reference, my taxonomy is <code>Organizations</code> and each entry is the name of an organization.</p>
<p>This is the first time I've really gotten into WordPress functions and templates.</p>
<p>Here's what I have:</p>
<pre><code> <?php
$terms = get_field('listing_organization');
$term_id = get_queried_object_id();
if( $terms ): ?>
<ul>
<?php foreach( $terms as $term ): ?>
<img src="<?php echo z_taxonomy_image_url($term_id, thumbnail); ?>" />
<h2><a href="<?php echo get_term_link( $term ); ?>"><?php echo $term->name; ?></a></h2>
<p><?php echo $term->description; ?></p>
<?php endforeach; ?>
</ul>
<?php endif; ?>
</code></pre>
| [
{
"answer_id": 273168,
"author": "dbeja",
"author_id": 9585,
"author_profile": "https://wordpress.stackexchange.com/users/9585",
"pm_score": 0,
"selected": false,
"text": "<p>Are you using this on an archive page?</p>\n\n<p>Try to get the term ID with this instead:</p>\n\n<pre><code>$queried_object = get_queried_object(); \n$term_id = $queried_object->term_id;\n</code></pre>\n"
},
{
"answer_id": 273170,
"author": "Milo",
"author_id": 4771,
"author_profile": "https://wordpress.stackexchange.com/users/4771",
"pm_score": 3,
"selected": true,
"text": "<p>The term ID is contained within the term object you are already using in your loop:</p>\n\n<pre><code>echo z_taxonomy_image_url( $term->term_id, 'thumbnail' );\n</code></pre>\n"
}
]
| 2017/07/12 | [
"https://wordpress.stackexchange.com/questions/273165",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/123721/"
]
| I am trying to display a taxonomy term's image and need the term's ID. For some reason I am having trouble getting the ID. If I hard-code the ID in place of `$term_id` everything works as expected, but of course that doesn't help in a template.
For reference, my taxonomy is `Organizations` and each entry is the name of an organization.
This is the first time I've really gotten into WordPress functions and templates.
Here's what I have:
```
<?php
$terms = get_field('listing_organization');
$term_id = get_queried_object_id();
if( $terms ): ?>
<ul>
<?php foreach( $terms as $term ): ?>
<img src="<?php echo z_taxonomy_image_url($term_id, thumbnail); ?>" />
<h2><a href="<?php echo get_term_link( $term ); ?>"><?php echo $term->name; ?></a></h2>
<p><?php echo $term->description; ?></p>
<?php endforeach; ?>
</ul>
<?php endif; ?>
``` | The term ID is contained within the term object you are already using in your loop:
```
echo z_taxonomy_image_url( $term->term_id, 'thumbnail' );
``` |
273,194 | <p>I want to prevent posts that dont have thumbnails from showing on the homepage, category page, archive, etc.</p>
<p>Using something like </p>
<pre><code>if (get_the_post_thumbnail_url() != "") {
//don't insert post
}
</code></pre>
<p>What filter / hook should I use?</p>
| [
{
"answer_id": 273206,
"author": "Johansson",
"author_id": 94498,
"author_profile": "https://wordpress.stackexchange.com/users/94498",
"pm_score": 0,
"selected": false,
"text": "<p>What you asked for can be expensive. You can not check if a post has thumbnail or not unless the query is ran. After that, if you exclude it from the query that has already been executed, it will mess with the pagination.</p>\n\n<p>What you can do is to run a query once (before the main query runs), but don't use it to output any content. Then, search for the posts without any thumbnail in that particular query, save their IDs to an array and exclude them from the main query.</p>\n\n<pre><code>add_action( 'pre_get_posts', 'exclude_no_thumbnails' );\nfunction exclude_no_thumbnails( $query ) {\n // Check if we are on the main query\n if (!is_admin() && ( $query->is_main_query() && $query->is_archive() ) ){\n remove_action( 'pre_get_posts', 'exclude_no_thumbnails' );\n // Get a list of the posts in the query\n $posts = get_posts( $query->query );\n // Create an empty array to save the IDs of posts without a thumbnail\n $ids = array();\n // Run a loop and check the thumbnails\n foreach ($posts as $post){\n if(!has_post_thumbnail($post->ID)){\n $ids[] = $post->ID;\n }\n }\n // Now time to exclude these posts from the query\n $query->set( 'post__not_in', $ids );\n }\n}\n</code></pre>\n\n<p>This will probably cost you an extra query. Caching can save your day here.</p>\n"
},
{
"answer_id": 273208,
"author": "hwl",
"author_id": 118366,
"author_profile": "https://wordpress.stackexchange.com/users/118366",
"pm_score": 2,
"selected": false,
"text": "<blockquote>\n <p>What filter / hook should I use?</p>\n</blockquote>\n\n<p>You can use the <code>pre_get_posts</code> action hook.</p>\n\n<p>Following <a href=\"https://wordpress.stackexchange.com/users/736/tom-j-nowell\">Tom's</a> comment on the question about querying for what you want, maybe set <code>meta_query</code> to <code>_thumbnail_id</code>.</p>\n\n<p>I would also <code>(</code> group <code>)</code> the conditionals to read: </p>\n\n<p>\"Is <em>both</em> not admin and is main query, AND is either home, category, or archive.\"</p>\n\n<pre><code>add_action( 'pre_get_posts', 'thumbnails_only' );\n\nfunction thumbnails_only( $query ) {\n if ( ( ! $query->is_admin && $query->is_main_query() ) && ( $query->is_home() || $query->is_category() || $query->is_archive() ) ) {\n\n $meta_query = array(\n array(\n 'key' => '_thumbnail_id',\n )\n );\n\n $query->set( 'meta_query', $meta_query );\n }\n}\n</code></pre>\n\n<p>may want to replace <code>is_home()</code> with <code>is_front_page()</code> <a href=\"https://developer.wordpress.org/reference/functions/is_home/#usage\" rel=\"nofollow noreferrer\">depending on your site settings.</a></p>\n"
}
]
| 2017/07/12 | [
"https://wordpress.stackexchange.com/questions/273194",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/123742/"
]
| I want to prevent posts that dont have thumbnails from showing on the homepage, category page, archive, etc.
Using something like
```
if (get_the_post_thumbnail_url() != "") {
//don't insert post
}
```
What filter / hook should I use? | >
> What filter / hook should I use?
>
>
>
You can use the `pre_get_posts` action hook.
Following [Tom's](https://wordpress.stackexchange.com/users/736/tom-j-nowell) comment on the question about querying for what you want, maybe set `meta_query` to `_thumbnail_id`.
I would also `(` group `)` the conditionals to read:
"Is *both* not admin and is main query, AND is either home, category, or archive."
```
add_action( 'pre_get_posts', 'thumbnails_only' );
function thumbnails_only( $query ) {
if ( ( ! $query->is_admin && $query->is_main_query() ) && ( $query->is_home() || $query->is_category() || $query->is_archive() ) ) {
$meta_query = array(
array(
'key' => '_thumbnail_id',
)
);
$query->set( 'meta_query', $meta_query );
}
}
```
may want to replace `is_home()` with `is_front_page()` [depending on your site settings.](https://developer.wordpress.org/reference/functions/is_home/#usage) |
273,239 | <p><strong>Set-up</strong></p>
<p>I have the following standard Adsense script inserted in my <code>header.php</code> file, </p>
<pre><code><script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js">
</script>
<script>
(adsbygoogle = window.adsbygoogle || []).push({
google_ad_client: "ca-pub-********",
enable_page_level_ads: true
});
</script>
</code></pre>
<p>This allows me to display ads on all pages instantly without too much hassle.</p>
<p><hr>
<strong>Problem</strong></p>
<p>I'd like to prevent display of all adsense ads on specific pages of my website. </p>
<p>I'm looking for some 'if' function to stop the display. Anyone knows of such a function?</p>
| [
{
"answer_id": 273247,
"author": "SleepyAsh",
"author_id": 123718,
"author_profile": "https://wordpress.stackexchange.com/users/123718",
"pm_score": 3,
"selected": true,
"text": "<p>You can use <a href=\"https://developer.wordpress.org/reference/functions/is_page/\" rel=\"nofollow noreferrer\" title=\"this\">this</a> function:<br /></p>\n\n<pre><code><?php if(is_page('your-page-slug')): ?>\n //do nothing on selected pages\n<?php else: ?>\n <script async src=\"//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js\" />\n <script>\n (adsbygoogle = window.adsbygoogle || []).push({\n google_ad_client: \"ca-pub-********\",\n enable_page_level_ads: true\n });\n </script>\n<?php endif; ?>\n</code></pre>\n\n<p>If you want to disable this on more than one page, just add them like this:</p>\n\n<pre><code><?php if(is_page('your-page-slug1') || is_page('your-page-slug2')): ?>\n</code></pre>\n\n<p>Wordpress Developer Resources are very useful (more than codex), so i recommend checking them out first if you don't know how to do something</p>\n"
},
{
"answer_id": 300574,
"author": "Joachim",
"author_id": 141647,
"author_profile": "https://wordpress.stackexchange.com/users/141647",
"pm_score": -1,
"selected": false,
"text": "<p>I can recommend the free plugin Advanced Ads for this mission. You can easily select the pages on which you want to (not) inject this code. Installation and setup will take around 10 minutes, but afterward, you can add pages without any need to touch code. </p>\n\n<p>Here is a tutorial about this setup with Advanced Ads: <a href=\"https://wpadvancedads.com/how-to-block-ads-on-a-specific-page/\" rel=\"nofollow noreferrer\">https://wpadvancedads.com/how-to-block-ads-on-a-specific-page/</a></p>\n"
},
{
"answer_id": 309454,
"author": "rluks",
"author_id": 82485,
"author_profile": "https://wordpress.stackexchange.com/users/82485",
"pm_score": 1,
"selected": false,
"text": "<p>Step 1: Login to your your AdSense dashboard and click on My ads>>Auto ads>>New URL group</p>\n\n<p>Step 2: Select URLs\nThe next thing you need to do is to enter all the URLs you want to choose a new global setting for…click on ‘Add URL’.</p>\n\n<p>Step 3: Select ad settings for new URL groups\nSince you don’t want ads displaying on those pages, toggle off all ads format for those pages and click on ‘next‘.</p>\n\n<p>Source: <a href=\"https://www.naijahomebased.com/stop-google-ads-from-displaying/\" rel=\"nofollow noreferrer\">https://www.naijahomebased.com/stop-google-ads-from-displaying/</a></p>\n"
}
]
| 2017/07/13 | [
"https://wordpress.stackexchange.com/questions/273239",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/123057/"
]
| **Set-up**
I have the following standard Adsense script inserted in my `header.php` file,
```
<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js">
</script>
<script>
(adsbygoogle = window.adsbygoogle || []).push({
google_ad_client: "ca-pub-********",
enable_page_level_ads: true
});
</script>
```
This allows me to display ads on all pages instantly without too much hassle.
---
**Problem**
I'd like to prevent display of all adsense ads on specific pages of my website.
I'm looking for some 'if' function to stop the display. Anyone knows of such a function? | You can use [this](https://developer.wordpress.org/reference/functions/is_page/ "this") function:
```
<?php if(is_page('your-page-slug')): ?>
//do nothing on selected pages
<?php else: ?>
<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js" />
<script>
(adsbygoogle = window.adsbygoogle || []).push({
google_ad_client: "ca-pub-********",
enable_page_level_ads: true
});
</script>
<?php endif; ?>
```
If you want to disable this on more than one page, just add them like this:
```
<?php if(is_page('your-page-slug1') || is_page('your-page-slug2')): ?>
```
Wordpress Developer Resources are very useful (more than codex), so i recommend checking them out first if you don't know how to do something |
273,242 | <p>So im currently developing a plugin, this plugin has a new CPT that i would like to exclude its menu from the admin page of the first site. Im using a multi-site installation. The menu has to only be visible to the other site admins but not the first one.</p>
<p>The Link where i want to remove the menu from is www.example.com/wp-admin</p>
<p>Thank you!</p>
| [
{
"answer_id": 273245,
"author": "TMA",
"author_id": 91044,
"author_profile": "https://wordpress.stackexchange.com/users/91044",
"pm_score": 0,
"selected": false,
"text": "<p>Wordpress <a href=\"https://codex.wordpress.org/WPMU_Functions/switch_to_blog\" rel=\"nofollow noreferrer\"><code>switch to blog</code></a> function will helps to solve your problem. </p>\n"
},
{
"answer_id": 273267,
"author": "Welcher",
"author_id": 27210,
"author_profile": "https://wordpress.stackexchange.com/users/27210",
"pm_score": 1,
"selected": false,
"text": "<p>When you register the custom post type, you can control whether the menu item appears with the <code>show_in_menu</code> arg. You could do something like the following ( this has not been tested ):</p>\n\n<pre><code>// create a constant to store the ID of the blog where the menu should be hidden.\ndefine('HIDDEN_MENU_BLOG_ID', 1 );\n\nfunction codex_custom_init() {\n $show_in_menus = ( HIDDEN_MENU_BLOG_ID === get_current_blog_id() ) ? false : true;\n\n $args = array(\n 'public' => true,\n 'label' => 'Books'\n 'show_in_menu' => $show_in_menus,\n );\n register_post_type( 'book', $args );\n}\nadd_action( 'init', 'codex_custom_init' );\n</code></pre>\n\n<p>This is not very scalable however, you may want to couple this with an admin screen where a super-admin can choose which blogs to hide the menu from.</p>\n\n<p>Hope this helps!</p>\n"
}
]
| 2017/07/13 | [
"https://wordpress.stackexchange.com/questions/273242",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/121367/"
]
| So im currently developing a plugin, this plugin has a new CPT that i would like to exclude its menu from the admin page of the first site. Im using a multi-site installation. The menu has to only be visible to the other site admins but not the first one.
The Link where i want to remove the menu from is www.example.com/wp-admin
Thank you! | When you register the custom post type, you can control whether the menu item appears with the `show_in_menu` arg. You could do something like the following ( this has not been tested ):
```
// create a constant to store the ID of the blog where the menu should be hidden.
define('HIDDEN_MENU_BLOG_ID', 1 );
function codex_custom_init() {
$show_in_menus = ( HIDDEN_MENU_BLOG_ID === get_current_blog_id() ) ? false : true;
$args = array(
'public' => true,
'label' => 'Books'
'show_in_menu' => $show_in_menus,
);
register_post_type( 'book', $args );
}
add_action( 'init', 'codex_custom_init' );
```
This is not very scalable however, you may want to couple this with an admin screen where a super-admin can choose which blogs to hide the menu from.
Hope this helps! |
273,264 | <p>I am developing theme to sell on themefores. I want to get option values in the head. but as the checkoptions would not be called yet i need to call wp-load.php. but the reviewer from themeforest said wp-load.php should not be called in any case. so can you please guide me how can i do the same without requiring wp-load.php ? </p>
<p>Here is my coede </p>
<pre><code><?php
$root = dirname(dirname(dirname(dirname(dirname(__FILE__)))));
if ( file_exists( $root.'/wp-load.php' ) ) {
require_once( $root.'/wp-load.php' );
} else {
$root = dirname(dirname(dirname(dirname(dirname(dirname(__FILE__))))));
if ( file_exists( $root.'/wp-load.php' ) ) {
require_once( $root.'/wp-load.php' );
}
}
$checkOpt = get_option('Bethaven');
header( "Content-type: text/css; charset: UTF-8" );
global $post;
//Footer font color
if (get_post_meta($post->ID, 'oebryn_footer_font_color', true) != '' ) {
$footer_font_color = get_post_meta($post->ID, 'oebryn_footer_font_color', true);
}
elseif ( $checkOpt['oebryn_footer_font_color'] != '' ) {
$footer_font_color = $checkOpt['oebryn_footer_font_color'];
}
// Footer link color
if (get_post_meta($post->ID, 'oebryn_footer_link_color', true) != '' ) {
$footer_font_color = get_post_meta($post->ID, 'oebryn_footer_link_color', true);
}
elseif ( $checkOpt['oebryn_footer_link_color'] != '' ) {
$footer_font_color = $checkOpt['oebryn_footer_link_color'];
}
// Footer hovered color
if (get_post_meta($post->ID, 'oebryn_footer_link_hover', true) != '' ) {
$footer_hovered = get_post_meta($post->ID, 'oebryn_footer_link_hover', true);
}
elseif ( $checkOpt['oebryn_footer_link_hover'] != '' ) {
$footer_hovered = $checkOpt['oebryn_footer_link_hover'];
}
// Widget title color
if (get_post_meta($post->ID, 'oebryn_footer_widget_title', true) != '' ) {
$footer_title = get_post_meta($post->ID, 'oebryn_footer_widget_title', true);
}
elseif ( $checkOpt['oebryn_footer_widget_title'] != '' ) {
$footer_title = $checkOpt['oebryn_footer_widget_title'];
}
?>
#header-bar nav ul#oebryn-navigation > li >a {
color: <?php echo esc_attr($checkOpt['oebryn_header_color'] );?> !important;
}
#oebryn-navigation ul.sub-menu {
background-color: <?php echo esc_attr($checkOpt['oebryn_submenu_background']); ?> !important;
}
#header-bar ul#oebryn-navigation li ul.sub-menu li ul.sub-menu a, #header-bar ul#oebryn-navigation li ul.sub-menu li a {
color: <?php echo esc_attr($checkOpt['oebryn_submenu_color'] );?> !important;
}
ul#oebryn-navigation li ul.sub-menu li ul.sub-menu li:hover, #header-bar ul#oebryn-navigation li ul.sub-menu li:hover {
border-bottom: 1px <?php echo esc_attr($checkOpt['oebryn_submenu_hover_color'] );?> solid !important;
}
#header-bar ul#oebryn-navigation li.megamenu ul.sub-menu li >a {
color: <?php echo esc_attr($checkOpt['oebryn_megamenu_titles'] );?> !important;
}
.sticky {
background-color: <?php echo esc_attr($checkOpt['oebryn_sticky_background']['rgba'] );?> !important;
line-height: <?php echo esc_attr($checkOpt['oebryn_sticky_height']); ?> !important;
height: <?php echo esc_attr($checkOpt['oebryn_sticky_height']); ?> !important;
border-bottom: <?php echo esc_attr($checkOpt['oebryn_sticky_border']); ?> solid <?php echo esc_attr($checkOpt['oebryn_sticky_border_color']['rgba']); ?> !important;
}
#header-bar.sticky ul#oebryn-navigation li a {
color: <?php echo esc_attr($checkOpt['oebryn_sticky_font_color']['rgba']); ?> !important;
}
#header-bar.sticky ul.second-menu li.header-cart {
border-bottom: <?php echo esc_attr($checkOpt['oebryn_sticky_border']); ?> solid <?php echo esc_attr($checkOpt['oebryn_sticky_border_color']['rgba']); ?> !important;
line-height: <?php echo esc_attr($checkOpt['oebryn_sticky_height']); ?> !important;
height: <?php echo esc_attr($checkOpt['oebryn_sticky_height']); ?> !important;
}
.widget li, .widget li a , .contact-info-widget ul li > i {
color: <?php echo esc_attr($footer_font_color); ?>;
}
.widget li a:hover {
color: <?php echo esc_attr($footer_hovered); ?>;
}
footer .widget h6 {
color: <?php echo esc_attr($footer_title); ?>;
}
.mobile-menu-logo-wrapper {
background-image: url('<?php echo esc_url($checkOpt['oebryn_mobile_menu_background_image']['url']) ?>');
background-color: <?php echo esc_url($checkOpt['oebryn_mobile_menu_background']); ?>;
}
.mobile-menu-logo-inner {
background-color: <?php echo esc_attr($checkOpt['oebryn_mobile_menu_background_overlay']['rgba']); ?>;
}
.menu-parent, .mobile-menu-cart .mobile-menu-meta > p > a.menu-checkout {
background-color: <?php echo esc_attr($checkOpt['oebryn_mobile_menu_background'] );?> !important;
}
.ul.mobile-menu-cart-items li, .oebryn-mobile-menuwrapper li a, .mobile-menu-cart .mobile-menu-meta > p > a.menu-checkout {
color: <?php echo esc_attr($checkOpt['oebryn_mobile_menu_fontcolor']) ;?> !important;
}
</code></pre>
| [
{
"answer_id": 273252,
"author": "satibel",
"author_id": 123782,
"author_profile": "https://wordpress.stackexchange.com/users/123782",
"pm_score": 2,
"selected": false,
"text": "<p>Disclaimer: I haven't used this, but from the description it looks like a good fit.</p>\n\n<hr>\n\n<p>The <a href=\"https://wordpress.org/plugins/groups/\" rel=\"nofollow noreferrer\">groups plugin</a> says it allows you to restrict an user's access to posts, so you could create one group per language, and assign each user to a group, then restrict users to only be able to edit posts of their group.</p>\n\n<p>The language info might be duplicated between polylang and groups, but it would probably work.</p>\n\n<p>If this doesn't work, leave a comment, I'll delete (or edit) the post.</p>\n"
},
{
"answer_id": 273466,
"author": "Mike",
"author_id": 52894,
"author_profile": "https://wordpress.stackexchange.com/users/52894",
"pm_score": 3,
"selected": true,
"text": "<p>There is actually a plugin that offers this exact functionality: <a href=\"http://wooexperts.com/plugins/polylang-user-manager/\" rel=\"nofollow noreferrer\">Polylang User Manager</a>:</p>\n\n<blockquote>\n <p>Polylang User Manager will work with Polylang WordPress multilingual Plugin, it will allow you to restrict access for editors/shop_manager or other user role based on languages they’re not assigned as Translators or editor.</p>\n</blockquote>\n"
}
]
| 2017/07/13 | [
"https://wordpress.stackexchange.com/questions/273264",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/123788/"
]
| I am developing theme to sell on themefores. I want to get option values in the head. but as the checkoptions would not be called yet i need to call wp-load.php. but the reviewer from themeforest said wp-load.php should not be called in any case. so can you please guide me how can i do the same without requiring wp-load.php ?
Here is my coede
```
<?php
$root = dirname(dirname(dirname(dirname(dirname(__FILE__)))));
if ( file_exists( $root.'/wp-load.php' ) ) {
require_once( $root.'/wp-load.php' );
} else {
$root = dirname(dirname(dirname(dirname(dirname(dirname(__FILE__))))));
if ( file_exists( $root.'/wp-load.php' ) ) {
require_once( $root.'/wp-load.php' );
}
}
$checkOpt = get_option('Bethaven');
header( "Content-type: text/css; charset: UTF-8" );
global $post;
//Footer font color
if (get_post_meta($post->ID, 'oebryn_footer_font_color', true) != '' ) {
$footer_font_color = get_post_meta($post->ID, 'oebryn_footer_font_color', true);
}
elseif ( $checkOpt['oebryn_footer_font_color'] != '' ) {
$footer_font_color = $checkOpt['oebryn_footer_font_color'];
}
// Footer link color
if (get_post_meta($post->ID, 'oebryn_footer_link_color', true) != '' ) {
$footer_font_color = get_post_meta($post->ID, 'oebryn_footer_link_color', true);
}
elseif ( $checkOpt['oebryn_footer_link_color'] != '' ) {
$footer_font_color = $checkOpt['oebryn_footer_link_color'];
}
// Footer hovered color
if (get_post_meta($post->ID, 'oebryn_footer_link_hover', true) != '' ) {
$footer_hovered = get_post_meta($post->ID, 'oebryn_footer_link_hover', true);
}
elseif ( $checkOpt['oebryn_footer_link_hover'] != '' ) {
$footer_hovered = $checkOpt['oebryn_footer_link_hover'];
}
// Widget title color
if (get_post_meta($post->ID, 'oebryn_footer_widget_title', true) != '' ) {
$footer_title = get_post_meta($post->ID, 'oebryn_footer_widget_title', true);
}
elseif ( $checkOpt['oebryn_footer_widget_title'] != '' ) {
$footer_title = $checkOpt['oebryn_footer_widget_title'];
}
?>
#header-bar nav ul#oebryn-navigation > li >a {
color: <?php echo esc_attr($checkOpt['oebryn_header_color'] );?> !important;
}
#oebryn-navigation ul.sub-menu {
background-color: <?php echo esc_attr($checkOpt['oebryn_submenu_background']); ?> !important;
}
#header-bar ul#oebryn-navigation li ul.sub-menu li ul.sub-menu a, #header-bar ul#oebryn-navigation li ul.sub-menu li a {
color: <?php echo esc_attr($checkOpt['oebryn_submenu_color'] );?> !important;
}
ul#oebryn-navigation li ul.sub-menu li ul.sub-menu li:hover, #header-bar ul#oebryn-navigation li ul.sub-menu li:hover {
border-bottom: 1px <?php echo esc_attr($checkOpt['oebryn_submenu_hover_color'] );?> solid !important;
}
#header-bar ul#oebryn-navigation li.megamenu ul.sub-menu li >a {
color: <?php echo esc_attr($checkOpt['oebryn_megamenu_titles'] );?> !important;
}
.sticky {
background-color: <?php echo esc_attr($checkOpt['oebryn_sticky_background']['rgba'] );?> !important;
line-height: <?php echo esc_attr($checkOpt['oebryn_sticky_height']); ?> !important;
height: <?php echo esc_attr($checkOpt['oebryn_sticky_height']); ?> !important;
border-bottom: <?php echo esc_attr($checkOpt['oebryn_sticky_border']); ?> solid <?php echo esc_attr($checkOpt['oebryn_sticky_border_color']['rgba']); ?> !important;
}
#header-bar.sticky ul#oebryn-navigation li a {
color: <?php echo esc_attr($checkOpt['oebryn_sticky_font_color']['rgba']); ?> !important;
}
#header-bar.sticky ul.second-menu li.header-cart {
border-bottom: <?php echo esc_attr($checkOpt['oebryn_sticky_border']); ?> solid <?php echo esc_attr($checkOpt['oebryn_sticky_border_color']['rgba']); ?> !important;
line-height: <?php echo esc_attr($checkOpt['oebryn_sticky_height']); ?> !important;
height: <?php echo esc_attr($checkOpt['oebryn_sticky_height']); ?> !important;
}
.widget li, .widget li a , .contact-info-widget ul li > i {
color: <?php echo esc_attr($footer_font_color); ?>;
}
.widget li a:hover {
color: <?php echo esc_attr($footer_hovered); ?>;
}
footer .widget h6 {
color: <?php echo esc_attr($footer_title); ?>;
}
.mobile-menu-logo-wrapper {
background-image: url('<?php echo esc_url($checkOpt['oebryn_mobile_menu_background_image']['url']) ?>');
background-color: <?php echo esc_url($checkOpt['oebryn_mobile_menu_background']); ?>;
}
.mobile-menu-logo-inner {
background-color: <?php echo esc_attr($checkOpt['oebryn_mobile_menu_background_overlay']['rgba']); ?>;
}
.menu-parent, .mobile-menu-cart .mobile-menu-meta > p > a.menu-checkout {
background-color: <?php echo esc_attr($checkOpt['oebryn_mobile_menu_background'] );?> !important;
}
.ul.mobile-menu-cart-items li, .oebryn-mobile-menuwrapper li a, .mobile-menu-cart .mobile-menu-meta > p > a.menu-checkout {
color: <?php echo esc_attr($checkOpt['oebryn_mobile_menu_fontcolor']) ;?> !important;
}
``` | There is actually a plugin that offers this exact functionality: [Polylang User Manager](http://wooexperts.com/plugins/polylang-user-manager/):
>
> Polylang User Manager will work with Polylang WordPress multilingual Plugin, it will allow you to restrict access for editors/shop\_manager or other user role based on languages they’re not assigned as Translators or editor.
>
>
> |
273,289 | <p>Using the plugin "Advanced Custom Fields":
<a href="https://wordpress.org/plugins/advanced-custom-fields/" rel="nofollow noreferrer">https://wordpress.org/plugins/advanced-custom-fields/</a>
I am able to add my custom fields to profile.php.</p>
<p><strong>But how do I remove the default elements from profile.php (Personal Options, Name, etc.)?</strong></p>
<p>I know I can create new template files in my child theme to override how pages look, but I can't find how to do this with profile.php.</p>
<p>I started using CSS to hide the elements, this works except for the titles which have no class or ID, and I can't simply hide the entire form because Advanced Custom Fields places the new elements in this same form.</p>
<p>I would prefer to stay away from large plugins that create front end user accounts on top of the existing system just so I can get a customized profile editing page.</p>
<p>Thanks for any help.</p>
| [
{
"answer_id": 273304,
"author": "Charles",
"author_id": 15605,
"author_profile": "https://wordpress.stackexchange.com/users/15605",
"pm_score": 2,
"selected": true,
"text": "<p>There are probably several options to achieve your goal, below is one of the options shown by me.<br />\n<em>(these 2 functions belong to each other)</em></p>\n\n<blockquote>\n <p>Please make always a copy of <code>functions.php</code> before you start to edit/add a plugin or other code snippet.</p>\n</blockquote>\n\n<pre><code>/**\n * Remove fields from an user profile page for all except Administrator\n *\n * FYI {@link https://codex.wordpress.org/Function_Reference/current_user_can}\n * {@link https://codex.wordpress.org/Roles_and_Capabilities}\n * {@link https://codex.wordpress.org/Plugin_API/Action_Reference/admin_footer}\n * {@link https://developer.wordpress.org/reference/hooks/load-pagenow/}\n *\n * Checked with @version WordPress 4.8\n */\nadd_action('admin_init', 'wpse273289_remove_profile_fields' ); \nfunction wpse273289_remove_profile_fields()\n{ \n global $pagenow;\n\n // apply only to user profile or user edit pages\n if( $pagenow !=='profile.php' && $pagenow !=='user-edit.php' )\n {\n return;\n }\n\n // Make it happen for all except Administrators\n if( current_user_can( 'manage_options' ) )\n {\n return;\n }\n\n add_action( 'admin_footer', 'wpse273289_remove_profile_fields_js' ); \n}\n\n/**\n * Remove (below)selected fields on user profile\n * This function belongs to the wpse273289_remove_profile_fields function!\n * \n */\nfunction wpse273289_remove_profile_fields_js()\n{\n ?>\n <script>\n jQuery(document).ready( function($) {\n $('input#user_login').closest('tr').remove(); // Username\n $('input#first_name').closest('tr').remove(); // First Name\n $('input#nickname').closest('tr').remove(); // Nickname (required) \n $('input#email').closest('tr').remove(); // Email (required)\n });\n </script>\n <?php\n}\n</code></pre>\n\n<blockquote>\n <p>The fields above in the script are just examples so please adjust to your own preference.<br /> Both functions are checked in a local sandbox and working for me. <br /></p>\n \n <blockquote>\n <p>Note: above is NOT tested with ACF plugin but that should not be a problem.</p>\n </blockquote>\n</blockquote>\n"
},
{
"answer_id": 281886,
"author": "Juraj.Lorinc",
"author_id": 67602,
"author_profile": "https://wordpress.stackexchange.com/users/67602",
"pm_score": 0,
"selected": false,
"text": "<p>Other option is to use css to disable/hide those elements. </p>\n\n<p>First you need to add function which will add body class based on user role:</p>\n\n<pre><code>function your_prefix_add_admin_body_class( $classes ) {\n $roles = wp_get_current_user()->roles;\n return \"$classes \".implode(' ', $roles);\n}\n\nadd_filter( 'admin_body_class', 'your_prefix_add_admin_body_class' );\n</code></pre>\n\n<p>And then add custom css to your admin:</p>\n\n<pre><code>function your_prefix_custom_css() {\n echo '<style>\n body:not(.administrator) .user-user-login-wrap,\n body:not(.administrator) .user-first-name-wrap,\n body:not(.administrator) .user-last-name-wrap{\n display: none;\n }\n </style>';\n}\n\nadd_action('admin_head', 'your_prefix_custom_css');\n</code></pre>\n\n<p>Just keep in mind, this is not the most secure solution. If user knows a bit of css, he can re-enable it.</p>\n"
}
]
| 2017/07/13 | [
"https://wordpress.stackexchange.com/questions/273289",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/123624/"
]
| Using the plugin "Advanced Custom Fields":
<https://wordpress.org/plugins/advanced-custom-fields/>
I am able to add my custom fields to profile.php.
**But how do I remove the default elements from profile.php (Personal Options, Name, etc.)?**
I know I can create new template files in my child theme to override how pages look, but I can't find how to do this with profile.php.
I started using CSS to hide the elements, this works except for the titles which have no class or ID, and I can't simply hide the entire form because Advanced Custom Fields places the new elements in this same form.
I would prefer to stay away from large plugins that create front end user accounts on top of the existing system just so I can get a customized profile editing page.
Thanks for any help. | There are probably several options to achieve your goal, below is one of the options shown by me.
*(these 2 functions belong to each other)*
>
> Please make always a copy of `functions.php` before you start to edit/add a plugin or other code snippet.
>
>
>
```
/**
* Remove fields from an user profile page for all except Administrator
*
* FYI {@link https://codex.wordpress.org/Function_Reference/current_user_can}
* {@link https://codex.wordpress.org/Roles_and_Capabilities}
* {@link https://codex.wordpress.org/Plugin_API/Action_Reference/admin_footer}
* {@link https://developer.wordpress.org/reference/hooks/load-pagenow/}
*
* Checked with @version WordPress 4.8
*/
add_action('admin_init', 'wpse273289_remove_profile_fields' );
function wpse273289_remove_profile_fields()
{
global $pagenow;
// apply only to user profile or user edit pages
if( $pagenow !=='profile.php' && $pagenow !=='user-edit.php' )
{
return;
}
// Make it happen for all except Administrators
if( current_user_can( 'manage_options' ) )
{
return;
}
add_action( 'admin_footer', 'wpse273289_remove_profile_fields_js' );
}
/**
* Remove (below)selected fields on user profile
* This function belongs to the wpse273289_remove_profile_fields function!
*
*/
function wpse273289_remove_profile_fields_js()
{
?>
<script>
jQuery(document).ready( function($) {
$('input#user_login').closest('tr').remove(); // Username
$('input#first_name').closest('tr').remove(); // First Name
$('input#nickname').closest('tr').remove(); // Nickname (required)
$('input#email').closest('tr').remove(); // Email (required)
});
</script>
<?php
}
```
>
> The fields above in the script are just examples so please adjust to your own preference.
> Both functions are checked in a local sandbox and working for me.
>
>
>
>
> >
> > Note: above is NOT tested with ACF plugin but that should not be a problem.
> >
> >
> >
>
>
> |
273,302 | <p>I'm getting an error on the admin screen for the custom post type. I've searched lots of other answers but see nothing in my code that could be causing it. Here's my code. Any help would be greatly appreciated.</p>
<pre><code>// Register the post types and taxonomys
add_action('init', 'register_post_types');
function register_post_types(){
// Property Post Type
$labels = array(
'name' => __('Properties'),
'singular_name' => __('Property'),
'add_new' => __('Add New'),
'add_new_item' => __('Add New Property'),
'edit_item' => __('Edit Property'),
'new_item' => __('New Property'),
'view_item' => __('View Property'),
'search_items' => __('Search Properties'),
'not_found' => __('Nothing found'),
'not_found_in_trash' => __('Nothing found in Trash'),
'parent_item_colon' => '',
);
$args = array(
'labels' => $labels,
'public' => true,
'publicly_queryable' => true,
'show_ui' => true,
'register_meta_box_cb' => 'custom_meta_boxes',
'query_var' => true,
'menu_icon' => null,
'rewrite' => true,
'capability_type' => 'post',
'hierarchical' => false,
'menu_position' => 5,
'supports' => array( 'title', 'editor', 'genesis-seo', 'thumbnail','genesis-cpt-archives-settings' ),
'has_archive' => true,
);
register_post_type('property' , $args);
// Property Taxonomy
$taxononmy_args = array(
'hierarchical' => true,
'label' => "Categories",
'singular_label' => "Category",
'rewrite' => true,
'show_admin_column' => TRUE
);
register_taxonomy("property_categories", array("property"), $taxononmy_args);
}
</code></pre>
| [
{
"answer_id": 273325,
"author": "Sddarter",
"author_id": 62082,
"author_profile": "https://wordpress.stackexchange.com/users/62082",
"pm_score": 1,
"selected": false,
"text": "<p>I've removed the custom_meta_boxes. I don't have to have them and it solves the problem. I still don't understand why they were a problem, but if I can do without them I will.</p>\n\n<p>I appreciate everyone's efforts.</p>\n\n<p>Note: rolling back to 4.7 made no difference.</p>\n"
},
{
"answer_id": 360504,
"author": "sleepingpanda",
"author_id": 183303,
"author_profile": "https://wordpress.stackexchange.com/users/183303",
"pm_score": 0,
"selected": false,
"text": "<p>where is your <code>custom_meta_boxes</code> function where you are adding your meta boxes?</p>\n\n<p>Please see this <a href=\"https://wptheming.com/2010/08/custom-metabox-for-post-type/\" rel=\"nofollow noreferrer\">URL</a> for creating a custom meta box for the custom post type.\nAfter adding this function your code will work fine.</p>\n"
}
]
| 2017/07/13 | [
"https://wordpress.stackexchange.com/questions/273302",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/62082/"
]
| I'm getting an error on the admin screen for the custom post type. I've searched lots of other answers but see nothing in my code that could be causing it. Here's my code. Any help would be greatly appreciated.
```
// Register the post types and taxonomys
add_action('init', 'register_post_types');
function register_post_types(){
// Property Post Type
$labels = array(
'name' => __('Properties'),
'singular_name' => __('Property'),
'add_new' => __('Add New'),
'add_new_item' => __('Add New Property'),
'edit_item' => __('Edit Property'),
'new_item' => __('New Property'),
'view_item' => __('View Property'),
'search_items' => __('Search Properties'),
'not_found' => __('Nothing found'),
'not_found_in_trash' => __('Nothing found in Trash'),
'parent_item_colon' => '',
);
$args = array(
'labels' => $labels,
'public' => true,
'publicly_queryable' => true,
'show_ui' => true,
'register_meta_box_cb' => 'custom_meta_boxes',
'query_var' => true,
'menu_icon' => null,
'rewrite' => true,
'capability_type' => 'post',
'hierarchical' => false,
'menu_position' => 5,
'supports' => array( 'title', 'editor', 'genesis-seo', 'thumbnail','genesis-cpt-archives-settings' ),
'has_archive' => true,
);
register_post_type('property' , $args);
// Property Taxonomy
$taxononmy_args = array(
'hierarchical' => true,
'label' => "Categories",
'singular_label' => "Category",
'rewrite' => true,
'show_admin_column' => TRUE
);
register_taxonomy("property_categories", array("property"), $taxononmy_args);
}
``` | I've removed the custom\_meta\_boxes. I don't have to have them and it solves the problem. I still don't understand why they were a problem, but if I can do without them I will.
I appreciate everyone's efforts.
Note: rolling back to 4.7 made no difference. |
273,322 | <p>Right now I've got future posts displayed on my site, and I was using this code on each post to show when it was published.</p>
<pre><code><?php echo human_time_diff( get_the_time('U'), current_time('timestamp') ) . ' ago'; ?>
</code></pre>
<p>Naturally it shows a post 2 days from now as 2 days ago. How might I fix it so it says "ago" and maybe "from now" where applicable?</p>
| [
{
"answer_id": 273326,
"author": "mwz",
"author_id": 121004,
"author_profile": "https://wordpress.stackexchange.com/users/121004",
"pm_score": 1,
"selected": true,
"text": "<p>I managed to figure it out</p>\n\n<pre><code><?php\n if ( get_post_status ( $ID ) == 'future' ) { \necho human_time_diff( get_the_time('U'), current_time('timestamp') ) . ' from \nnow';\n } else { \necho human_time_diff( get_the_time('U'), current_time('timestamp') ) . ' ago'; ?>\n</code></pre>\n"
},
{
"answer_id": 273331,
"author": "Picard",
"author_id": 118566,
"author_profile": "https://wordpress.stackexchange.com/users/118566",
"pm_score": 1,
"selected": false,
"text": "<p>You could also do it using <code>human_time_diff</code> hook, but it would make it global:</p>\n\n<pre><code>function my_time_diff_mins( $since, $diff, $from, $to ) {\n return $since . ($from > $to ? ' from now' : ' ago');\n}\nadd_filter( 'human_time_diff', 'my_time_diff_mins', 10, 4 );\n</code></pre>\n"
}
]
| 2017/07/13 | [
"https://wordpress.stackexchange.com/questions/273322",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/121004/"
]
| Right now I've got future posts displayed on my site, and I was using this code on each post to show when it was published.
```
<?php echo human_time_diff( get_the_time('U'), current_time('timestamp') ) . ' ago'; ?>
```
Naturally it shows a post 2 days from now as 2 days ago. How might I fix it so it says "ago" and maybe "from now" where applicable? | I managed to figure it out
```
<?php
if ( get_post_status ( $ID ) == 'future' ) {
echo human_time_diff( get_the_time('U'), current_time('timestamp') ) . ' from
now';
} else {
echo human_time_diff( get_the_time('U'), current_time('timestamp') ) . ' ago'; ?>
``` |
273,333 | <p>The Admin Bar has a menu with shortcuts for adding new content.</p>
<p>By default, it shows "Post", "Media", "Page" and "User".</p>
<p><a href="https://i.stack.imgur.com/0ydcC.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/0ydcC.png" alt="enter image description here"></a></p>
<p>I'm using <code>register_post_type</code> to register a new custom post type. I can use its <code>menu_position</code> property to change the position in the dashboard menu, but how can I reorder the shortcut link so it will show higher, instead of just above "User"?</p>
| [
{
"answer_id": 273388,
"author": "Kudratullah",
"author_id": 62726,
"author_profile": "https://wordpress.stackexchange.com/users/62726",
"pm_score": 0,
"selected": false,
"text": "<p>This section rendered via <code>wp_admin_bar_new_content_menu</code> (admin-bar.php <a href=\"https://core.trac.wordpress.org/browser/tags/4.8/src/wp-includes/admin-bar.php#L683\" rel=\"nofollow noreferrer\">Line No. 690-746</a>) callback on <code>admin_bar_menu</code> action (class-wp-admin-bar.php <a href=\"https://core.trac.wordpress.org/browser/tags/4.8/src/wp-includes/class-wp-admin-bar.php#L584\" rel=\"nofollow noreferrer\">Line No. 584-588</a>).</p>\n\n<p>I couldn't find any hooks to filter the menu items here. So i'm thinking of removing that action and add another action with your own sorting.</p>\n\n<p>Remove this action with <code>remove_action</code> and then attach your custom callback again to add menus. Eg.</p>\n\n<pre><code>remove_action( 'admin_bar_menu', 'wp_admin_bar_new_content_menu', 70 );\n\nadd_action( 'admin_bar_menu', 'wpse273333_admin_bar_custom_new_content_menu', 70 );\nfunction wpse_273333_admin_bar_custom_new_content_menu( \\WP_Admin_Bar $wp_admin_bar ){\n // add your menus\n // check wp_admin_bar_new_content_menu() function for some idea\n}\n</code></pre>\n"
},
{
"answer_id": 312573,
"author": "cogdog",
"author_id": 14945,
"author_profile": "https://wordpress.stackexchange.com/users/14945",
"pm_score": 2,
"selected": false,
"text": "<p>I had a similar situation. My custom post type showed up under the Admin Bar as <strong>Artifact</strong>, but my clients preferred it to be at the top of the list. Plus, the items for <strong>Media</strong> and <strong>User</strong> were not really needed.</p>\n\n<p><a href=\"https://i.stack.imgur.com/pI5kR.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/pI5kR.jpg\" alt=\"WordPress New menu before\"></a></p>\n\n<p>My approach was first to user <a href=\"https://codex.wordpress.org/Function_Reference/remove_node\" rel=\"nofollow noreferrer\">remove_node</a> to take away all the ones except my custom post-type and then put back the ones I want with <a href=\"https://codex.wordpress.org/Function_Reference/remove_node\" rel=\"nofollow noreferrer\">add_node</a></p>\n\n<pre><code>add_action( 'wp_before_admin_bar_render', 'portfolio_adminbar' );\n\nfunction portfolio_adminbar() {\n\n global $wp_admin_bar;\n\n // get node for New + menu node\n $new_content_node = $wp_admin_bar->get_node('new-content');\n\n // change URL for node, edit for prefered link\n $new_content_node->href = admin_url( 'post-new.php?post_type=portfolio' );\n\n // Update New + menu node\n $wp_admin_bar->add_node($new_content_node);\n\n // remove all items from New Content menu\n $wp_admin_bar->remove_node('new-post');\n $wp_admin_bar->remove_node('new-media');\n $wp_admin_bar->remove_node('new-page');\n $wp_admin_bar->remove_node('new-user');\n\n // add back the new Post link\n $args = array(\n 'id' => 'new-post', \n 'title' => 'Blog Post', \n 'parent' => 'new-content',\n 'href' => admin_url( 'post-new.php' ),\n 'meta' => array( 'class' => 'ab-item' )\n );\n $wp_admin_bar->add_node( $args );\n\n // add back the new Page \n $args = array(\n 'id' => 'new-page', \n 'title' => 'Page', \n 'parent' => 'new-content',\n 'href' => admin_url( 'post-new.php?post_type=page' ),\n 'meta' => array( 'class' => 'ab-item' )\n );\n $wp_admin_bar->add_node( $args );\n\n}\n</code></pre>\n\n<p>Here is my menu after:</p>\n\n<p><a href=\"https://i.stack.imgur.com/du4kU.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/du4kU.jpg\" alt=\"enter image description here\"></a></p>\n"
}
]
| 2017/07/13 | [
"https://wordpress.stackexchange.com/questions/273333",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/22510/"
]
| The Admin Bar has a menu with shortcuts for adding new content.
By default, it shows "Post", "Media", "Page" and "User".
[](https://i.stack.imgur.com/0ydcC.png)
I'm using `register_post_type` to register a new custom post type. I can use its `menu_position` property to change the position in the dashboard menu, but how can I reorder the shortcut link so it will show higher, instead of just above "User"? | I had a similar situation. My custom post type showed up under the Admin Bar as **Artifact**, but my clients preferred it to be at the top of the list. Plus, the items for **Media** and **User** were not really needed.
[](https://i.stack.imgur.com/pI5kR.jpg)
My approach was first to user [remove\_node](https://codex.wordpress.org/Function_Reference/remove_node) to take away all the ones except my custom post-type and then put back the ones I want with [add\_node](https://codex.wordpress.org/Function_Reference/remove_node)
```
add_action( 'wp_before_admin_bar_render', 'portfolio_adminbar' );
function portfolio_adminbar() {
global $wp_admin_bar;
// get node for New + menu node
$new_content_node = $wp_admin_bar->get_node('new-content');
// change URL for node, edit for prefered link
$new_content_node->href = admin_url( 'post-new.php?post_type=portfolio' );
// Update New + menu node
$wp_admin_bar->add_node($new_content_node);
// remove all items from New Content menu
$wp_admin_bar->remove_node('new-post');
$wp_admin_bar->remove_node('new-media');
$wp_admin_bar->remove_node('new-page');
$wp_admin_bar->remove_node('new-user');
// add back the new Post link
$args = array(
'id' => 'new-post',
'title' => 'Blog Post',
'parent' => 'new-content',
'href' => admin_url( 'post-new.php' ),
'meta' => array( 'class' => 'ab-item' )
);
$wp_admin_bar->add_node( $args );
// add back the new Page
$args = array(
'id' => 'new-page',
'title' => 'Page',
'parent' => 'new-content',
'href' => admin_url( 'post-new.php?post_type=page' ),
'meta' => array( 'class' => 'ab-item' )
);
$wp_admin_bar->add_node( $args );
}
```
Here is my menu after:
[](https://i.stack.imgur.com/du4kU.jpg) |
273,367 | <p>Im trying to remove the editor from the homepage using the following functions however I am struggling to achieve this?</p>
<pre><code>function hide_homepage_editor() {
if ( is_admin() ) {
if (is_front_page()) {
remove_post_type_support('page', 'editor');
}
}
}
add_action( 'admin_init', 'hide_homepage_editor' );
</code></pre>
<p>another try:</p>
<pre><code>function hide_homepage_editor() {
if ( is_admin() ) {
$post_id = 0;
if(isset($_GET['post'])) $post_id = $_GET['post'];
$template_file = get_post_meta($post_id, '_wp_page_template', TRUE);
if ($template_file == 'front-page.php') {
remove_post_type_support('page', 'editor');
}
}
}
add_action( 'admin_init', 'hide_homepage_editor' );
</code></pre>
<p>Anyone know why these are not working and how I can remove the page editor from the page set as frontpage?</p>
| [
{
"answer_id": 273371,
"author": "Andrew M",
"author_id": 89356,
"author_profile": "https://wordpress.stackexchange.com/users/89356",
"pm_score": 5,
"selected": true,
"text": "<p>There are a couple of issues with your approach</p>\n\n<p>By using the <strong>admin_init</strong> hook you won't have any reference to the post object. This means you won't be able to get the post ID or use anything like get_the_ID because the post won't actually be loaded. You can see that in the order here <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference\" rel=\"noreferrer\">https://codex.wordpress.org/Plugin_API/Action_Reference</a></p>\n\n<p>So if you run the action hook after the wp action you'll have the post object. For example</p>\n\n<pre><code>add_action('admin_head', 'remove_content_editor');\n/**\n * Remove the content editor from ALL pages \n */\nfunction remove_content_editor()\n{ \n remove_post_type_support('page', 'editor'); \n}\n</code></pre>\n\n<p>Now this snippet will remove the editor from all pages. The problem is that <strong>is_home</strong> and <strong>is_front_page</strong> won't work on the admin side so you'll need to add some meta data to distinguish whether you're on the home page. There's a very comprehensive discussion of approaches for that on this page: <a href=\"https://wordpress.stackexchange.com/questions/103433/best-way-to-present-options-for-home-page-in-admin\">Best way to present options for home page in admin?</a></p>\n\n<p>So, if you used some extra meta data, you can then check this like</p>\n\n<pre><code>add_action('admin_head', 'remove_content_editor');\n/**\n * Remove the content editor from ALL pages \n */\nfunction remove_content_editor()\n{\n //Check against your meta data here\n if(get_post_meta( get_the_ID(), 'is_home_page' )){ \n remove_post_type_support('page', 'editor'); \n }\n\n}\n</code></pre>\n\n<p>Hopefully that will help you out</p>\n\n<p>******* Update ************</p>\n\n<p>Actually, I've just looked into this again and realised that there is an easier way. If you have set the front page to be a static page in the Reading settings, you can check against the <strong>page_on_front</strong> option value. In that case, the following will work</p>\n\n<pre><code>add_action('admin_head', 'remove_content_editor');\n/**\n * Remove the content editor from pages as all content is handled through Panels\n */\nfunction remove_content_editor()\n{\n if((int) get_option('page_on_front')==get_the_ID())\n {\n remove_post_type_support('page', 'editor');\n }\n}\n</code></pre>\n"
},
{
"answer_id": 305539,
"author": "Nic Bug",
"author_id": 144969,
"author_profile": "https://wordpress.stackexchange.com/users/144969",
"pm_score": 2,
"selected": false,
"text": "<p>thanks for the solution Andrew. I added a code for the page translated by polylang to apply the filter too:</p>\n\n<pre><code>/**\n * Remove the content editor from front page\n */\nfunction remove_content_editor(){\n if((int) get_option('page_on_front')==get_the_ID()){\n remove_post_type_support('page', 'editor');\n }\n if(function_exists(\"pll_get_post\")){\n if((int) pll_get_post(get_the_ID(),\"en\")==get_the_ID()){\n remove_post_type_support('page', 'editor');\n }\n }\n}\nadd_action('admin_head', 'remove_content_editor');\n</code></pre>\n\n<p>Change \"en\" to the matching language string. in my case first language is german and second english (en).</p>\n"
},
{
"answer_id": 344711,
"author": "Mauro Mascia",
"author_id": 44922,
"author_profile": "https://wordpress.stackexchange.com/users/44922",
"pm_score": 3,
"selected": false,
"text": "<p>Update for Wordpress 5 with Gutenberg:</p>\n\n<pre><code><?php\n/**\n * Disable standard editor and Gutenberg for the homepage\n * keeping the status (enabled/disabled) for others who uses the same filter (i.e. ACF)\n */\nadd_filter( 'use_block_editor_for_post', 'yourtheme_hide_editor', 10, 2 );\nfunction yourtheme_hide_editor( $use_block_editor, $post_type ) {\n if ( (int) get_option( 'page_on_front' ) == get_the_ID() ) { // on frontpage\n remove_post_type_support( 'page', 'editor' ); // disable standard editor\n return false; // and disable gutenberg\n }\n\n return $use_block_editor; // keep gutenberg status for other pages/posts \n}\n</code></pre>\n"
}
]
| 2017/07/14 | [
"https://wordpress.stackexchange.com/questions/273367",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/102937/"
]
| Im trying to remove the editor from the homepage using the following functions however I am struggling to achieve this?
```
function hide_homepage_editor() {
if ( is_admin() ) {
if (is_front_page()) {
remove_post_type_support('page', 'editor');
}
}
}
add_action( 'admin_init', 'hide_homepage_editor' );
```
another try:
```
function hide_homepage_editor() {
if ( is_admin() ) {
$post_id = 0;
if(isset($_GET['post'])) $post_id = $_GET['post'];
$template_file = get_post_meta($post_id, '_wp_page_template', TRUE);
if ($template_file == 'front-page.php') {
remove_post_type_support('page', 'editor');
}
}
}
add_action( 'admin_init', 'hide_homepage_editor' );
```
Anyone know why these are not working and how I can remove the page editor from the page set as frontpage? | There are a couple of issues with your approach
By using the **admin\_init** hook you won't have any reference to the post object. This means you won't be able to get the post ID or use anything like get\_the\_ID because the post won't actually be loaded. You can see that in the order here <https://codex.wordpress.org/Plugin_API/Action_Reference>
So if you run the action hook after the wp action you'll have the post object. For example
```
add_action('admin_head', 'remove_content_editor');
/**
* Remove the content editor from ALL pages
*/
function remove_content_editor()
{
remove_post_type_support('page', 'editor');
}
```
Now this snippet will remove the editor from all pages. The problem is that **is\_home** and **is\_front\_page** won't work on the admin side so you'll need to add some meta data to distinguish whether you're on the home page. There's a very comprehensive discussion of approaches for that on this page: [Best way to present options for home page in admin?](https://wordpress.stackexchange.com/questions/103433/best-way-to-present-options-for-home-page-in-admin)
So, if you used some extra meta data, you can then check this like
```
add_action('admin_head', 'remove_content_editor');
/**
* Remove the content editor from ALL pages
*/
function remove_content_editor()
{
//Check against your meta data here
if(get_post_meta( get_the_ID(), 'is_home_page' )){
remove_post_type_support('page', 'editor');
}
}
```
Hopefully that will help you out
\*\*\*\*\*\*\* Update \*\*\*\*\*\*\*\*\*\*\*\*
Actually, I've just looked into this again and realised that there is an easier way. If you have set the front page to be a static page in the Reading settings, you can check against the **page\_on\_front** option value. In that case, the following will work
```
add_action('admin_head', 'remove_content_editor');
/**
* Remove the content editor from pages as all content is handled through Panels
*/
function remove_content_editor()
{
if((int) get_option('page_on_front')==get_the_ID())
{
remove_post_type_support('page', 'editor');
}
}
``` |
273,394 | <p>I'm trying to make simple about me widget with WordPress media uploader. When I click the button <strong>Upload</strong> it opens media uploader, but after I hit <strong>save</strong>, the button doesn't work anymore, the same behavior if I have one active widget and then I add another, media upload button doesn't work in second widget. No JS errors in console. Can someone point me, where I'm wrong?</p>
<p><strong>PHP</strong></p>
<pre><code>class Inka_Profile_Widget extends WP_Widget {
// setup the widget name, description etc.
function __construct() {
$widget_options = array(
'classname' => esc_attr( "inka_profile_widget", 'inka' ),
'description' => esc_html__( 'Custom Profile Widget', 'inka' ),
'customize_selective_refresh' => true
);
parent::__construct( 'inka_profile', 'Inka Profile', $widget_options);
}
// back-end display of widget
function form( $instance ) {
$title = ! empty( $instance['title'] ) ? $instance['title'] : esc_html__( 'About Me', 'inka' );
$image = ! empty( $instance['image'] ) ? $instance['image'] : '';
?>
<p>
<label for="<?php echo esc_attr( $this->get_field_id('title') ); ?>"><?php esc_attr_e( 'Title', 'inka' ); ?></label>
<input class="widefat" id="<?php echo esc_attr( $this->get_field_id( 'title' ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( 'title' ) ); ?>" type="text" value="<?php echo esc_attr( $title ); ?>">
</p>
<p>
<img src="<?php echo esc_attr( $image ); ?>" alt="" class="deo-image-holder" style="width: 100%;">
</p>
<p>
<input type="hidden" class="deo-image-hidden-field" name="<?php echo $this->get_field_name( 'image' ); ?>" id="<?php echo $this->get_field_id( 'image' ); ?>" value="<?php echo esc_attr( $image ); ?>"/>
<input type="button" class="deo-image-upload-button button button-primary" value="Upload">
<input type="button" class="deo-image-delete-button button" value="Remove Image">
</p>
<?php
}
// front-end display of widget
function widget( $args, $instance ) {
echo "Hey";
}
// update of the widget
function update( $new_instance, $old_instance ) {
$instance = $old_instance;
$instance['title'] = ( ! empty( $new_instance['title'] ) ) ? strip_tags( $new_instance['title'] ) : '';
$instance['image'] = ( ! empty( $new_instance['image'] ) ) ? strip_tags( $new_instance['image'] ) : '';
return $instance;
}
}
add_action( 'widgets_init', function() {
register_widget( 'Inka_Profile_Widget' );
});
</code></pre>
<p><strong>JS</strong></p>
<pre><code>(function($){
/* WordPress Media Uploader
-------------------------------------------------------*/
var addButton = $('.deo-image-upload-button');
var deleteButton = $('.deo-image-delete-button');
var hiddenField = $('.deo-image-hidden-field');
var imageHolder = $('.deo-image-holder');
var mediaUploader;
addButton.on('click', function(e) {
e.preventDefault();
if ( mediaUploader ) {
mediaUploader.open();
return;
}
mediaUploader = wp.media.frames.file_frame = wp.media({
title: 'Select an Image',
button: {
text: 'Use This Image'
},
multiple: false
});
mediaUploader.on('select', function() {
var attachment = mediaUploader.state().get('selection').first().toJSON();
hiddenField.val(attachment.url);
imageHolder.attr('src', attachment.url);
});
mediaUploader.open();
});
})(jQuery);
</code></pre>
| [
{
"answer_id": 273371,
"author": "Andrew M",
"author_id": 89356,
"author_profile": "https://wordpress.stackexchange.com/users/89356",
"pm_score": 5,
"selected": true,
"text": "<p>There are a couple of issues with your approach</p>\n\n<p>By using the <strong>admin_init</strong> hook you won't have any reference to the post object. This means you won't be able to get the post ID or use anything like get_the_ID because the post won't actually be loaded. You can see that in the order here <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference\" rel=\"noreferrer\">https://codex.wordpress.org/Plugin_API/Action_Reference</a></p>\n\n<p>So if you run the action hook after the wp action you'll have the post object. For example</p>\n\n<pre><code>add_action('admin_head', 'remove_content_editor');\n/**\n * Remove the content editor from ALL pages \n */\nfunction remove_content_editor()\n{ \n remove_post_type_support('page', 'editor'); \n}\n</code></pre>\n\n<p>Now this snippet will remove the editor from all pages. The problem is that <strong>is_home</strong> and <strong>is_front_page</strong> won't work on the admin side so you'll need to add some meta data to distinguish whether you're on the home page. There's a very comprehensive discussion of approaches for that on this page: <a href=\"https://wordpress.stackexchange.com/questions/103433/best-way-to-present-options-for-home-page-in-admin\">Best way to present options for home page in admin?</a></p>\n\n<p>So, if you used some extra meta data, you can then check this like</p>\n\n<pre><code>add_action('admin_head', 'remove_content_editor');\n/**\n * Remove the content editor from ALL pages \n */\nfunction remove_content_editor()\n{\n //Check against your meta data here\n if(get_post_meta( get_the_ID(), 'is_home_page' )){ \n remove_post_type_support('page', 'editor'); \n }\n\n}\n</code></pre>\n\n<p>Hopefully that will help you out</p>\n\n<p>******* Update ************</p>\n\n<p>Actually, I've just looked into this again and realised that there is an easier way. If you have set the front page to be a static page in the Reading settings, you can check against the <strong>page_on_front</strong> option value. In that case, the following will work</p>\n\n<pre><code>add_action('admin_head', 'remove_content_editor');\n/**\n * Remove the content editor from pages as all content is handled through Panels\n */\nfunction remove_content_editor()\n{\n if((int) get_option('page_on_front')==get_the_ID())\n {\n remove_post_type_support('page', 'editor');\n }\n}\n</code></pre>\n"
},
{
"answer_id": 305539,
"author": "Nic Bug",
"author_id": 144969,
"author_profile": "https://wordpress.stackexchange.com/users/144969",
"pm_score": 2,
"selected": false,
"text": "<p>thanks for the solution Andrew. I added a code for the page translated by polylang to apply the filter too:</p>\n\n<pre><code>/**\n * Remove the content editor from front page\n */\nfunction remove_content_editor(){\n if((int) get_option('page_on_front')==get_the_ID()){\n remove_post_type_support('page', 'editor');\n }\n if(function_exists(\"pll_get_post\")){\n if((int) pll_get_post(get_the_ID(),\"en\")==get_the_ID()){\n remove_post_type_support('page', 'editor');\n }\n }\n}\nadd_action('admin_head', 'remove_content_editor');\n</code></pre>\n\n<p>Change \"en\" to the matching language string. in my case first language is german and second english (en).</p>\n"
},
{
"answer_id": 344711,
"author": "Mauro Mascia",
"author_id": 44922,
"author_profile": "https://wordpress.stackexchange.com/users/44922",
"pm_score": 3,
"selected": false,
"text": "<p>Update for Wordpress 5 with Gutenberg:</p>\n\n<pre><code><?php\n/**\n * Disable standard editor and Gutenberg for the homepage\n * keeping the status (enabled/disabled) for others who uses the same filter (i.e. ACF)\n */\nadd_filter( 'use_block_editor_for_post', 'yourtheme_hide_editor', 10, 2 );\nfunction yourtheme_hide_editor( $use_block_editor, $post_type ) {\n if ( (int) get_option( 'page_on_front' ) == get_the_ID() ) { // on frontpage\n remove_post_type_support( 'page', 'editor' ); // disable standard editor\n return false; // and disable gutenberg\n }\n\n return $use_block_editor; // keep gutenberg status for other pages/posts \n}\n</code></pre>\n"
}
]
| 2017/07/14 | [
"https://wordpress.stackexchange.com/questions/273394",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/112255/"
]
| I'm trying to make simple about me widget with WordPress media uploader. When I click the button **Upload** it opens media uploader, but after I hit **save**, the button doesn't work anymore, the same behavior if I have one active widget and then I add another, media upload button doesn't work in second widget. No JS errors in console. Can someone point me, where I'm wrong?
**PHP**
```
class Inka_Profile_Widget extends WP_Widget {
// setup the widget name, description etc.
function __construct() {
$widget_options = array(
'classname' => esc_attr( "inka_profile_widget", 'inka' ),
'description' => esc_html__( 'Custom Profile Widget', 'inka' ),
'customize_selective_refresh' => true
);
parent::__construct( 'inka_profile', 'Inka Profile', $widget_options);
}
// back-end display of widget
function form( $instance ) {
$title = ! empty( $instance['title'] ) ? $instance['title'] : esc_html__( 'About Me', 'inka' );
$image = ! empty( $instance['image'] ) ? $instance['image'] : '';
?>
<p>
<label for="<?php echo esc_attr( $this->get_field_id('title') ); ?>"><?php esc_attr_e( 'Title', 'inka' ); ?></label>
<input class="widefat" id="<?php echo esc_attr( $this->get_field_id( 'title' ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( 'title' ) ); ?>" type="text" value="<?php echo esc_attr( $title ); ?>">
</p>
<p>
<img src="<?php echo esc_attr( $image ); ?>" alt="" class="deo-image-holder" style="width: 100%;">
</p>
<p>
<input type="hidden" class="deo-image-hidden-field" name="<?php echo $this->get_field_name( 'image' ); ?>" id="<?php echo $this->get_field_id( 'image' ); ?>" value="<?php echo esc_attr( $image ); ?>"/>
<input type="button" class="deo-image-upload-button button button-primary" value="Upload">
<input type="button" class="deo-image-delete-button button" value="Remove Image">
</p>
<?php
}
// front-end display of widget
function widget( $args, $instance ) {
echo "Hey";
}
// update of the widget
function update( $new_instance, $old_instance ) {
$instance = $old_instance;
$instance['title'] = ( ! empty( $new_instance['title'] ) ) ? strip_tags( $new_instance['title'] ) : '';
$instance['image'] = ( ! empty( $new_instance['image'] ) ) ? strip_tags( $new_instance['image'] ) : '';
return $instance;
}
}
add_action( 'widgets_init', function() {
register_widget( 'Inka_Profile_Widget' );
});
```
**JS**
```
(function($){
/* WordPress Media Uploader
-------------------------------------------------------*/
var addButton = $('.deo-image-upload-button');
var deleteButton = $('.deo-image-delete-button');
var hiddenField = $('.deo-image-hidden-field');
var imageHolder = $('.deo-image-holder');
var mediaUploader;
addButton.on('click', function(e) {
e.preventDefault();
if ( mediaUploader ) {
mediaUploader.open();
return;
}
mediaUploader = wp.media.frames.file_frame = wp.media({
title: 'Select an Image',
button: {
text: 'Use This Image'
},
multiple: false
});
mediaUploader.on('select', function() {
var attachment = mediaUploader.state().get('selection').first().toJSON();
hiddenField.val(attachment.url);
imageHolder.attr('src', attachment.url);
});
mediaUploader.open();
});
})(jQuery);
``` | There are a couple of issues with your approach
By using the **admin\_init** hook you won't have any reference to the post object. This means you won't be able to get the post ID or use anything like get\_the\_ID because the post won't actually be loaded. You can see that in the order here <https://codex.wordpress.org/Plugin_API/Action_Reference>
So if you run the action hook after the wp action you'll have the post object. For example
```
add_action('admin_head', 'remove_content_editor');
/**
* Remove the content editor from ALL pages
*/
function remove_content_editor()
{
remove_post_type_support('page', 'editor');
}
```
Now this snippet will remove the editor from all pages. The problem is that **is\_home** and **is\_front\_page** won't work on the admin side so you'll need to add some meta data to distinguish whether you're on the home page. There's a very comprehensive discussion of approaches for that on this page: [Best way to present options for home page in admin?](https://wordpress.stackexchange.com/questions/103433/best-way-to-present-options-for-home-page-in-admin)
So, if you used some extra meta data, you can then check this like
```
add_action('admin_head', 'remove_content_editor');
/**
* Remove the content editor from ALL pages
*/
function remove_content_editor()
{
//Check against your meta data here
if(get_post_meta( get_the_ID(), 'is_home_page' )){
remove_post_type_support('page', 'editor');
}
}
```
Hopefully that will help you out
\*\*\*\*\*\*\* Update \*\*\*\*\*\*\*\*\*\*\*\*
Actually, I've just looked into this again and realised that there is an easier way. If you have set the front page to be a static page in the Reading settings, you can check against the **page\_on\_front** option value. In that case, the following will work
```
add_action('admin_head', 'remove_content_editor');
/**
* Remove the content editor from pages as all content is handled through Panels
*/
function remove_content_editor()
{
if((int) get_option('page_on_front')==get_the_ID())
{
remove_post_type_support('page', 'editor');
}
}
``` |
273,403 | <p>I've been pulling my hair over this strange issue for several hours now and need some help figuring out what's going on. Allow me to explain my setup followed by the behavior and question.</p>
<p>Setup:</p>
<ol>
<li><p>I've set my 'posts page' to domain.com/search/ where I intend to list all my posts. </p></li>
<li><p>Since I need a custom layout for displaying my posts, I've the following redirect in 'template_include' hook:</p>
<pre><code>/*Use custom template to render posts on /search/ */
if ( is_home() ) {
return plugin_dir_path( __FILE__ ) . 'partials/display-speaker-list.php';
}
</code></pre></li>
<li><p>My posts list also displays tags associated with each post. I want these tags to be clickable. When user clicks on any tag, I want to filter the posts using the clicked tag as keyword. The HTML for my displaying tags for each post looks like this:</p>
<pre><code> <a href="<?php echo esc_url( home_url('/') . 'search/?tag=' . str_replace(' ', '+', $topic ) ); ?>" class="btn btn-outline-primary" role="button"><?php echo esc_html( $topic ); ?></a>
</code></pre></li>
</ol>
<p>In order to make the search work, I decided to make use of 'pre_get_posts' hook. This is where the strange things began to happen. Look at the code I execute with <code>pre_get_posts</code> : </p>
<pre><code>/* Filter posts using the tag
public function io_speakers_pre_get_posts( $query ) {
if ( $query->is_main_query() && $query->is_home() ) {
$query->set('tag', $_GET['tag']);
return $query;
}
return $query;
}
</code></pre>
<p>Here's the Odd behavior:</p>
<p>If I remove the <code>$query->set('query_var', 'value');</code> statement from the condition, WordPress returns all posts, completely ignoring the <code>search/?tag=xyz</code> query. But it works even if I set it to something random or even empty. That is, WordPress correctly filters the posts if I change that line to <code>$query->set('', '');</code> </p>
<p>In short, WordPress expects me to have a <code>$query->set(WHATEVER);</code> in that condition for it to acknowledge existence of 'tag' parameter. Otherwise it just returns all the posts. </p>
<p>My questions are: </p>
<ol>
<li>What's really happening with <code>$query->set()</code>? </li>
<li>Why does it require me to set any random stuff in <code>$query->(blah, blah)</code> in order to work properly?</li>
<li>What if I want to search by <code>/search/?topic=someTopic</code> instead of <code>/search/?tag=someTopic</code>? </li>
</ol>
<p>I hope I've explained my question properly. It's a pretty long explanation and I look forward to your help. Would really appreciate it. Thank you in advance for your time.</p>
<p>-K</p>
| [
{
"answer_id": 273371,
"author": "Andrew M",
"author_id": 89356,
"author_profile": "https://wordpress.stackexchange.com/users/89356",
"pm_score": 5,
"selected": true,
"text": "<p>There are a couple of issues with your approach</p>\n\n<p>By using the <strong>admin_init</strong> hook you won't have any reference to the post object. This means you won't be able to get the post ID or use anything like get_the_ID because the post won't actually be loaded. You can see that in the order here <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference\" rel=\"noreferrer\">https://codex.wordpress.org/Plugin_API/Action_Reference</a></p>\n\n<p>So if you run the action hook after the wp action you'll have the post object. For example</p>\n\n<pre><code>add_action('admin_head', 'remove_content_editor');\n/**\n * Remove the content editor from ALL pages \n */\nfunction remove_content_editor()\n{ \n remove_post_type_support('page', 'editor'); \n}\n</code></pre>\n\n<p>Now this snippet will remove the editor from all pages. The problem is that <strong>is_home</strong> and <strong>is_front_page</strong> won't work on the admin side so you'll need to add some meta data to distinguish whether you're on the home page. There's a very comprehensive discussion of approaches for that on this page: <a href=\"https://wordpress.stackexchange.com/questions/103433/best-way-to-present-options-for-home-page-in-admin\">Best way to present options for home page in admin?</a></p>\n\n<p>So, if you used some extra meta data, you can then check this like</p>\n\n<pre><code>add_action('admin_head', 'remove_content_editor');\n/**\n * Remove the content editor from ALL pages \n */\nfunction remove_content_editor()\n{\n //Check against your meta data here\n if(get_post_meta( get_the_ID(), 'is_home_page' )){ \n remove_post_type_support('page', 'editor'); \n }\n\n}\n</code></pre>\n\n<p>Hopefully that will help you out</p>\n\n<p>******* Update ************</p>\n\n<p>Actually, I've just looked into this again and realised that there is an easier way. If you have set the front page to be a static page in the Reading settings, you can check against the <strong>page_on_front</strong> option value. In that case, the following will work</p>\n\n<pre><code>add_action('admin_head', 'remove_content_editor');\n/**\n * Remove the content editor from pages as all content is handled through Panels\n */\nfunction remove_content_editor()\n{\n if((int) get_option('page_on_front')==get_the_ID())\n {\n remove_post_type_support('page', 'editor');\n }\n}\n</code></pre>\n"
},
{
"answer_id": 305539,
"author": "Nic Bug",
"author_id": 144969,
"author_profile": "https://wordpress.stackexchange.com/users/144969",
"pm_score": 2,
"selected": false,
"text": "<p>thanks for the solution Andrew. I added a code for the page translated by polylang to apply the filter too:</p>\n\n<pre><code>/**\n * Remove the content editor from front page\n */\nfunction remove_content_editor(){\n if((int) get_option('page_on_front')==get_the_ID()){\n remove_post_type_support('page', 'editor');\n }\n if(function_exists(\"pll_get_post\")){\n if((int) pll_get_post(get_the_ID(),\"en\")==get_the_ID()){\n remove_post_type_support('page', 'editor');\n }\n }\n}\nadd_action('admin_head', 'remove_content_editor');\n</code></pre>\n\n<p>Change \"en\" to the matching language string. in my case first language is german and second english (en).</p>\n"
},
{
"answer_id": 344711,
"author": "Mauro Mascia",
"author_id": 44922,
"author_profile": "https://wordpress.stackexchange.com/users/44922",
"pm_score": 3,
"selected": false,
"text": "<p>Update for Wordpress 5 with Gutenberg:</p>\n\n<pre><code><?php\n/**\n * Disable standard editor and Gutenberg for the homepage\n * keeping the status (enabled/disabled) for others who uses the same filter (i.e. ACF)\n */\nadd_filter( 'use_block_editor_for_post', 'yourtheme_hide_editor', 10, 2 );\nfunction yourtheme_hide_editor( $use_block_editor, $post_type ) {\n if ( (int) get_option( 'page_on_front' ) == get_the_ID() ) { // on frontpage\n remove_post_type_support( 'page', 'editor' ); // disable standard editor\n return false; // and disable gutenberg\n }\n\n return $use_block_editor; // keep gutenberg status for other pages/posts \n}\n</code></pre>\n"
}
]
| 2017/07/14 | [
"https://wordpress.stackexchange.com/questions/273403",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/21100/"
]
| I've been pulling my hair over this strange issue for several hours now and need some help figuring out what's going on. Allow me to explain my setup followed by the behavior and question.
Setup:
1. I've set my 'posts page' to domain.com/search/ where I intend to list all my posts.
2. Since I need a custom layout for displaying my posts, I've the following redirect in 'template\_include' hook:
```
/*Use custom template to render posts on /search/ */
if ( is_home() ) {
return plugin_dir_path( __FILE__ ) . 'partials/display-speaker-list.php';
}
```
3. My posts list also displays tags associated with each post. I want these tags to be clickable. When user clicks on any tag, I want to filter the posts using the clicked tag as keyword. The HTML for my displaying tags for each post looks like this:
```
<a href="<?php echo esc_url( home_url('/') . 'search/?tag=' . str_replace(' ', '+', $topic ) ); ?>" class="btn btn-outline-primary" role="button"><?php echo esc_html( $topic ); ?></a>
```
In order to make the search work, I decided to make use of 'pre\_get\_posts' hook. This is where the strange things began to happen. Look at the code I execute with `pre_get_posts` :
```
/* Filter posts using the tag
public function io_speakers_pre_get_posts( $query ) {
if ( $query->is_main_query() && $query->is_home() ) {
$query->set('tag', $_GET['tag']);
return $query;
}
return $query;
}
```
Here's the Odd behavior:
If I remove the `$query->set('query_var', 'value');` statement from the condition, WordPress returns all posts, completely ignoring the `search/?tag=xyz` query. But it works even if I set it to something random or even empty. That is, WordPress correctly filters the posts if I change that line to `$query->set('', '');`
In short, WordPress expects me to have a `$query->set(WHATEVER);` in that condition for it to acknowledge existence of 'tag' parameter. Otherwise it just returns all the posts.
My questions are:
1. What's really happening with `$query->set()`?
2. Why does it require me to set any random stuff in `$query->(blah, blah)` in order to work properly?
3. What if I want to search by `/search/?topic=someTopic` instead of `/search/?tag=someTopic`?
I hope I've explained my question properly. It's a pretty long explanation and I look forward to your help. Would really appreciate it. Thank you in advance for your time.
-K | There are a couple of issues with your approach
By using the **admin\_init** hook you won't have any reference to the post object. This means you won't be able to get the post ID or use anything like get\_the\_ID because the post won't actually be loaded. You can see that in the order here <https://codex.wordpress.org/Plugin_API/Action_Reference>
So if you run the action hook after the wp action you'll have the post object. For example
```
add_action('admin_head', 'remove_content_editor');
/**
* Remove the content editor from ALL pages
*/
function remove_content_editor()
{
remove_post_type_support('page', 'editor');
}
```
Now this snippet will remove the editor from all pages. The problem is that **is\_home** and **is\_front\_page** won't work on the admin side so you'll need to add some meta data to distinguish whether you're on the home page. There's a very comprehensive discussion of approaches for that on this page: [Best way to present options for home page in admin?](https://wordpress.stackexchange.com/questions/103433/best-way-to-present-options-for-home-page-in-admin)
So, if you used some extra meta data, you can then check this like
```
add_action('admin_head', 'remove_content_editor');
/**
* Remove the content editor from ALL pages
*/
function remove_content_editor()
{
//Check against your meta data here
if(get_post_meta( get_the_ID(), 'is_home_page' )){
remove_post_type_support('page', 'editor');
}
}
```
Hopefully that will help you out
\*\*\*\*\*\*\* Update \*\*\*\*\*\*\*\*\*\*\*\*
Actually, I've just looked into this again and realised that there is an easier way. If you have set the front page to be a static page in the Reading settings, you can check against the **page\_on\_front** option value. In that case, the following will work
```
add_action('admin_head', 'remove_content_editor');
/**
* Remove the content editor from pages as all content is handled through Panels
*/
function remove_content_editor()
{
if((int) get_option('page_on_front')==get_the_ID())
{
remove_post_type_support('page', 'editor');
}
}
``` |
273,419 | <p>The following bit of code was used in my fictitious plugin to redirect the non-logged-in users from page <code>173</code> (ID) to <code>sample-page</code> (slug). The code's working well. But just today, I figured out that the code is causing Notices <del>in Firefox</del>.</p>
<p>The issue happened when I tried setting a Static Page as the front page from Settings » Reading.</p>
<blockquote>
<p><strong>Notice:</strong> Trying to get property of non-object in
<code>/wp-includes/class-wp-query.php</code> on line 3760
<strong>Notice:</strong> Trying to get property of non-object in
<code>/wp-includes/class-wp-query.php</code> on line 3762
<strong>Notice:</strong> Trying to get property of non-object in
<code>/wp-includes/class-wp-query.php</code> on line 3764</p>
</blockquote>
<p>With several inspection, I figured out that, the following bit of code is causing the issue. And to be specific the issue is with the <code>is_page(173)</code>.</p>
<pre><code>add_action('pre_get_posts', function($query) {
if( $query->is_main_query() && ! is_admin() && ! is_user_logged_in() && $query->is_page(173) ) {
wp_redirect(home_url('/sample-page'));
exit();
}
});
</code></pre>
<p>I tried changing from <code>$query->is_page(173)</code> to <code>is_page(173)</code> - the result is same.</p>
<p>To test in a blank installation, I tried disabling all the plugins and set the default theme TwentySixteen, and re-installed WordPress to get a fresh install. I put the following code in TwentySixteen's <code>functions.php</code>, and with DEBUG <em>on</em>, <a href="http://dev.nanodesignsbd.com/" rel="nofollow noreferrer">here's what I got</a>. (The notice is under the black area of header, just hit <kbd>Ctrl</kbd> + <kbd>A</kbd> to see 'em) <del>You can check the redirection is working from <a href="http://dev.nanodesignsbd.com/level-2/" rel="nofollow noreferrer">this page</a> (<code>173</code>) to <a href="http://dev.nanodesignsbd.com/sample-page/" rel="nofollow noreferrer">this page</a> without any notice.</del></p>
<p>What's the problem with my code?</p>
| [
{
"answer_id": 344086,
"author": "Tom",
"author_id": 172789,
"author_profile": "https://wordpress.stackexchange.com/users/172789",
"pm_score": 0,
"selected": false,
"text": "<p>Turn off debug mode and it will be gone, at least worked for me. \nI know it's an old post but just want to help people with the same issue.</p>\n"
},
{
"answer_id": 378219,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 1,
"selected": false,
"text": "<p><code>pre_get_posts</code> is innapropriate for this use, instead you should use the <code>template_redirect</code> filter, e.g.</p>\n<pre class=\"lang-php prettyprint-override\"><code>add_action( 'template_redirect', funnction() {\n if ( ! is_user_logged_in() && is_page( 123 ) ) {\n wp_safe_redirect( home_url( '/sample-page' ) );\n exit;\n }\n} );\n</code></pre>\n"
}
]
| 2017/07/14 | [
"https://wordpress.stackexchange.com/questions/273419",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/22728/"
]
| The following bit of code was used in my fictitious plugin to redirect the non-logged-in users from page `173` (ID) to `sample-page` (slug). The code's working well. But just today, I figured out that the code is causing Notices ~~in Firefox~~.
The issue happened when I tried setting a Static Page as the front page from Settings » Reading.
>
> **Notice:** Trying to get property of non-object in
> `/wp-includes/class-wp-query.php` on line 3760
> **Notice:** Trying to get property of non-object in
> `/wp-includes/class-wp-query.php` on line 3762
> **Notice:** Trying to get property of non-object in
> `/wp-includes/class-wp-query.php` on line 3764
>
>
>
With several inspection, I figured out that, the following bit of code is causing the issue. And to be specific the issue is with the `is_page(173)`.
```
add_action('pre_get_posts', function($query) {
if( $query->is_main_query() && ! is_admin() && ! is_user_logged_in() && $query->is_page(173) ) {
wp_redirect(home_url('/sample-page'));
exit();
}
});
```
I tried changing from `$query->is_page(173)` to `is_page(173)` - the result is same.
To test in a blank installation, I tried disabling all the plugins and set the default theme TwentySixteen, and re-installed WordPress to get a fresh install. I put the following code in TwentySixteen's `functions.php`, and with DEBUG *on*, [here's what I got](http://dev.nanodesignsbd.com/). (The notice is under the black area of header, just hit `Ctrl` + `A` to see 'em) ~~You can check the redirection is working from [this page](http://dev.nanodesignsbd.com/level-2/) (`173`) to [this page](http://dev.nanodesignsbd.com/sample-page/) without any notice.~~
What's the problem with my code? | `pre_get_posts` is innapropriate for this use, instead you should use the `template_redirect` filter, e.g.
```php
add_action( 'template_redirect', funnction() {
if ( ! is_user_logged_in() && is_page( 123 ) ) {
wp_safe_redirect( home_url( '/sample-page' ) );
exit;
}
} );
``` |
273,438 | <p>I want to show random posts from a custom post type in my page. For example, I have 10 posts, but I want to show 5 post in page which will change randomly.</p>
<p>How can I do this?</p>
<p>Regards.</p>
| [
{
"answer_id": 273439,
"author": "Rick Hellewell",
"author_id": 29416,
"author_profile": "https://wordpress.stackexchange.com/users/29416",
"pm_score": 0,
"selected": false,
"text": "<p>A quick 'googles' turns up several possibilities (the googles are your friend to get answers for most questions).</p>\n\n<p>There is this article <a href=\"http://www.wpbeginner.com/wp-tutorials/how-to-redirect-users-to-a-random-post-in-wordpress/\" rel=\"nofollow noreferrer\">http://www.wpbeginner.com/wp-tutorials/how-to-redirect-users-to-a-random-post-in-wordpress/</a> . </p>\n\n<p>Plus there are various plugins that will do similar.</p>\n\n<p>I found lots of answers with a quick googles of 'wordpress random posts'. </p>\n"
},
{
"answer_id": 273440,
"author": "Johansson",
"author_id": 94498,
"author_profile": "https://wordpress.stackexchange.com/users/94498",
"pm_score": 2,
"selected": false,
"text": "<p>You can write a custom query to get some random posts for your template. The simplest possible solution will be this query:</p>\n\n<pre><code><?php\n// Set the post type here, and sort them randomly\n$args = array(\n 'post_type' => 'YOUR-POST-TYPE',\n 'posts_per_page'=> 5, \n 'order_by' => 'rand',\n);\n// Initiate a custom query\n$my_query = new WP_Query($args);\n// If the query has any post, start the loop\nif($my_query->have_posts()){\n while($my_query->have_posts()){\n // Output a link and a thumbnail of the post\n $my_query->the_post(); ?>\n <div class=\"random-post\">\n <img src=\"<?php the_post_thumbnail_url();?>\"/>\n <a href=\"<?php the_permalink();?>\"><?php the_title();?></a>\n </div><?php\n }\n} ?>\n</code></pre>\n\n<p>Replace <code>YOUR-POST-TYPE</code> with your actual post type's name, then paste this code wherever you wish in your template. You can add or remove any element that you wish, if you are familiar with WordPress's functions.</p>\n"
}
]
| 2017/07/14 | [
"https://wordpress.stackexchange.com/questions/273438",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/123903/"
]
| I want to show random posts from a custom post type in my page. For example, I have 10 posts, but I want to show 5 post in page which will change randomly.
How can I do this?
Regards. | You can write a custom query to get some random posts for your template. The simplest possible solution will be this query:
```
<?php
// Set the post type here, and sort them randomly
$args = array(
'post_type' => 'YOUR-POST-TYPE',
'posts_per_page'=> 5,
'order_by' => 'rand',
);
// Initiate a custom query
$my_query = new WP_Query($args);
// If the query has any post, start the loop
if($my_query->have_posts()){
while($my_query->have_posts()){
// Output a link and a thumbnail of the post
$my_query->the_post(); ?>
<div class="random-post">
<img src="<?php the_post_thumbnail_url();?>"/>
<a href="<?php the_permalink();?>"><?php the_title();?></a>
</div><?php
}
} ?>
```
Replace `YOUR-POST-TYPE` with your actual post type's name, then paste this code wherever you wish in your template. You can add or remove any element that you wish, if you are familiar with WordPress's functions. |
273,442 | <p>I will post the entire plugin code below.. here is the problem that I am having with it. I am using the values that are imported to custom fields in a custom post type to construct the URLs. On the edit post page it shows the permalink as I wish it to be..</p>
<blockquote>
<p>site.com/real-estate/%postname%-%field_City%-%field_State%-%field_Zip_Code%/</p>
</blockquote>
<p>as</p>
<blockquote>
<p>site.com/real-estate/51-main-st-<strong>port-jefferson</strong>-ny-11777/</p>
</blockquote>
<p>The permalink however is 404.. although if I remove the hyphens in the city name and search..</p>
<blockquote>
<p>site.com/real-estate/51-main-st-<strong>portjefferson</strong>-ny-11777/</p>
</blockquote>
<p>than the url works..</p>
<p>So I imagine the plugin is missing something with respects to fields with spaces.. strange that it shows properly in the permalink field within the post editor though.. any help will be much appreciated..</p>
<pre><code> <?php
/*
Plugin Name: Custom Fields Permalink 2
Plugin URI: http://athlan.pl/wordpress-custom-fields-permalink-plugin
Description: Plugin allows to use post's custom fields values in permalink structure by adding %field_fieldname%, for posts, pages and custom post types.
Author: Piotr Pelczar
Version: 2.0
Author URI: http://athlan.pl/
*/
class CustomFieldsPermalink {
const PARAM_CUSTOMFIELD_KEY = 'custom_field_key';
const PARAM_CUSTOMFIELD_VALUE = 'custom_field_value';
public static $checkCustomFieldValue = false;
public static function linkPost($permalink, $post, $leavename) {
return self::linkRewriteFields($permalink, $post);
}
public static function linkPostType($permalink, $post, $leavename, $sample) {
return self::linkRewriteFields($permalink, $post);
}
protected static function linkRewriteFields($permalink, $post) {
$replaceCallback = function($matches) use (&$post) {
return CustomFieldsPermalink::linkRewriteFieldsExtract($post, $matches[2]);
};
return preg_replace_callback('#(%field_(.*?)%)#', $replaceCallback, $permalink);
}
public static function linkRewriteFieldsExtract($post, $fieldName) {
$postMeta = get_post_meta($post->ID);
if(!isset($postMeta[$fieldName]))
return '';
$value = implode('', $postMeta[$fieldName]);
$value = sanitize_title($value);
return $value;
}
public static function registerExtraQueryVars($value) {
array_push($value, self::PARAM_CUSTOMFIELD_KEY, self::PARAM_CUSTOMFIELD_VALUE);
return $value;
}
public static function processRequest($value) {
// additional parameters added to Wordpress
// Main Loop query
if(array_key_exists(self::PARAM_CUSTOMFIELD_KEY, $value)) {
$value['meta_key'] = $value[self::PARAM_CUSTOMFIELD_KEY];
// remove temporary injected parameter
unset($value[self::PARAM_CUSTOMFIELD_KEY]);
// do not check field's value for this moment
if(true === self::$checkCustomFieldValue) {
if(array_key_exists(self::PARAM_CUSTOMFIELD_VALUE, $value)) {
$value['meta_value'] = $value[self::PARAM_CUSTOMFIELD_VALUE];
// remove temporary injected parameter
unset($value[self::PARAM_CUSTOMFIELD_VALUE]);
}
}
}
return $value;
}
public static function rewriteRulesArrayFilter($rules) {
$keys = array_keys($rules);
$tmp = $rules;
$rules = array();
for($i = 0, $j = sizeof($keys); $i < $j; ++$i) {
$key = $keys[$i];
if (preg_match('/%field_([^%]*?)%/', $key)) {
$keyNew = preg_replace(
'/%field_([^%]*?)%/',
'([^/]+)',
// you can simply add next group to the url, because WordPress
// detect them automatically and add next $matches indiceis
$key
);
$rules[$keyNew] = preg_replace(
'/%field_([^%]*?)%/',
sprintf('%s=$1&%s=', self::PARAM_CUSTOMFIELD_KEY, self::PARAM_CUSTOMFIELD_VALUE),
// here on the end will be pasted $matches[$i] from $keyNew, so we can
// grab it it the future in self::PARAM_CUSTOMFIELD_VALUE parameter
$tmp[$key]
);
}
else {
$rules[$key] = $tmp[$key];
}
}
return $rules;
}
}
add_filter('pre_post_link', array('CustomFieldsPermalink', 'linkPost'), 100, 3);
add_filter('post_type_link', array('CustomFieldsPermalink', 'linkPostType'), 100, 4);
add_filter('rewrite_rules_array', array('CustomFieldsPermalink', 'rewriteRulesArrayFilter'));
add_filter('query_vars', array('CustomFieldsPermalink', 'registerExtraQueryVars'), 10, 1);
add_filter('request', array('CustomFieldsPermalink', 'processRequest'), 10, 1);
</code></pre>
<p>I THOUGHT I FIGURED OUT A SOLUTION.. BUT...
I thought that using the hex code for hyphen (%2D) in permalink settings was a solution.. but it turns out this only works in the chrome browser.. not in IE or Edge.. so I am still without a solution unfortunately :(</p>
| [
{
"answer_id": 273439,
"author": "Rick Hellewell",
"author_id": 29416,
"author_profile": "https://wordpress.stackexchange.com/users/29416",
"pm_score": 0,
"selected": false,
"text": "<p>A quick 'googles' turns up several possibilities (the googles are your friend to get answers for most questions).</p>\n\n<p>There is this article <a href=\"http://www.wpbeginner.com/wp-tutorials/how-to-redirect-users-to-a-random-post-in-wordpress/\" rel=\"nofollow noreferrer\">http://www.wpbeginner.com/wp-tutorials/how-to-redirect-users-to-a-random-post-in-wordpress/</a> . </p>\n\n<p>Plus there are various plugins that will do similar.</p>\n\n<p>I found lots of answers with a quick googles of 'wordpress random posts'. </p>\n"
},
{
"answer_id": 273440,
"author": "Johansson",
"author_id": 94498,
"author_profile": "https://wordpress.stackexchange.com/users/94498",
"pm_score": 2,
"selected": false,
"text": "<p>You can write a custom query to get some random posts for your template. The simplest possible solution will be this query:</p>\n\n<pre><code><?php\n// Set the post type here, and sort them randomly\n$args = array(\n 'post_type' => 'YOUR-POST-TYPE',\n 'posts_per_page'=> 5, \n 'order_by' => 'rand',\n);\n// Initiate a custom query\n$my_query = new WP_Query($args);\n// If the query has any post, start the loop\nif($my_query->have_posts()){\n while($my_query->have_posts()){\n // Output a link and a thumbnail of the post\n $my_query->the_post(); ?>\n <div class=\"random-post\">\n <img src=\"<?php the_post_thumbnail_url();?>\"/>\n <a href=\"<?php the_permalink();?>\"><?php the_title();?></a>\n </div><?php\n }\n} ?>\n</code></pre>\n\n<p>Replace <code>YOUR-POST-TYPE</code> with your actual post type's name, then paste this code wherever you wish in your template. You can add or remove any element that you wish, if you are familiar with WordPress's functions.</p>\n"
}
]
| 2017/07/14 | [
"https://wordpress.stackexchange.com/questions/273442",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/123857/"
]
| I will post the entire plugin code below.. here is the problem that I am having with it. I am using the values that are imported to custom fields in a custom post type to construct the URLs. On the edit post page it shows the permalink as I wish it to be..
>
> site.com/real-estate/%postname%-%field\_City%-%field\_State%-%field\_Zip\_Code%/
>
>
>
as
>
> site.com/real-estate/51-main-st-**port-jefferson**-ny-11777/
>
>
>
The permalink however is 404.. although if I remove the hyphens in the city name and search..
>
> site.com/real-estate/51-main-st-**portjefferson**-ny-11777/
>
>
>
than the url works..
So I imagine the plugin is missing something with respects to fields with spaces.. strange that it shows properly in the permalink field within the post editor though.. any help will be much appreciated..
```
<?php
/*
Plugin Name: Custom Fields Permalink 2
Plugin URI: http://athlan.pl/wordpress-custom-fields-permalink-plugin
Description: Plugin allows to use post's custom fields values in permalink structure by adding %field_fieldname%, for posts, pages and custom post types.
Author: Piotr Pelczar
Version: 2.0
Author URI: http://athlan.pl/
*/
class CustomFieldsPermalink {
const PARAM_CUSTOMFIELD_KEY = 'custom_field_key';
const PARAM_CUSTOMFIELD_VALUE = 'custom_field_value';
public static $checkCustomFieldValue = false;
public static function linkPost($permalink, $post, $leavename) {
return self::linkRewriteFields($permalink, $post);
}
public static function linkPostType($permalink, $post, $leavename, $sample) {
return self::linkRewriteFields($permalink, $post);
}
protected static function linkRewriteFields($permalink, $post) {
$replaceCallback = function($matches) use (&$post) {
return CustomFieldsPermalink::linkRewriteFieldsExtract($post, $matches[2]);
};
return preg_replace_callback('#(%field_(.*?)%)#', $replaceCallback, $permalink);
}
public static function linkRewriteFieldsExtract($post, $fieldName) {
$postMeta = get_post_meta($post->ID);
if(!isset($postMeta[$fieldName]))
return '';
$value = implode('', $postMeta[$fieldName]);
$value = sanitize_title($value);
return $value;
}
public static function registerExtraQueryVars($value) {
array_push($value, self::PARAM_CUSTOMFIELD_KEY, self::PARAM_CUSTOMFIELD_VALUE);
return $value;
}
public static function processRequest($value) {
// additional parameters added to Wordpress
// Main Loop query
if(array_key_exists(self::PARAM_CUSTOMFIELD_KEY, $value)) {
$value['meta_key'] = $value[self::PARAM_CUSTOMFIELD_KEY];
// remove temporary injected parameter
unset($value[self::PARAM_CUSTOMFIELD_KEY]);
// do not check field's value for this moment
if(true === self::$checkCustomFieldValue) {
if(array_key_exists(self::PARAM_CUSTOMFIELD_VALUE, $value)) {
$value['meta_value'] = $value[self::PARAM_CUSTOMFIELD_VALUE];
// remove temporary injected parameter
unset($value[self::PARAM_CUSTOMFIELD_VALUE]);
}
}
}
return $value;
}
public static function rewriteRulesArrayFilter($rules) {
$keys = array_keys($rules);
$tmp = $rules;
$rules = array();
for($i = 0, $j = sizeof($keys); $i < $j; ++$i) {
$key = $keys[$i];
if (preg_match('/%field_([^%]*?)%/', $key)) {
$keyNew = preg_replace(
'/%field_([^%]*?)%/',
'([^/]+)',
// you can simply add next group to the url, because WordPress
// detect them automatically and add next $matches indiceis
$key
);
$rules[$keyNew] = preg_replace(
'/%field_([^%]*?)%/',
sprintf('%s=$1&%s=', self::PARAM_CUSTOMFIELD_KEY, self::PARAM_CUSTOMFIELD_VALUE),
// here on the end will be pasted $matches[$i] from $keyNew, so we can
// grab it it the future in self::PARAM_CUSTOMFIELD_VALUE parameter
$tmp[$key]
);
}
else {
$rules[$key] = $tmp[$key];
}
}
return $rules;
}
}
add_filter('pre_post_link', array('CustomFieldsPermalink', 'linkPost'), 100, 3);
add_filter('post_type_link', array('CustomFieldsPermalink', 'linkPostType'), 100, 4);
add_filter('rewrite_rules_array', array('CustomFieldsPermalink', 'rewriteRulesArrayFilter'));
add_filter('query_vars', array('CustomFieldsPermalink', 'registerExtraQueryVars'), 10, 1);
add_filter('request', array('CustomFieldsPermalink', 'processRequest'), 10, 1);
```
I THOUGHT I FIGURED OUT A SOLUTION.. BUT...
I thought that using the hex code for hyphen (%2D) in permalink settings was a solution.. but it turns out this only works in the chrome browser.. not in IE or Edge.. so I am still without a solution unfortunately :( | You can write a custom query to get some random posts for your template. The simplest possible solution will be this query:
```
<?php
// Set the post type here, and sort them randomly
$args = array(
'post_type' => 'YOUR-POST-TYPE',
'posts_per_page'=> 5,
'order_by' => 'rand',
);
// Initiate a custom query
$my_query = new WP_Query($args);
// If the query has any post, start the loop
if($my_query->have_posts()){
while($my_query->have_posts()){
// Output a link and a thumbnail of the post
$my_query->the_post(); ?>
<div class="random-post">
<img src="<?php the_post_thumbnail_url();?>"/>
<a href="<?php the_permalink();?>"><?php the_title();?></a>
</div><?php
}
} ?>
```
Replace `YOUR-POST-TYPE` with your actual post type's name, then paste this code wherever you wish in your template. You can add or remove any element that you wish, if you are familiar with WordPress's functions. |
273,459 | <p>In the navigation menu creation page, when you are trying to add a category to the menu, if the category is empty, it won't show up in the search results. However, if the category itself is empty but has a child that is not empty, it will still be shown.</p>
<p>I have a blog with over 500 categories, and I'm trying to add some of them to the menu but they have no posts yet. Navigating through category list is going to take time, and is also frustrating.</p>
<p>Now I've tracked down the issue to <code>/wp-admin/includes/nav-menu.php</code>, ( starting at line 588 ) but can't find a filter or hook to do so.</p>
<p>This line (109) seems to be responsible for doing the search:</p>
<pre><code>$terms = get_terms( $matches[2], array(
'name__like' => $query,
'number' => 10,
));
</code></pre>
<p>According to the <a href="https://developer.wordpress.org/reference/functions/get_terms/" rel="nofollow noreferrer">documentations</a>, this function accepts an argument for showing empty terms <code>'hide_empty' => false</code>, but I can't see such option in this part of core's code. I've added this option to the core (temporarily) to see if it solves the issue, and it does.</p>
<p>Can this be a bug? And is it possible to enable the search to return the result no matter the category has a post or not?</p>
| [
{
"answer_id": 273812,
"author": "Worduoso",
"author_id": 101425,
"author_profile": "https://wordpress.stackexchange.com/users/101425",
"pm_score": 2,
"selected": true,
"text": "<p>You can modify this behaviour by adding a custom filter to your functions.php or as a plugin:</p>\n\n<pre><code>add_filter('get_terms_args', 'wodruoso_terms_args', 10, 1); \nfunction wodruoso_terms_args($args) {\n /* note: I am checking here that we are in WP Admin area and that it's\n * search by category name to minimize impact on other areas\n */\n if(is_admin() && isset($args[\"name__like\"]) && !empty($args[\"name__like\"])) {\n $args[\"hide_empty\"] = false;\n }\n return $args;\n}\n</code></pre>\n"
},
{
"answer_id": 273827,
"author": "Johansson",
"author_id": 94498,
"author_profile": "https://wordpress.stackexchange.com/users/94498",
"pm_score": 0,
"selected": false,
"text": "<p>The posted answer does temporarily resolve the issue, but only while doing a quick search using AJAX.</p>\n\n<p>I've created and uploaded a patch on trac <a href=\"https://core.trac.wordpress.org/ticket/41351\" rel=\"nofollow noreferrer\">here</a>. This patch fully resolves the issue, while allowing the user to exclude/include empty taxonomies from search results.</p>\n\n<p>Feedbacks from anyone is appreciated.</p>\n"
}
]
| 2017/07/15 | [
"https://wordpress.stackexchange.com/questions/273459",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/94498/"
]
| In the navigation menu creation page, when you are trying to add a category to the menu, if the category is empty, it won't show up in the search results. However, if the category itself is empty but has a child that is not empty, it will still be shown.
I have a blog with over 500 categories, and I'm trying to add some of them to the menu but they have no posts yet. Navigating through category list is going to take time, and is also frustrating.
Now I've tracked down the issue to `/wp-admin/includes/nav-menu.php`, ( starting at line 588 ) but can't find a filter or hook to do so.
This line (109) seems to be responsible for doing the search:
```
$terms = get_terms( $matches[2], array(
'name__like' => $query,
'number' => 10,
));
```
According to the [documentations](https://developer.wordpress.org/reference/functions/get_terms/), this function accepts an argument for showing empty terms `'hide_empty' => false`, but I can't see such option in this part of core's code. I've added this option to the core (temporarily) to see if it solves the issue, and it does.
Can this be a bug? And is it possible to enable the search to return the result no matter the category has a post or not? | You can modify this behaviour by adding a custom filter to your functions.php or as a plugin:
```
add_filter('get_terms_args', 'wodruoso_terms_args', 10, 1);
function wodruoso_terms_args($args) {
/* note: I am checking here that we are in WP Admin area and that it's
* search by category name to minimize impact on other areas
*/
if(is_admin() && isset($args["name__like"]) && !empty($args["name__like"])) {
$args["hide_empty"] = false;
}
return $args;
}
``` |
273,500 | <p>I have just followed <a href="http://www.wpbeginner.com/wp-tutorials/how-to-move-live-wordpress-site-to-local-server/" rel="nofollow noreferrer">this guide</a> on manually migrating a WordPress site to localhost.</p>
<p>I have followed all of the steps: downloading files using FTP, exporting database, importing to localhost database, changing URL links to localhost and finally updating wp-config.</p>
<p>I tried this on two of my sites and came across different problems:</p>
<ol>
<li>Safari cannot connect to the server' error message</li>
<li>The following text displayed on the screen:</li>
</ol>
<blockquote>
<p>"Front to the WordPress application. This file doesn't do anything,
but loads wp-blog-header.php which does and tells WordPress to load
the theme.</p>
</blockquote>
<pre><code> *
@package WordPress */
/** * Tells WordPress to load the WordPress theme and output it.
* * @var bool */
define('WP_USE_THEMES', true);
/** Loads the WordPress Environment and Template */
require( dirname( FILE ) . '/wp-blog-header.php' );"
</code></pre>
<p>Can anyone advise as to how I can make my website display?</p>
| [
{
"answer_id": 273496,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 1,
"selected": false,
"text": "<p>You can't find it because it doesn't exist. There is no page at that location.</p>\n\n<p>In WordPress everything is either an archive of posts or a post of some type. Pages are posts of type <code>page</code> etc. Date archives are archives of posts</p>\n\n<p>So if you went to <code>/category</code> what would it show? For this reason there is nothing there to show. You would need to write a rewrite rule, manually load a template, and that's assuming it doesn't interfere with other rewrite rules</p>\n"
},
{
"answer_id": 273507,
"author": "Johansson",
"author_id": 94498,
"author_profile": "https://wordpress.stackexchange.com/users/94498",
"pm_score": 0,
"selected": false,
"text": "<p>Your home page already shows posts from all the categories. The reason that you can't find anything in that path is that <code>/category/</code> is a base term for categories, the same way <code>/tag/</code> is for tags. You can check this in the permalink page, if you navigate to <code>Settings > Permalinks</code>.</p>\n\n<p>There is only 1 condition that you can have a page that list every post from every category, and it's when you have a static home page. In that case, if you navigate to <code>http://example.com/blog/</code> you will see a list of every post on your website. If you wish, you can redirect <code>http://example.com/category/</code> to <code>http://example.com/blog/</code>.</p>\n\n<p>However, be careful not to redirect any other path such as <code>http://example.com/category/example/</code>, and make sure you have a static page set as home page, or you will get stuck in an infinite loop.</p>\n\n<p>But as @Tom already mentioned, a quarter of the internet runs on WordPress, and they don't have a SEO problem because of this. So, you can just forget about it ;)</p>\n"
}
]
| 2017/07/15 | [
"https://wordpress.stackexchange.com/questions/273500",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/123633/"
]
| I have just followed [this guide](http://www.wpbeginner.com/wp-tutorials/how-to-move-live-wordpress-site-to-local-server/) on manually migrating a WordPress site to localhost.
I have followed all of the steps: downloading files using FTP, exporting database, importing to localhost database, changing URL links to localhost and finally updating wp-config.
I tried this on two of my sites and came across different problems:
1. Safari cannot connect to the server' error message
2. The following text displayed on the screen:
>
> "Front to the WordPress application. This file doesn't do anything,
> but loads wp-blog-header.php which does and tells WordPress to load
> the theme.
>
>
>
```
*
@package WordPress */
/** * Tells WordPress to load the WordPress theme and output it.
* * @var bool */
define('WP_USE_THEMES', true);
/** Loads the WordPress Environment and Template */
require( dirname( FILE ) . '/wp-blog-header.php' );"
```
Can anyone advise as to how I can make my website display? | You can't find it because it doesn't exist. There is no page at that location.
In WordPress everything is either an archive of posts or a post of some type. Pages are posts of type `page` etc. Date archives are archives of posts
So if you went to `/category` what would it show? For this reason there is nothing there to show. You would need to write a rewrite rule, manually load a template, and that's assuming it doesn't interfere with other rewrite rules |
273,523 | <p>I cannot successfully filter posts from some categories and exclude at the same time from others. The code is working perfectly when used to include only posts from a given category. Categories to be included are subcategories and the excluded categories are main categories (they're not parents to the included subcategories)</p>
<p>Examples:</p>
<p>1) Use both <code>category__in</code> and <code>category__not_in</code> at the same time</p>
<pre><code>$wpid = get_category_id($_REQUEST['param']);
$cat_arr = array($wpid);
$args = array(
'category__in' => $cat_arr,
'category__not_in' => array(350,351),
'posts_per_page' => 10,
'post_status' => 'publish',
'suppress_filters' => 0
);
$the_query = new WP_Query( $args );
while ($the_query -> have_posts()){
.
.
}
</code></pre>
<p>2) Use only <code>category__in</code> with negative values:</p>
<pre><code>$wpid = get_category_id($_REQUEST['param']);
$cat_arr = array($wpid);
array_push($cat_arr, -350, -351);
$args = array(
'category__in' => $cat_arr,
'posts_per_page' => 10,
'post_status' => 'publish',
'suppress_filters' => 0
);
$the_query = new WP_Query( $args );
while ($the_query -> have_posts()){
.
.
}
</code></pre>
| [
{
"answer_id": 273496,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 1,
"selected": false,
"text": "<p>You can't find it because it doesn't exist. There is no page at that location.</p>\n\n<p>In WordPress everything is either an archive of posts or a post of some type. Pages are posts of type <code>page</code> etc. Date archives are archives of posts</p>\n\n<p>So if you went to <code>/category</code> what would it show? For this reason there is nothing there to show. You would need to write a rewrite rule, manually load a template, and that's assuming it doesn't interfere with other rewrite rules</p>\n"
},
{
"answer_id": 273507,
"author": "Johansson",
"author_id": 94498,
"author_profile": "https://wordpress.stackexchange.com/users/94498",
"pm_score": 0,
"selected": false,
"text": "<p>Your home page already shows posts from all the categories. The reason that you can't find anything in that path is that <code>/category/</code> is a base term for categories, the same way <code>/tag/</code> is for tags. You can check this in the permalink page, if you navigate to <code>Settings > Permalinks</code>.</p>\n\n<p>There is only 1 condition that you can have a page that list every post from every category, and it's when you have a static home page. In that case, if you navigate to <code>http://example.com/blog/</code> you will see a list of every post on your website. If you wish, you can redirect <code>http://example.com/category/</code> to <code>http://example.com/blog/</code>.</p>\n\n<p>However, be careful not to redirect any other path such as <code>http://example.com/category/example/</code>, and make sure you have a static page set as home page, or you will get stuck in an infinite loop.</p>\n\n<p>But as @Tom already mentioned, a quarter of the internet runs on WordPress, and they don't have a SEO problem because of this. So, you can just forget about it ;)</p>\n"
}
]
| 2017/07/16 | [
"https://wordpress.stackexchange.com/questions/273523",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/1210/"
]
| I cannot successfully filter posts from some categories and exclude at the same time from others. The code is working perfectly when used to include only posts from a given category. Categories to be included are subcategories and the excluded categories are main categories (they're not parents to the included subcategories)
Examples:
1) Use both `category__in` and `category__not_in` at the same time
```
$wpid = get_category_id($_REQUEST['param']);
$cat_arr = array($wpid);
$args = array(
'category__in' => $cat_arr,
'category__not_in' => array(350,351),
'posts_per_page' => 10,
'post_status' => 'publish',
'suppress_filters' => 0
);
$the_query = new WP_Query( $args );
while ($the_query -> have_posts()){
.
.
}
```
2) Use only `category__in` with negative values:
```
$wpid = get_category_id($_REQUEST['param']);
$cat_arr = array($wpid);
array_push($cat_arr, -350, -351);
$args = array(
'category__in' => $cat_arr,
'posts_per_page' => 10,
'post_status' => 'publish',
'suppress_filters' => 0
);
$the_query = new WP_Query( $args );
while ($the_query -> have_posts()){
.
.
}
``` | You can't find it because it doesn't exist. There is no page at that location.
In WordPress everything is either an archive of posts or a post of some type. Pages are posts of type `page` etc. Date archives are archives of posts
So if you went to `/category` what would it show? For this reason there is nothing there to show. You would need to write a rewrite rule, manually load a template, and that's assuming it doesn't interfere with other rewrite rules |
273,545 | <p>I am attempting to import several users, who each should have a connection with a term in a taxonomy named "firm" - but I don't know how to make the connection...</p>
<p><strong>Background:</strong></p>
<p>FYI, I have already enabled WordPress taxonomy support for Users using plugin <a href="https://wordpress.org/plugins/lh-user-taxonomies/" rel="nofollow noreferrer">LH User Taxonomies</a>, and taxonomy "firm" has already been registered. I am importing using plugin <a href="http://www.wpallimport.com/" rel="nofollow noreferrer">WPAllImport</a>.</p>
<p>65 "firms" terms have been created via prior WPAllImport import. Term slugs underwent text processing on inbound company name field <code>$company</code> to <a href="https://stackoverflow.com/questions/40641973/php-to-convert-string-to-slug">strip spaces and convert to lowercase</a>, in order to create a clean term slug.</p>
<p>All this is set up, and the question is not about enabling taxonomy support for Users.</p>
<p><strong>The problem:</strong></p>
<p>I am now importing many Users, and need to connect them to an existing "firm" term (ie. the company they work for). Unfortunately, WPAllImport does not support import to taxonomy terms for Users - but it does support PHP functions executed upon each user import, and actions like pmxi_after_xml_import, which fires after import.</p>
<p>The best way to match seems to be via slug - that is, matching inbound User field <code>$company</code>, after stripping spaces, against a "firm" term with matching unique slug. But how do I do this, and then how do we make the association in the database?</p>
<p>On each individual User import, logic may look something like this:</p>
<ul>
<li>Identify inbound string <code>$company</code></li>
<li>Strip spaces and make <code>$company</code> lowercase using my <code>convert_company_name()</code> function.</li>
<li>Identify taxonomy "firms".</li>
<li>Step through "firms" taxonomy to find a term whose slug matches our processed <code>$company</code> string (eg. "widgetsinc" for User's processed <code>$company</code>, matching "widgetsinc" term slug)</li>
<li>Associate this User with that slug, ie. set the term.</li>
<li>Any appropriate fallback.</li>
</ul>
<p>I'm not sure how any of the code would be written for this.</p>
<p><code>wp set object terms</code> seems like it might be involved?</p>
<p><strong>Edit (2):</strong></p>
<p>I think I have learned how to do a lot here. This seems to work, to a point...</p>
<pre><code>// Relate user to "firm" taxonomy terms
function relate_user_to_firm($company, $username){
// convert company name to slug format
$company_slug = lowercase_and_strip($company);
// use slug to find corresponding taxonomy term
$term = get_term_by('slug', $company_slug, 'firm');
// get the object id of this term
$mytermid = $term->term_id;
// get user's ID
$user = get_user_by('login', $username);
$user_id = $user->ID;
// *** relate user to this term ***
wp_set_object_terms( $user_id, $mytermid, 'firm' );
}
</code></pre>
<p>The trouble is, whilst the correct terms show under the "Firms" column on my Users listing page, the Users count against the actual term on the Firms listing page is not updated, it still shows 0. What's going on there?</p>
| [
{
"answer_id": 273590,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 0,
"selected": false,
"text": "<p>users are humans (or extensions of humans) that have some level of admin access, taxonomies are for \"categorizing\" content, humans are not content. In other words - if you feel like you need to associate a taxonomy with users, you are probably doing something wrong, or at least shady.</p>\n\n<p>The only association that there should be between a user and content is whatever setting are required to determine if the user can edit that content, but it sounds like you are trying to get users \"categorized\" with taxonomies, which is wrong.</p>\n"
},
{
"answer_id": 356932,
"author": "Yaakov Aglamaz",
"author_id": 154659,
"author_profile": "https://wordpress.stackexchange.com/users/154659",
"pm_score": 1,
"selected": false,
"text": "<p>The function wp_set_object_terms relates to objects (posts, page, etc).\nYou better use usermeta - update_usermeta.\nE.g \n<code>update_usermeta( $user_id, 'company', $company_id );</code></p>\n\n<p>Wordpress is built by two major database tables (wp_posts and wp_users) and two (meta tables wp_postmeta and wp_usermeta). It seems that the term tables (wp_terms and others) relates to wp_posts.</p>\n\n<p>I dealing with the same need (relate user to a company). I thought to use terms, but I will use usermeta.</p>\n"
}
]
| 2017/07/16 | [
"https://wordpress.stackexchange.com/questions/273545",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/39300/"
]
| I am attempting to import several users, who each should have a connection with a term in a taxonomy named "firm" - but I don't know how to make the connection...
**Background:**
FYI, I have already enabled WordPress taxonomy support for Users using plugin [LH User Taxonomies](https://wordpress.org/plugins/lh-user-taxonomies/), and taxonomy "firm" has already been registered. I am importing using plugin [WPAllImport](http://www.wpallimport.com/).
65 "firms" terms have been created via prior WPAllImport import. Term slugs underwent text processing on inbound company name field `$company` to [strip spaces and convert to lowercase](https://stackoverflow.com/questions/40641973/php-to-convert-string-to-slug), in order to create a clean term slug.
All this is set up, and the question is not about enabling taxonomy support for Users.
**The problem:**
I am now importing many Users, and need to connect them to an existing "firm" term (ie. the company they work for). Unfortunately, WPAllImport does not support import to taxonomy terms for Users - but it does support PHP functions executed upon each user import, and actions like pmxi\_after\_xml\_import, which fires after import.
The best way to match seems to be via slug - that is, matching inbound User field `$company`, after stripping spaces, against a "firm" term with matching unique slug. But how do I do this, and then how do we make the association in the database?
On each individual User import, logic may look something like this:
* Identify inbound string `$company`
* Strip spaces and make `$company` lowercase using my `convert_company_name()` function.
* Identify taxonomy "firms".
* Step through "firms" taxonomy to find a term whose slug matches our processed `$company` string (eg. "widgetsinc" for User's processed `$company`, matching "widgetsinc" term slug)
* Associate this User with that slug, ie. set the term.
* Any appropriate fallback.
I'm not sure how any of the code would be written for this.
`wp set object terms` seems like it might be involved?
**Edit (2):**
I think I have learned how to do a lot here. This seems to work, to a point...
```
// Relate user to "firm" taxonomy terms
function relate_user_to_firm($company, $username){
// convert company name to slug format
$company_slug = lowercase_and_strip($company);
// use slug to find corresponding taxonomy term
$term = get_term_by('slug', $company_slug, 'firm');
// get the object id of this term
$mytermid = $term->term_id;
// get user's ID
$user = get_user_by('login', $username);
$user_id = $user->ID;
// *** relate user to this term ***
wp_set_object_terms( $user_id, $mytermid, 'firm' );
}
```
The trouble is, whilst the correct terms show under the "Firms" column on my Users listing page, the Users count against the actual term on the Firms listing page is not updated, it still shows 0. What's going on there? | The function wp\_set\_object\_terms relates to objects (posts, page, etc).
You better use usermeta - update\_usermeta.
E.g
`update_usermeta( $user_id, 'company', $company_id );`
Wordpress is built by two major database tables (wp\_posts and wp\_users) and two (meta tables wp\_postmeta and wp\_usermeta). It seems that the term tables (wp\_terms and others) relates to wp\_posts.
I dealing with the same need (relate user to a company). I thought to use terms, but I will use usermeta. |
273,558 | <p>So I made a couple of custom taxonomies to add multiple categories to a page/project. (single-work.php) The default one (built in category) being <code>project type</code>, and the two new ones being <code>client</code> and <code>agency</code>.</p>
<p>Basically I use the same code for all three, but I just noticed that what it's doing for the two custom categories is basically reading out EVERY tag I've added to different projects, instead of only showing the tag that's selected for that specific page.</p>
<p>In other words, it's basically just showing every tag that can be found under the "Choose from the most used tags" area. Despite only a single tag being selected for each project.</p>
<p>I hope that was somewhat clear :)</p>
<p>Here's the code I'm using:</p>
<pre><code><?php $terms = get_terms( 'portfolio_tags_client' );
foreach ( $terms as $term ) {
$term_link = get_term_link( $term );
if ( is_wp_error( $term_link ) ) {
continue;
}
echo 'Client: <a href="' . esc_url( $term_link ) . '">' . $term->name . '</a>&nbsp;<br />';
}
?>
</code></pre>
<p>And here's the taxonomy it's coming out of, if that helps:</p>
<pre><code>register_taxonomy(
'portfolio_tags_client', //The name of the taxonomy. Name should be in slug form (must not contain capital letters or spaces).
'work', // Post type name
array(
'hierarchical' => false,
'label' => 'Clients', // Display name
'singular_name' => 'Client',
'query_var' => true,
'rewrite' => array(
'slug' => 'client', // This controls the base slug that will display before each term
'with_front' => false // Don't display the category base before
)
)
);
</code></pre>
<p>Does anyone know what it could be? I've spent way more time than I'd like to admit trying to fix this :)</p>
<p><strong>UPDATE</strong> Fixed! Thanks so much for the help guys. I really appreciate it. Here's the final code:</p>
<pre><code><?php $post_tags = get_the_terms(get_the_ID(), 'portfolio_tags_client');
if ($post_tags) {
foreach($post_tags as $tag) {
echo 'Client: <a href="'.get_tag_link($tag->term_id).'" title="'.$tag->name.'">'. $tag->name .'</a>&nbsp;<br />';
}
}
?>
</code></pre>
| [
{
"answer_id": 273561,
"author": "montrealist",
"author_id": 8105,
"author_profile": "https://wordpress.stackexchange.com/users/8105",
"pm_score": 0,
"selected": false,
"text": "<p>You can set the post status to <code>trash</code>.</p>\n\n<pre><code>$post_id = 1; // change this to your post ID\n$status = 'trash';\n$current_post = get_post( $post_id, 'ARRAY_A' );\n$current_post['post_status'] = $status;\nwp_update_post($current_post);\n</code></pre>\n\n<p>Got code from <a href=\"https://wordpress.stackexchange.com/a/12518/8105\">this answer</a>.</p>\n"
},
{
"answer_id": 273563,
"author": "Max Yudin",
"author_id": 11761,
"author_profile": "https://wordpress.stackexchange.com/users/11761",
"pm_score": 1,
"selected": false,
"text": "<p>You can move the post to Trash before you save it or publish:</p>\n\n<p><a href=\"https://i.stack.imgur.com/olHzC.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/olHzC.png\" alt=\"enter image description here\"></a></p>\n\n<p>Or you can do it later, from the post list:</p>\n\n<p><a href=\"https://i.stack.imgur.com/Ng1mh.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Ng1mh.png\" alt=\"enter image description here\"></a></p>\n\n<p>Later you can empty Trash or it will automatically delete everything from Trash what is older than a month.</p>\n"
}
]
| 2017/07/16 | [
"https://wordpress.stackexchange.com/questions/273558",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/123968/"
]
| So I made a couple of custom taxonomies to add multiple categories to a page/project. (single-work.php) The default one (built in category) being `project type`, and the two new ones being `client` and `agency`.
Basically I use the same code for all three, but I just noticed that what it's doing for the two custom categories is basically reading out EVERY tag I've added to different projects, instead of only showing the tag that's selected for that specific page.
In other words, it's basically just showing every tag that can be found under the "Choose from the most used tags" area. Despite only a single tag being selected for each project.
I hope that was somewhat clear :)
Here's the code I'm using:
```
<?php $terms = get_terms( 'portfolio_tags_client' );
foreach ( $terms as $term ) {
$term_link = get_term_link( $term );
if ( is_wp_error( $term_link ) ) {
continue;
}
echo 'Client: <a href="' . esc_url( $term_link ) . '">' . $term->name . '</a> <br />';
}
?>
```
And here's the taxonomy it's coming out of, if that helps:
```
register_taxonomy(
'portfolio_tags_client', //The name of the taxonomy. Name should be in slug form (must not contain capital letters or spaces).
'work', // Post type name
array(
'hierarchical' => false,
'label' => 'Clients', // Display name
'singular_name' => 'Client',
'query_var' => true,
'rewrite' => array(
'slug' => 'client', // This controls the base slug that will display before each term
'with_front' => false // Don't display the category base before
)
)
);
```
Does anyone know what it could be? I've spent way more time than I'd like to admit trying to fix this :)
**UPDATE** Fixed! Thanks so much for the help guys. I really appreciate it. Here's the final code:
```
<?php $post_tags = get_the_terms(get_the_ID(), 'portfolio_tags_client');
if ($post_tags) {
foreach($post_tags as $tag) {
echo 'Client: <a href="'.get_tag_link($tag->term_id).'" title="'.$tag->name.'">'. $tag->name .'</a> <br />';
}
}
?>
``` | You can move the post to Trash before you save it or publish:
[](https://i.stack.imgur.com/olHzC.png)
Or you can do it later, from the post list:
[](https://i.stack.imgur.com/Ng1mh.png)
Later you can empty Trash or it will automatically delete everything from Trash what is older than a month. |
273,572 | <p>I am using WordPress to develop a picture gallery website. I have albums and galleries, with different permalinks...<code>http://url.com/albums</code> and <code>http://url.com/gallery</code>, but only the albums appear in the main navigation.</p>
<p>The code for my navigation looks like:</p>
<pre><code><div id="nav">
<ul>
<?php wp_list_pages("title_li="); ?>
</ul>
</div>
</code></pre>
<p>Because I am using the <code>wp_list_pages()</code> function, the current page that you're on gets a <code>current_page_item</code> class added to the <code>li</code> tag.</p>
<p>The gallery page is not part of the main navigation, so when someone is viewing one of the gallery pages, nothing is highlighted in the main navigation.</p>
<p>I'd like to highlight the album page in the main navigation when someone is viewing a gallery page. Because each gallery is in album, it makes sense to highlight that page.</p>
<p>Can anyone point me in the right direction?</p>
<p>Thanks,<br />
Josh</p>
| [
{
"answer_id": 273653,
"author": "Milo",
"author_id": 4771,
"author_profile": "https://wordpress.stackexchange.com/users/4771",
"pm_score": 2,
"selected": true,
"text": "<p>The <a href=\"https://developer.wordpress.org/reference/hooks/page_css_class/\" rel=\"nofollow noreferrer\"><code>page_css_class</code> filter</a> lets you modify the classes each menu item gets.</p>\n\n<p>Here we check if we are currently viewing a singular <code>envira</code> post type and the menu item slug is <code>gallery</code>. In that case we add a class to the array of default classes passed to the function.</p>\n\n<pre><code>function wpd_page_css_class( $css_class, $page ){\n if( is_singular( 'envira' ) && 'albums' == $page->post_name ){\n $css_class[] = 'current_page_item';\n }\n return $css_class;\n}\nadd_filter( 'page_css_class', 'wpd_page_css_class', 10, 2 );\n</code></pre>\n"
},
{
"answer_id": 273676,
"author": "Josh Rodgers",
"author_id": 9820,
"author_profile": "https://wordpress.stackexchange.com/users/9820",
"pm_score": 0,
"selected": false,
"text": "<p>After some poking around, I found my answer here: <a href=\"https://forum.jquery.com/topic/jquery-addclass-to-containing-li-based-on-a-href-contents\" rel=\"nofollow noreferrer\">https://forum.jquery.com/topic/jquery-addclass-to-containing-li-based-on-a-href-contents</a> from Przemek (4th comment down).</p>\n\n<p>All I did was make sure that the code is only executed on the gallery page:</p>\n\n<pre><code><?php if ( is_singular(\"envira\") ) { ?>\n <script>\n $(function() {\n $('li.page_item').find('a[href*=\"/albums/\"]').parent().addClass('current_page_item');\n });\n </script>\n<?php } ?>\n</code></pre>\n\n<p>This works, because it finds the list item with the albums permalink and adds the class I need. If I ever change the page order, the script will still work. The only time this would be an issue is if my permalink changes, but for this site, that is not an issue.</p>\n\n<p>Thanks,<br />\nJosh</p>\n"
}
]
| 2017/07/17 | [
"https://wordpress.stackexchange.com/questions/273572",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/9820/"
]
| I am using WordPress to develop a picture gallery website. I have albums and galleries, with different permalinks...`http://url.com/albums` and `http://url.com/gallery`, but only the albums appear in the main navigation.
The code for my navigation looks like:
```
<div id="nav">
<ul>
<?php wp_list_pages("title_li="); ?>
</ul>
</div>
```
Because I am using the `wp_list_pages()` function, the current page that you're on gets a `current_page_item` class added to the `li` tag.
The gallery page is not part of the main navigation, so when someone is viewing one of the gallery pages, nothing is highlighted in the main navigation.
I'd like to highlight the album page in the main navigation when someone is viewing a gallery page. Because each gallery is in album, it makes sense to highlight that page.
Can anyone point me in the right direction?
Thanks,
Josh | The [`page_css_class` filter](https://developer.wordpress.org/reference/hooks/page_css_class/) lets you modify the classes each menu item gets.
Here we check if we are currently viewing a singular `envira` post type and the menu item slug is `gallery`. In that case we add a class to the array of default classes passed to the function.
```
function wpd_page_css_class( $css_class, $page ){
if( is_singular( 'envira' ) && 'albums' == $page->post_name ){
$css_class[] = 'current_page_item';
}
return $css_class;
}
add_filter( 'page_css_class', 'wpd_page_css_class', 10, 2 );
``` |
273,582 | <p>Let suppose I have made a file in my theme folder (with the name c.php) and I want it to link it with a custom button (that I have made in post/page) in admin using GET action. How can I achieve that</p>
| [
{
"answer_id": 273623,
"author": "lky",
"author_id": 102937,
"author_profile": "https://wordpress.stackexchange.com/users/102937",
"pm_score": 0,
"selected": false,
"text": "<p>Im a little unsure what you are trying to achieve but can't you link the button like:</p>\n\n<pre><code>href=\"<?php echo get_template_directory_uri(); ?>/c.php\"\n</code></pre>\n"
},
{
"answer_id": 277560,
"author": "Owaiz Yusufi",
"author_id": 108146,
"author_profile": "https://wordpress.stackexchange.com/users/108146",
"pm_score": 3,
"selected": true,
"text": "<p>Finally, I make it, the way without losing the access to WordPress environment:</p>\n\n<pre><code>add_action( 'edit_form_after_title', 'custom_button' );\nfunction custom_button() {\n$button = sprintf('<a href=\"%1$s\" class=\"button button-primary button-large\">%2$s</a>', esc_url( add_query_arg( 'link' , true, get_the_permalink() ) ), 'Custom Button'\n );\n\n print_r($button);\n}\n</code></pre>\n\n<p><strong>Update:</strong> </p>\n\n<p><strong><em>Hint</em></strong>: Please make a function for validation the url for ssl and wrap get_the_permalink() inside it.</p>\n"
}
]
| 2017/07/17 | [
"https://wordpress.stackexchange.com/questions/273582",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/108146/"
]
| Let suppose I have made a file in my theme folder (with the name c.php) and I want it to link it with a custom button (that I have made in post/page) in admin using GET action. How can I achieve that | Finally, I make it, the way without losing the access to WordPress environment:
```
add_action( 'edit_form_after_title', 'custom_button' );
function custom_button() {
$button = sprintf('<a href="%1$s" class="button button-primary button-large">%2$s</a>', esc_url( add_query_arg( 'link' , true, get_the_permalink() ) ), 'Custom Button'
);
print_r($button);
}
```
**Update:**
***Hint***: Please make a function for validation the url for ssl and wrap get\_the\_permalink() inside it. |
273,597 | <p>I need an extra pair of eyes on this. I have customized a block of code in a function of a commercial theme, which is the following code: </p>
<pre><code> <div class="author-description">
<h5><span class="fn"><?php the_author_link(); ?></span></h5>
<p class="note"><?php the_author_meta( 'description', $id ); ?></p>
<?php csco_post_author_social_accounts( $id ); ?>
</div>
</code></pre>
<p>There's <code>the_author_link()</code> in it, which states either the name of the user, or the link to the website of the user, which can be filled in the admin users profile. The <code>the_author_link()</code> does not accept any parameters, according to the Codex. </p>
<p>I would like this function to open the link in a new window. Do I need to break the function down?</p>
| [
{
"answer_id": 273623,
"author": "lky",
"author_id": 102937,
"author_profile": "https://wordpress.stackexchange.com/users/102937",
"pm_score": 0,
"selected": false,
"text": "<p>Im a little unsure what you are trying to achieve but can't you link the button like:</p>\n\n<pre><code>href=\"<?php echo get_template_directory_uri(); ?>/c.php\"\n</code></pre>\n"
},
{
"answer_id": 277560,
"author": "Owaiz Yusufi",
"author_id": 108146,
"author_profile": "https://wordpress.stackexchange.com/users/108146",
"pm_score": 3,
"selected": true,
"text": "<p>Finally, I make it, the way without losing the access to WordPress environment:</p>\n\n<pre><code>add_action( 'edit_form_after_title', 'custom_button' );\nfunction custom_button() {\n$button = sprintf('<a href=\"%1$s\" class=\"button button-primary button-large\">%2$s</a>', esc_url( add_query_arg( 'link' , true, get_the_permalink() ) ), 'Custom Button'\n );\n\n print_r($button);\n}\n</code></pre>\n\n<p><strong>Update:</strong> </p>\n\n<p><strong><em>Hint</em></strong>: Please make a function for validation the url for ssl and wrap get_the_permalink() inside it.</p>\n"
}
]
| 2017/07/17 | [
"https://wordpress.stackexchange.com/questions/273597",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/60297/"
]
| I need an extra pair of eyes on this. I have customized a block of code in a function of a commercial theme, which is the following code:
```
<div class="author-description">
<h5><span class="fn"><?php the_author_link(); ?></span></h5>
<p class="note"><?php the_author_meta( 'description', $id ); ?></p>
<?php csco_post_author_social_accounts( $id ); ?>
</div>
```
There's `the_author_link()` in it, which states either the name of the user, or the link to the website of the user, which can be filled in the admin users profile. The `the_author_link()` does not accept any parameters, according to the Codex.
I would like this function to open the link in a new window. Do I need to break the function down? | Finally, I make it, the way without losing the access to WordPress environment:
```
add_action( 'edit_form_after_title', 'custom_button' );
function custom_button() {
$button = sprintf('<a href="%1$s" class="button button-primary button-large">%2$s</a>', esc_url( add_query_arg( 'link' , true, get_the_permalink() ) ), 'Custom Button'
);
print_r($button);
}
```
**Update:**
***Hint***: Please make a function for validation the url for ssl and wrap get\_the\_permalink() inside it. |
273,654 | <p>I can't access the dashboard of the second site. When I go to the second site, I only see the HTML page without the style (css).</p>
<p>When I try to access the dashboard (from Safari), I get this message from the browser: "too many redirects occurred trying to open".</p>
<p>Subsite set-up</p>
<p>example.com (works)</p>
<p>example.com/secondary (doesn't work)</p>
<p>I tried disabling all plugins and change to the default theme. It still doesn't work. Here's what in my .htaccess file:</p>
<pre><code># BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
# add a trailing slash to /wp-admin
RewriteRule ^([_0-9a-zA-Z-]+/)?wp-admin$ $1wp-admin/ [R=301,L]
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]
RewriteRule ^([_0-9a-zA-Z-]+/)?(wp-(content|admin|includes).*) $2 [L]
RewriteRule ^([_0-9a-zA-Z-]+/)?(.*\.php)$ $2 [L]
RewriteRule . index.php [L]
</IfModule>
# END WordPress
</code></pre>
| [
{
"answer_id": 273619,
"author": "Chris Cox",
"author_id": 1718,
"author_profile": "https://wordpress.stackexchange.com/users/1718",
"pm_score": 1,
"selected": false,
"text": "<p>It's in the filename. single-$posttype.php, archive-$posttype.php</p>\n"
},
{
"answer_id": 273622,
"author": "lky",
"author_id": 102937,
"author_profile": "https://wordpress.stackexchange.com/users/102937",
"pm_score": 2,
"selected": false,
"text": "<p>You need to create the template files within your theme using the correct naming.</p>\n\n<p>Please see:</p>\n\n<p><a href=\"https://developer.wordpress.org/themes/template-files-section/page-template-files/#creating-page-templates-for-specific-post-types\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/themes/template-files-section/page-template-files/#creating-page-templates-for-specific-post-types</a></p>\n"
},
{
"answer_id": 273629,
"author": "Simon Forster",
"author_id": 17208,
"author_profile": "https://wordpress.stackexchange.com/users/17208",
"pm_score": 0,
"selected": false,
"text": "<p>As heady12 pointed out</p>\n\n<p><a href=\"https://wordpress.stackexchange.com/questions/204657/apply-template-to-custom-post-type\">Apply template to custom post type</a></p>\n\n<p>With some modifications to conditions this worked.</p>\n"
}
]
| 2017/07/17 | [
"https://wordpress.stackexchange.com/questions/273654",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/123998/"
]
| I can't access the dashboard of the second site. When I go to the second site, I only see the HTML page without the style (css).
When I try to access the dashboard (from Safari), I get this message from the browser: "too many redirects occurred trying to open".
Subsite set-up
example.com (works)
example.com/secondary (doesn't work)
I tried disabling all plugins and change to the default theme. It still doesn't work. Here's what in my .htaccess file:
```
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
# add a trailing slash to /wp-admin
RewriteRule ^([_0-9a-zA-Z-]+/)?wp-admin$ $1wp-admin/ [R=301,L]
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]
RewriteRule ^([_0-9a-zA-Z-]+/)?(wp-(content|admin|includes).*) $2 [L]
RewriteRule ^([_0-9a-zA-Z-]+/)?(.*\.php)$ $2 [L]
RewriteRule . index.php [L]
</IfModule>
# END WordPress
``` | You need to create the template files within your theme using the correct naming.
Please see:
<https://developer.wordpress.org/themes/template-files-section/page-template-files/#creating-page-templates-for-specific-post-types> |
273,678 | <p>I am sending php array using serialise but the response is different. Here is my attempt</p>
<pre><code>$array = serialize($out);
var_dump(serialize($array));
//string(58) "s:50:"a:2:{s:9:"sidebar-1";i:5;s:12:"footer-insta";i:2;}";"
</code></pre>
<p>The way I am sending this value, </p>
<pre><code>echo '<div data-ad = '.$array.' class="ash_loadmore"><span>LOAD MORE</span></div>';
</code></pre>
<p>As I am sending the serialised value using ajax, the value that ajax response give me,</p>
<pre><code>string(54) "a:2:{s:9:\"sidebar-1\";i:5;s:12:\"footer-insta\";i:2;}"
</code></pre>
<p>I need the exact value as I have unserialise again to make it array. Why there is extra <code>\</code> and output is different. </p>
| [
{
"answer_id": 273680,
"author": "CodeMascot",
"author_id": 44192,
"author_profile": "https://wordpress.stackexchange.com/users/44192",
"pm_score": 0,
"selected": false,
"text": "<p>Well, this <code>\\</code> is getting added to escape the <code>\"</code>. For example you are storing the whole string <code>\"sidebar-1\"</code>. Notice the string contains opening <code>\"</code> and also closing <code>\"</code>. Now the string is also wrapped with another <code>\"\"</code>, so for separating the opening <code>\"</code> and closing <code>\"</code> of the stored string it's adding a <code>\\</code> to escape it. This way it makes it hidden form parsing the <code>\"\"</code> of the stored string as a real quote.</p>\n"
},
{
"answer_id": 273936,
"author": "ashraf",
"author_id": 30937,
"author_profile": "https://wordpress.stackexchange.com/users/30937",
"pm_score": 3,
"selected": true,
"text": "<p>Well it seems @JacobPeattie mentioned to use json, I just echoing that. </p>\n\n<ol>\n<li><p>First json encode the variable <code>$array = json_encode($out);</code></p></li>\n<li><p>Then send this value <code>echo '<div data-ad = '.$array.' class=\"ash_loadmore\"><span>LOAD MORE</span></div>';</code></p></li>\n<li><p>To get that <code>echo json_encode($_POST['ad'])</code></p></li>\n</ol>\n\n<p>I think that's it.BTW you don't have now that string problem as the output will be like this <code>{\"footer-insta\":2,\"sidebar-1\":3}</code> you see it is wrapped by <code>{}</code></p>\n"
},
{
"answer_id": 273981,
"author": "Arkadiusz Bartnik",
"author_id": 105408,
"author_profile": "https://wordpress.stackexchange.com/users/105408",
"pm_score": 0,
"selected": false,
"text": "<p>The simplest and least problematic solution:</p>\n\n<pre><code>$array = json_encode($out);\nvar_dump(array); // string \"{\\\"sidebar-1\\\":5,\\\"footer-insta\\\":2}\"\n</code></pre>\n\n<p>In JS you can use:</p>\n\n<pre>\nJSON.parse(\"{\\\"sidebar-1\\\":5,\\\"footer-insta\\\":2}\")\n</pre>\n\n<p>and you have object with data</p>\n"
}
]
| 2017/07/17 | [
"https://wordpress.stackexchange.com/questions/273678",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/48294/"
]
| I am sending php array using serialise but the response is different. Here is my attempt
```
$array = serialize($out);
var_dump(serialize($array));
//string(58) "s:50:"a:2:{s:9:"sidebar-1";i:5;s:12:"footer-insta";i:2;}";"
```
The way I am sending this value,
```
echo '<div data-ad = '.$array.' class="ash_loadmore"><span>LOAD MORE</span></div>';
```
As I am sending the serialised value using ajax, the value that ajax response give me,
```
string(54) "a:2:{s:9:\"sidebar-1\";i:5;s:12:\"footer-insta\";i:2;}"
```
I need the exact value as I have unserialise again to make it array. Why there is extra `\` and output is different. | Well it seems @JacobPeattie mentioned to use json, I just echoing that.
1. First json encode the variable `$array = json_encode($out);`
2. Then send this value `echo '<div data-ad = '.$array.' class="ash_loadmore"><span>LOAD MORE</span></div>';`
3. To get that `echo json_encode($_POST['ad'])`
I think that's it.BTW you don't have now that string problem as the output will be like this `{"footer-insta":2,"sidebar-1":3}` you see it is wrapped by `{}` |
273,695 | <p>I have two meta_keys on a custom post type. I want to be able to query all of these posts, and order them by the two <code>meta_key</code>, one taking precedence over the other.</p>
<p>I.e. I have one <code>meta_key</code> called <code>stickied</code>, these should always appear first. The second <code>meta_key</code> is <code>popularity</code>, which is a basic hit count for that post.</p>
<p>When I use <code>meta_query</code>, it seems that posts <em>without</em> the meta keys initialized will not appear in the result set. I want <em>all</em> posts regardless of whether they have the <code>meta_key</code> initialized or not, and <em>then</em> order them based on those <code>meta_key</code>.</p>
<p>Is this possible?</p>
| [
{
"answer_id": 273697,
"author": "Johansson",
"author_id": 94498,
"author_profile": "https://wordpress.stackexchange.com/users/94498",
"pm_score": 0,
"selected": false,
"text": "<p>As I understand, you are trying to sort the post by meta values. In such cases, you can use <code>'orderby => 'meta_value'</code>. So your query will look like this:</p>\n\n<pre><code>$args = array(\n 'orderby' => 'meta_value',\n 'meta_key' => 'stickied',\n);\n$query = new WP_Query( $args );\n</code></pre>\n\n<p>Not that <code>orderby</code> can accept multiple values, such as:</p>\n\n<pre><code>$args = array(\n 'post_type' => 'page',\n 'orderby' => array( 'title' => 'DESC', 'meta_value' => 'ASC' ),\n 'meta_key' => 'stickied',\n\n);\n</code></pre>\n\n<p>However I'm not sure if you can use multiple meta values, but it is probably possible. At the moment I don't have such condition in my database to test it, but based on my example and this <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters\" rel=\"nofollow noreferrer\">codex page</a> you should be able to easily try it out.</p>\n\n<p>Please let me know if sorting by multiple values worked for you based on above structure.</p>\n\n<h2>UPDATE</h2>\n\n<p>After digging for a while, I've found <a href=\"https://wordpress.stackexchange.com/a/188305/94498\">this</a> answer and this code that provides a solution to this situation:</p>\n\n<pre><code>$args = array(\n 'post_type' => 'post',\n 'orderby' => 'meta_key',\n 'order' => 'ASC',\n 'meta_query' => array(\n 'relation' => 'OR',\n array( \n 'key'=>'stickied',\n 'compare' => 'EXISTS' \n ),\n array( \n 'key'=>'popularity',\n 'compare' => 'EXISTS' \n )\n ),\n 'post_per_page'=>-1\n);\n\n$query = new WP_Query($args);\n</code></pre>\n"
},
{
"answer_id": 356986,
"author": "KFish",
"author_id": 158938,
"author_profile": "https://wordpress.stackexchange.com/users/158938",
"pm_score": 0,
"selected": false,
"text": "<p>There are a number of ways to go about solving something like this. The real problem comes if/when you need to apply default pagination to the query.</p>\n\n<p>The best way to handle this, and preserve the ability to paginate, would be to use a combination of meta_query clauses. Jack Johansson was on the right track, this just requires a bit more logic in the query. You may need to adjust the exact combination a bit to suit your needs, as this is just an estimated guess based on the info provided.</p>\n\n<p>Try something like this:</p>\n\n<pre><code>$args = array(\n 'post_type' => 'post',\n 'meta_query' => array(\n 'relation' => 'OR',\n 'sticky_pop_clause' => array(\n 'relation' => 'AND',\n 'sp_sticky' => array( \n 'key' => 'stickied',\n 'compare' => 'EXISTS' \n ),\n 'sp_pop' => array( \n 'key' => 'popularity',\n 'compare' => 'EXISTS' \n ) \n ),\n 'sticky_clause' => array( \n 'key' => 'stickied',\n 'compare' => 'EXISTS' \n ),\n 'popular_clause' => array( \n 'key'=>'popularity',\n 'compare' => 'EXISTS' \n ),\n 'other_clause' => array(\n 'relation' => 'AND',\n array( \n 'key'=>'stickied',\n 'compare' => 'NOT EXISTS' \n ),\n array( \n 'key'=>'popularity',\n 'compare' => 'NOT EXISTS' \n )\n )\n ),\n 'orderby' => array(\n 'sp_pop' => 'DESC',\n 'sticky_clause' => 'ASC',\n 'popular_clause' => 'DESC',\n 'date' => 'DESC'\n )\n);\n\n$query = new WP_Query($args);\n</code></pre>\n"
},
{
"answer_id": 367498,
"author": "dodo254",
"author_id": 109705,
"author_profile": "https://wordpress.stackexchange.com/users/109705",
"pm_score": 0,
"selected": false,
"text": "<p>You would need to check all (<em>select</em>) the posts with and without <code>stickied</code> and <code>popularity</code> with both <code>EXISTS</code> and <code>NOT EXISTS</code>. After that you sort it with <code>orderby</code>.</p>\n\n<p>Didn't test it. Modify it to your needs. I did smth similar. Results were okay.</p>\n\n<pre><code>$args = [\n 'meta_query' => [\n 'relation' => 'OR',\n 'with_stickied' => [\n 'key'=>'stickied',\n 'compare' => 'EXISTS' \n ],\n 'without_stickied' => [\n 'key'=>'stickied',\n 'compare' => 'NOT EXISTS' \n ],\n 'with_popularity' => [\n 'key'=>'popularity',\n 'compare' => 'EXISTS' \n ],\n 'with_popularity' => [\n 'key'=>'popularity',\n 'compare' => 'NOT EXISTS' \n ],\n ],\n 'orderby' => [\n 'with_stickied' => 'DESC',\n 'with_popularity' => 'DESC',\n ]\n];\n</code></pre>\n\n<p>You might want to check \"<strong>‘orderby’ with multiple ‘meta_key’s</strong>\" from <a href=\"https://developer.wordpress.org/reference/classes/wp_query/#order-orderby-parameters\" rel=\"nofollow noreferrer\">WP Codex</a>.</p>\n"
},
{
"answer_id": 370575,
"author": "nicolasDevDes",
"author_id": 140598,
"author_profile": "https://wordpress.stackexchange.com/users/140598",
"pm_score": 2,
"selected": false,
"text": "<p>I had a similar issue but couldn't solved with the snippets on this thread.</p>\n<p>I had to order a query by:</p>\n<ol>\n<li>all 'featured' posts first (<em><strong>is_it_a_featured_etf</strong></em>) and</li>\n<li>by a numeric field (<em><strong>etf_aum</strong></em>) in DESC order after the featured ones.</li>\n</ol>\n<p>My solution:</p>\n<pre><code>'meta_query' => [\n 'relation' => 'OR',\n\n 'etf_aum' => array(\n 'key' => 'etf_aum',\n 'type' => 'NUMERIC',\n 'compare' => 'EXISTS',\n ),\n\n 'is_it_a_featured_etf' => array(\n 'key' => 'is_it_a_featured_etf',\n 'compare' => 'EXISTS',\n 'value' => '1',\n 'operator' => '=',\n ),\n],\n'orderby' => [\n 'is_it_a_featured_etf' => 'ASC',\n 'etf_aum' => 'DESC',\n]\n</code></pre>\n"
}
]
| 2017/07/18 | [
"https://wordpress.stackexchange.com/questions/273695",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/124056/"
]
| I have two meta\_keys on a custom post type. I want to be able to query all of these posts, and order them by the two `meta_key`, one taking precedence over the other.
I.e. I have one `meta_key` called `stickied`, these should always appear first. The second `meta_key` is `popularity`, which is a basic hit count for that post.
When I use `meta_query`, it seems that posts *without* the meta keys initialized will not appear in the result set. I want *all* posts regardless of whether they have the `meta_key` initialized or not, and *then* order them based on those `meta_key`.
Is this possible? | I had a similar issue but couldn't solved with the snippets on this thread.
I had to order a query by:
1. all 'featured' posts first (***is\_it\_a\_featured\_etf***) and
2. by a numeric field (***etf\_aum***) in DESC order after the featured ones.
My solution:
```
'meta_query' => [
'relation' => 'OR',
'etf_aum' => array(
'key' => 'etf_aum',
'type' => 'NUMERIC',
'compare' => 'EXISTS',
),
'is_it_a_featured_etf' => array(
'key' => 'is_it_a_featured_etf',
'compare' => 'EXISTS',
'value' => '1',
'operator' => '=',
),
],
'orderby' => [
'is_it_a_featured_etf' => 'ASC',
'etf_aum' => 'DESC',
]
``` |
273,704 | <p>Since some updates of WooCommerce, Wordpress, Theme etc. on our product pages in the product-tab "additional information" some attributes are now linkable (to some automatic created pages). I cant find the setting how to disable it and even so no php solution for functions.php. I neither want that automatic pages then the links.</p>
<p><a href="https://i.stack.imgur.com/0o8AT.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/0o8AT.png" alt="enter image description here"></a></p>
<p>Do you know how to fix that?</p>
| [
{
"answer_id": 276255,
"author": "Krystian",
"author_id": 122426,
"author_profile": "https://wordpress.stackexchange.com/users/122426",
"pm_score": 1,
"selected": true,
"text": "<p>I couldnt find a real Solution, but I used CSS to visually hide the link, but actually the link still exists, but its not clickable anymore. Note: change this CSS to your font-color:</p>\n\n<pre><code>.shop_attributes a[rel=\"tag\"] {\n pointer-events: none;\n cursor: default;\n color: #888;\n}\n</code></pre>\n"
},
{
"answer_id": 276760,
"author": "JayBomb",
"author_id": 125787,
"author_profile": "https://wordpress.stackexchange.com/users/125787",
"pm_score": 2,
"selected": false,
"text": "<p>I think what you are looking for is archive deactivation for the attributes.</p>\n\n<ul>\n<li>Go to Attributes</li>\n<li>Select and Edit the linkable Attribute</li>\n<li>Uncheck \"Enable Archives\"</li>\n<li>Update</li>\n</ul>\n\n<p>Should do the trick.</p>\n"
}
]
| 2017/07/18 | [
"https://wordpress.stackexchange.com/questions/273704",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/122426/"
]
| Since some updates of WooCommerce, Wordpress, Theme etc. on our product pages in the product-tab "additional information" some attributes are now linkable (to some automatic created pages). I cant find the setting how to disable it and even so no php solution for functions.php. I neither want that automatic pages then the links.
[](https://i.stack.imgur.com/0o8AT.png)
Do you know how to fix that? | I couldnt find a real Solution, but I used CSS to visually hide the link, but actually the link still exists, but its not clickable anymore. Note: change this CSS to your font-color:
```
.shop_attributes a[rel="tag"] {
pointer-events: none;
cursor: default;
color: #888;
}
``` |
273,720 | <p>I want to apply my valid custom admin bar color scheme to front-end toolbar.</p>
<p>I am using this code to do it:</p>
<pre><code>add_action(
'wp_enqueue_scripts',
function () {
wp_enqueue_style(
'color-admin-bar',
PATH_TO_CSS,
array( 'admin-bar' )
);
} );
</code></pre>
<p>However it causes some strange bugs.</p>
<p>For example, when I hover a button it is colored with deep blue which is ok. But when it loses hover for 1 second it changes back to original color cheme (black background and blue text color).</p>
<p><a href="https://i.stack.imgur.com/VxiZy.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/VxiZy.png" alt="enter image description here"></a></p>
<p><a href="https://i.stack.imgur.com/zfLAo.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/zfLAo.png" alt="enter image description here"></a></p>
<p>I guess this is happening because of the default admin bar stylesheet:</p>
<pre><code><link rel='stylesheet' id='admin-bar-css' href='http://neuralnet.info.loc/wp-includes/css/admin-bar.min.css?ver=4.8' type='text/css' media='all' />
</code></pre>
<p>But I can't turn it off because whole toolbar layout gets broken.</p>
<p>So how to properly replace admin bar color scheme in front-end?</p>
<p><strong>UPD</strong></p>
<p>I did look in admin-bar.css and it seems that it is a bit different from back-end admin bar...</p>
| [
{
"answer_id": 273724,
"author": "Chris Cox",
"author_id": 1718,
"author_profile": "https://wordpress.stackexchange.com/users/1718",
"pm_score": -1,
"selected": false,
"text": "<p><a href=\"https://css-tricks.com/forums/topic/styling-wordpress-admin-bar/\" rel=\"nofollow noreferrer\">This might be useful to you</a>. The Admin Bar has some fairly specific CSS because it has to ensure that it's not accidentally overridden by theme CSS, which is why the post I linked makes heavy use of <code>!important</code>.</p>\n\n<p>When deliberately trying to override it you need to be more specific and cover each of the states an element has styled by default otherwise it will fall back to whatever the default styles are.</p>\n"
},
{
"answer_id": 273732,
"author": "Max Yudin",
"author_id": 11761,
"author_profile": "https://wordpress.stackexchange.com/users/11761",
"pm_score": 1,
"selected": true,
"text": "<p>You make it the wrong way.</p>\n\n<p>First, you do double work. Enqueue inside enqueue. You don't need <code>wp_enqueue_scripts()</code>:</p>\n\n<pre><code>wp_enqueue_style(\n 'color-admin-bar',\n PATH_TO_CSS,\n array( 'admin-bar' )\n);\n</code></pre>\n\n<p>Second. Don't use anonymous functions with WordPress Actions. Once-for-all-time is OK, but while the project is growing up you can collide with the inability to dequeue that style when you'll want to.</p>\n\n<p>The solution.</p>\n\n<p>Make a copy of the <code>admin-bar.css</code> and correct it to fit your needs. Then minimize it using any tool you can google for (optionally).</p>\n\n<p>Dequeue the original admin bar: </p>\n\n<pre><code><?php\nadd_action('admin_init', 'my_remove_admin_bar');\nfunction my_remove_admin_bar() {\n wp_dequeue_style('admin-bar')\n}\n</code></pre>\n\n<p>And enqueue your new-laid <code>my-admin-bar.css</code></p>\n\n<p>Slight hitch. You can face the problem when the whole admin bar gets updated to the new look with the new WordPress version.</p>\n"
}
]
| 2017/07/18 | [
"https://wordpress.stackexchange.com/questions/273720",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/109919/"
]
| I want to apply my valid custom admin bar color scheme to front-end toolbar.
I am using this code to do it:
```
add_action(
'wp_enqueue_scripts',
function () {
wp_enqueue_style(
'color-admin-bar',
PATH_TO_CSS,
array( 'admin-bar' )
);
} );
```
However it causes some strange bugs.
For example, when I hover a button it is colored with deep blue which is ok. But when it loses hover for 1 second it changes back to original color cheme (black background and blue text color).
[](https://i.stack.imgur.com/VxiZy.png)
[](https://i.stack.imgur.com/zfLAo.png)
I guess this is happening because of the default admin bar stylesheet:
```
<link rel='stylesheet' id='admin-bar-css' href='http://neuralnet.info.loc/wp-includes/css/admin-bar.min.css?ver=4.8' type='text/css' media='all' />
```
But I can't turn it off because whole toolbar layout gets broken.
So how to properly replace admin bar color scheme in front-end?
**UPD**
I did look in admin-bar.css and it seems that it is a bit different from back-end admin bar... | You make it the wrong way.
First, you do double work. Enqueue inside enqueue. You don't need `wp_enqueue_scripts()`:
```
wp_enqueue_style(
'color-admin-bar',
PATH_TO_CSS,
array( 'admin-bar' )
);
```
Second. Don't use anonymous functions with WordPress Actions. Once-for-all-time is OK, but while the project is growing up you can collide with the inability to dequeue that style when you'll want to.
The solution.
Make a copy of the `admin-bar.css` and correct it to fit your needs. Then minimize it using any tool you can google for (optionally).
Dequeue the original admin bar:
```
<?php
add_action('admin_init', 'my_remove_admin_bar');
function my_remove_admin_bar() {
wp_dequeue_style('admin-bar')
}
```
And enqueue your new-laid `my-admin-bar.css`
Slight hitch. You can face the problem when the whole admin bar gets updated to the new look with the new WordPress version. |
273,734 | <p>When I change <code>WP_PLUGIN_DIR</code> example:</p>
<pre><code>define( 'WP_PLUGIN_DIR', $_SERVER['DOCUMENT_ROOT'] . '/../wp-content/renamefolder' );
</code></pre>
<p>All plugins are shown and I can activate them.
<a href="https://i.stack.imgur.com/z4naU.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/z4naU.png" alt="enter image description here"></a> </p>
<p>But with TinyMCE Advanced when I wrote post, alert message shows
<a href="https://i.stack.imgur.com/vEV1Q.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vEV1Q.png" alt="enter image description here"></a></p>
<blockquote>
<p>Failed to load plugin: insertdatetime from url ../../wp-content/plugins/tinymce-advanced/mce/insertdatetime/plugin.min.js</p>
</blockquote>
<p>How to change code in <code>tinymce-advanced.php</code> or how to fix it?</p>
| [
{
"answer_id": 273751,
"author": "Rarst",
"author_id": 847,
"author_profile": "https://wordpress.stackexchange.com/users/847",
"pm_score": 1,
"selected": true,
"text": "<p><code>WP_PLUGIN_DIR</code> customizes the location of files in filesystem.</p>\n\n<p>Most likely you <em>also</em> need to customize <code>WP_PLUGIN_URL</code>, which customizes client–facing URL location. If you omit this one, WP will decide it based on <code>WP_CONTENT_URL</code>, which might not at all point to your new location.</p>\n\n<p>Another possibility is that plugin/code in question simply <em>cannot</em> handle a custom location. Generally this shouldn't happen under a normal WP API usage and such should be reported to developers as a possible bug.</p>\n"
},
{
"answer_id": 326724,
"author": "Chris",
"author_id": 159896,
"author_profile": "https://wordpress.stackexchange.com/users/159896",
"pm_score": -1,
"selected": false,
"text": "<p>I had the same problem an copied the en.js to de.js and voila - it works. </p>\n\n<p>for some reason tinymce seams to ignore the language and defaults to en</p>\n"
}
]
| 2017/07/18 | [
"https://wordpress.stackexchange.com/questions/273734",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/123978/"
]
| When I change `WP_PLUGIN_DIR` example:
```
define( 'WP_PLUGIN_DIR', $_SERVER['DOCUMENT_ROOT'] . '/../wp-content/renamefolder' );
```
All plugins are shown and I can activate them.
[](https://i.stack.imgur.com/z4naU.png)
But with TinyMCE Advanced when I wrote post, alert message shows
[](https://i.stack.imgur.com/vEV1Q.png)
>
> Failed to load plugin: insertdatetime from url ../../wp-content/plugins/tinymce-advanced/mce/insertdatetime/plugin.min.js
>
>
>
How to change code in `tinymce-advanced.php` or how to fix it? | `WP_PLUGIN_DIR` customizes the location of files in filesystem.
Most likely you *also* need to customize `WP_PLUGIN_URL`, which customizes client–facing URL location. If you omit this one, WP will decide it based on `WP_CONTENT_URL`, which might not at all point to your new location.
Another possibility is that plugin/code in question simply *cannot* handle a custom location. Generally this shouldn't happen under a normal WP API usage and such should be reported to developers as a possible bug. |
273,765 | <p>I made a large-scale research. But there are no anything what I want. I want to style my options page in a static style file. How can I do that?</p>
<p><strong>Sources</strong></p>
<pre><code>/*
*Create A Simple Theme Options Panel
*Exit if accessed directly
*/
if (!defined('ABSPATH')){
exit;
}
// Start Class
if ( ! class_exists('Azura_Theme_Options')){
class Azura_Theme_Options{
public function __construct(){
// We only need to register the admin panel on the back-end
if (is_admin()){
add_action('admin_menu', array( 'Azura_Theme_Options', 'add_admin_menu'));
add_action('admin_init', array( 'Azura_Theme_Options', 'register_settings'));
}
}
public static function get_theme_options() {
return get_option('theme_options');
}
public static function get_theme_option($id) {
$options = self::get_theme_options();
if (isset($options[$id])){
return $options[$id];
}
}
// Add sub menu page
public static function add_admin_menu(){
add_menu_page(
esc_html__('Azura Panel', 'text-domain'),
esc_html__('Azura Panel', 'text-domain'),
'manage_options',
'azura-panel',
array('Azura_Theme_Options', 'create_admin_page')
);
}
/**
* Register a setting and its sanitization callback.
* We are only registering 1 setting so we can store all options in a single option as
* an array. You could, however, register a new setting for each option
*/
public static function register_settings(){
register_setting('theme_options', 'theme_options', array( 'Azura_Theme_Options', 'sanitize'));
}
// Sanitization callback
public static function sanitize($options){
// If we have options lets sanitize them
if ($options){
// Input
if (!empty($options['site_name'])){
$options['site_name'] = sanitize_text_field( $options['site_name'] );
}else{
unset($options['site_name']); // Remove from options if empty
}
// Select
if (!empty($options['select_example'])){
$options['select_example'] = sanitize_text_field( $options['select_example'] );
}
}
// Return sanitized options
return $options;
}
/**
* Settings page output
*/
public static function create_admin_page(){ ?>
<div class="wrap">
<h1><?php esc_html_e('Tema Ayarları', 'text-domain'); ?></h1>
<form method="post" action="options.php">
<?php settings_fields('theme_options'); ?>
<table class="form-table wpex-custom-admin-login-table">
<?php // Text input example ?>
<tr valign="top">
<th scope="row"><?php esc_html_e('Başlık', 'text-domain'); ?></th>
<td>
<?php $value = self::get_theme_option('site_name'); ?>
<input type="text" name="theme_options[site_name]" value="<?php echo esc_attr($value); ?>">
</td>
</tr>
<tr valign="top">
<th scope="row"><?php esc_html_e('Açıklama', 'text-domain'); ?></th>
<td>
<?php $value = self::get_theme_option('site_desc'); ?>
<input type="text" name="theme_options[site_desc]" value="<?php echo esc_attr($value); ?>">
</td>
</tr>
<tr valign="top">
<th scope="row"><?php esc_html_e('Buton', 'text-domain'); ?></th>
<td>
<?php $value = self::get_theme_option('top_header_btn'); ?>
<input type="text" name="theme_options[top_header_btn]" value="<?php echo esc_attr($value); ?>">
</td>
</tr>
<tr valign="top">
<th scope="row"><?php esc_html_e('Buton Link', 'text-domain'); ?></th>
<td>
<?php $value = self::get_theme_option('top_header_btn_link'); ?>
<input type="text" name="theme_options[top_header_btn_link]" value="<?php echo esc_attr($value); ?>">
</td>
</tr>
</table>
<?php submit_button(); ?>
</form>
</div><!-- .wrap -->
<?php }
}
}
new Azura_Theme_Options();
// Helper function to use in your theme to return a theme option value
function myprefix_get_theme_option( $id = '' ) {
return Azura_Theme_Options::get_theme_option( $id );
}
</code></pre>
| [
{
"answer_id": 273767,
"author": "Chris Cox",
"author_id": 1718,
"author_profile": "https://wordpress.stackexchange.com/users/1718",
"pm_score": -1,
"selected": false,
"text": "<p>Give your HTML elements existing classes from the WP admin CSS and they'll inherit styles consistent with the rest of the Dashboard. Elaborately styling theme or plugin UI to clash with the rest of the application is an abomination.</p>\n"
},
{
"answer_id": 273776,
"author": "Rian",
"author_id": 124107,
"author_profile": "https://wordpress.stackexchange.com/users/124107",
"pm_score": 0,
"selected": false,
"text": "<p>In your construct function you also need to enqueue a custom stylesheet that will house the CSS to style up your theme options.</p>\n\n<p>A simplified example would look like this:</p>\n\n<pre><code>function admin_style() {\n wp_enqueue_style( 'theme-options-style', get_template_directory_uri().'styles/theme-options-style.css');\n}\nadd_action('admin_enqueue_scripts', 'admin_style');\n</code></pre>\n"
},
{
"answer_id": 273792,
"author": "rudtek",
"author_id": 77767,
"author_profile": "https://wordpress.stackexchange.com/users/77767",
"pm_score": 0,
"selected": false,
"text": "<p>@Rian's answer is good if you're placing that code in a theme. If you're going to be using it in a plugin then enqueue with:</p>\n\n<p><strong>from the codex:</strong></p>\n\n<pre><code>function load_custom_wp_admin_style($hook) {\n // Load only on ?page=mypluginname\n if($hook != 'toplevel_page_mypluginname') {\n return;\n }\n wp_enqueue_style( 'custom-admin_css', plugins_url('admin-style.css', __FILE__) );\n}\nadd_action( 'admin_enqueue_scripts', 'load_custom_wp_admin_style' );\n</code></pre>\n\n<p>This will return the full URL to custom.css, such as example.com/wp-content/plugins/myplugin/custom-admin_css. </p>\n\n<p>If you are unsure what your $hook name is .. use this to determine your hookname. Put the code after the { from the function</p>\n\n<pre><code>wp_die($hook);\n</code></pre>\n\n<p>(Alternately just look at the last portion of your url when you're on your admin page)</p>\n\n<p>This code ensures you don't load the css on every page of your site; but only on the admin page of your plugin.</p>\n"
}
]
| 2017/07/18 | [
"https://wordpress.stackexchange.com/questions/273765",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/124103/"
]
| I made a large-scale research. But there are no anything what I want. I want to style my options page in a static style file. How can I do that?
**Sources**
```
/*
*Create A Simple Theme Options Panel
*Exit if accessed directly
*/
if (!defined('ABSPATH')){
exit;
}
// Start Class
if ( ! class_exists('Azura_Theme_Options')){
class Azura_Theme_Options{
public function __construct(){
// We only need to register the admin panel on the back-end
if (is_admin()){
add_action('admin_menu', array( 'Azura_Theme_Options', 'add_admin_menu'));
add_action('admin_init', array( 'Azura_Theme_Options', 'register_settings'));
}
}
public static function get_theme_options() {
return get_option('theme_options');
}
public static function get_theme_option($id) {
$options = self::get_theme_options();
if (isset($options[$id])){
return $options[$id];
}
}
// Add sub menu page
public static function add_admin_menu(){
add_menu_page(
esc_html__('Azura Panel', 'text-domain'),
esc_html__('Azura Panel', 'text-domain'),
'manage_options',
'azura-panel',
array('Azura_Theme_Options', 'create_admin_page')
);
}
/**
* Register a setting and its sanitization callback.
* We are only registering 1 setting so we can store all options in a single option as
* an array. You could, however, register a new setting for each option
*/
public static function register_settings(){
register_setting('theme_options', 'theme_options', array( 'Azura_Theme_Options', 'sanitize'));
}
// Sanitization callback
public static function sanitize($options){
// If we have options lets sanitize them
if ($options){
// Input
if (!empty($options['site_name'])){
$options['site_name'] = sanitize_text_field( $options['site_name'] );
}else{
unset($options['site_name']); // Remove from options if empty
}
// Select
if (!empty($options['select_example'])){
$options['select_example'] = sanitize_text_field( $options['select_example'] );
}
}
// Return sanitized options
return $options;
}
/**
* Settings page output
*/
public static function create_admin_page(){ ?>
<div class="wrap">
<h1><?php esc_html_e('Tema Ayarları', 'text-domain'); ?></h1>
<form method="post" action="options.php">
<?php settings_fields('theme_options'); ?>
<table class="form-table wpex-custom-admin-login-table">
<?php // Text input example ?>
<tr valign="top">
<th scope="row"><?php esc_html_e('Başlık', 'text-domain'); ?></th>
<td>
<?php $value = self::get_theme_option('site_name'); ?>
<input type="text" name="theme_options[site_name]" value="<?php echo esc_attr($value); ?>">
</td>
</tr>
<tr valign="top">
<th scope="row"><?php esc_html_e('Açıklama', 'text-domain'); ?></th>
<td>
<?php $value = self::get_theme_option('site_desc'); ?>
<input type="text" name="theme_options[site_desc]" value="<?php echo esc_attr($value); ?>">
</td>
</tr>
<tr valign="top">
<th scope="row"><?php esc_html_e('Buton', 'text-domain'); ?></th>
<td>
<?php $value = self::get_theme_option('top_header_btn'); ?>
<input type="text" name="theme_options[top_header_btn]" value="<?php echo esc_attr($value); ?>">
</td>
</tr>
<tr valign="top">
<th scope="row"><?php esc_html_e('Buton Link', 'text-domain'); ?></th>
<td>
<?php $value = self::get_theme_option('top_header_btn_link'); ?>
<input type="text" name="theme_options[top_header_btn_link]" value="<?php echo esc_attr($value); ?>">
</td>
</tr>
</table>
<?php submit_button(); ?>
</form>
</div><!-- .wrap -->
<?php }
}
}
new Azura_Theme_Options();
// Helper function to use in your theme to return a theme option value
function myprefix_get_theme_option( $id = '' ) {
return Azura_Theme_Options::get_theme_option( $id );
}
``` | In your construct function you also need to enqueue a custom stylesheet that will house the CSS to style up your theme options.
A simplified example would look like this:
```
function admin_style() {
wp_enqueue_style( 'theme-options-style', get_template_directory_uri().'styles/theme-options-style.css');
}
add_action('admin_enqueue_scripts', 'admin_style');
``` |
273,773 | <p>How add, update and retrieve user meta fields with the wp api? I added a function to add a meta field phonenumber to a user. Is a function like this necessary to add meta values to the meta object? The function doesn't add the field to the meta object in the API response but adds it as a new field.</p>
<p>The function i have right now:</p>
<pre><code><?php
function portal_add_user_field() {
register_rest_field( 'user', 'phonenumber',
array(
'get_callback' => function( $user, $field_name, $request ) {
return get_user_meta( $user[ 'id' ], $field_name, true );
},
'update_callback' => function( $user, $meta_key, $meta_value, $prev_value ) {
$ret = update_user_meta( array( $user, $meta_key, $meta_value );
return true;
},
'schema' => array(
'description' => __( 'user phonenumber' ),
'type' => 'string'
),
)
);
}
add_action( 'rest_api_init', 'portal_add_user_field' );
</code></pre>
<p>I also tried to add the phone number field to the user meta with ajax without a extra function like this: (this doesn't save the phone number field)</p>
<pre><code>updateUser: function () {
var data = {
username: this.username,
email: this.email,
first_name: this.firstname,
last_name: this.lastname,
meta: {
phonenumber: this.phonenumber
}
};
console.log(data);
$.ajax({
method: "POST",
url: wpApiSettings.current_domain + '/wp-json/wp/v2/users/' + wpApiSettings.current_user.ID,
data: data,
beforeSend: function ( xhr ) {
xhr.setRequestHeader( 'X-WP-Nonce', wpApiSettings.nonce );
}
})
.done( $.proxy( function() {
alert('Account saved');
}, this ))
.fail( $.proxy( function( response ) {
alert('something went wrong');
}, this ));
</code></pre>
| [
{
"answer_id": 273875,
"author": "Maarten Heideman",
"author_id": 54693,
"author_profile": "https://wordpress.stackexchange.com/users/54693",
"pm_score": 2,
"selected": true,
"text": "<p>found it, first yes for meta data on a user you'll need a custom function like this:</p>\n\n<pre><code><?php\nfunction portal_add_user_field() {\n register_rest_field( 'user', 'userfields',\n array(\n 'get_callback' => function( $user, $field_name, $request ) {\n return get_user_meta( $user[ 'id' ], $field_name, true );\n },\n 'update_callback' => function($meta_value ) {\n $havemetafield = get_user_meta(1, 'userfields', false);\n if ($havemetafield) {\n $ret = update_user_meta(1, 'userfields', $meta_value );\n return true;\n } else {\n $ret = add_user_meta( 1, 'userfields', $meta_value ,true );\n return true;\n }\n },\n 'schema' => null\n )\n );\n}\nadd_action( 'rest_api_init', 'portal_add_user_field', 10, 2 );\n</code></pre>\n\n<p>?></p>\n\n<p>after that with ajax send it like this:</p>\n\n<pre><code>updateUser: function () {\n var data = {\n userfields: {\n somefield: this.somefield,\n somefield2: this.somefield2\n }\n };\n console.log(data);\n $.ajax({\n method: \"POST\",\n url: wpApiSettings.current_domain + '/wp-json/wp/v2/users/' + wpApiSettings.current_user.ID,\n data: data,\n beforeSend: function ( xhr ) {\n xhr.setRequestHeader( 'X-WP-Nonce', wpApiSettings.nonce );\n }\n })\n .done( $.proxy( function() {\n alert('Account saved');\n }, this ))\n .fail( $.proxy( function( response ) {\n alert('something went wrong');\n }, this ));\n }\n</code></pre>\n"
},
{
"answer_id": 278847,
"author": "Guilherme Sampaio",
"author_id": 108115,
"author_profile": "https://wordpress.stackexchange.com/users/108115",
"pm_score": 3,
"selected": false,
"text": "<p>I have managed to do this with hooking into <code>rest_insert_user</code>.\nI send an array like this: </p>\n\n<pre><code>var data = {\n first_name: user.first_name,\n last_name: user.last_name,\n name: user.display_name,\n email: user.email,\n description: user.description,\n meta: {\n 'wpcf-phone': user.phone,\n 'wpcf-institution': user.institution,\n 'wpcf-birthday': Math.round(new Date(user.birthday).getTime()/1000)\n }\n };\n</code></pre>\n\n<p>And treat only the meta data through the hook as this: </p>\n\n<pre><code>function aa_user_update($user, $request, $create)\n{\n if ($request['meta']) {\n $user_id = $user->ID;\n foreach ($request['meta'] as $key => $value) {\n update_user_meta( $user_id, $key, $value );\n }\n }\n}\nadd_action( 'rest_insert_user', 'aa_user_update', 12, 3 );\n</code></pre>\n\n<p>The ordinary fields of the user are updated normally by the API.</p>\n"
}
]
| 2017/07/18 | [
"https://wordpress.stackexchange.com/questions/273773",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/54693/"
]
| How add, update and retrieve user meta fields with the wp api? I added a function to add a meta field phonenumber to a user. Is a function like this necessary to add meta values to the meta object? The function doesn't add the field to the meta object in the API response but adds it as a new field.
The function i have right now:
```
<?php
function portal_add_user_field() {
register_rest_field( 'user', 'phonenumber',
array(
'get_callback' => function( $user, $field_name, $request ) {
return get_user_meta( $user[ 'id' ], $field_name, true );
},
'update_callback' => function( $user, $meta_key, $meta_value, $prev_value ) {
$ret = update_user_meta( array( $user, $meta_key, $meta_value );
return true;
},
'schema' => array(
'description' => __( 'user phonenumber' ),
'type' => 'string'
),
)
);
}
add_action( 'rest_api_init', 'portal_add_user_field' );
```
I also tried to add the phone number field to the user meta with ajax without a extra function like this: (this doesn't save the phone number field)
```
updateUser: function () {
var data = {
username: this.username,
email: this.email,
first_name: this.firstname,
last_name: this.lastname,
meta: {
phonenumber: this.phonenumber
}
};
console.log(data);
$.ajax({
method: "POST",
url: wpApiSettings.current_domain + '/wp-json/wp/v2/users/' + wpApiSettings.current_user.ID,
data: data,
beforeSend: function ( xhr ) {
xhr.setRequestHeader( 'X-WP-Nonce', wpApiSettings.nonce );
}
})
.done( $.proxy( function() {
alert('Account saved');
}, this ))
.fail( $.proxy( function( response ) {
alert('something went wrong');
}, this ));
``` | found it, first yes for meta data on a user you'll need a custom function like this:
```
<?php
function portal_add_user_field() {
register_rest_field( 'user', 'userfields',
array(
'get_callback' => function( $user, $field_name, $request ) {
return get_user_meta( $user[ 'id' ], $field_name, true );
},
'update_callback' => function($meta_value ) {
$havemetafield = get_user_meta(1, 'userfields', false);
if ($havemetafield) {
$ret = update_user_meta(1, 'userfields', $meta_value );
return true;
} else {
$ret = add_user_meta( 1, 'userfields', $meta_value ,true );
return true;
}
},
'schema' => null
)
);
}
add_action( 'rest_api_init', 'portal_add_user_field', 10, 2 );
```
?>
after that with ajax send it like this:
```
updateUser: function () {
var data = {
userfields: {
somefield: this.somefield,
somefield2: this.somefield2
}
};
console.log(data);
$.ajax({
method: "POST",
url: wpApiSettings.current_domain + '/wp-json/wp/v2/users/' + wpApiSettings.current_user.ID,
data: data,
beforeSend: function ( xhr ) {
xhr.setRequestHeader( 'X-WP-Nonce', wpApiSettings.nonce );
}
})
.done( $.proxy( function() {
alert('Account saved');
}, this ))
.fail( $.proxy( function( response ) {
alert('something went wrong');
}, this ));
}
``` |
273,790 | <p>I am trying to use $wpdb object to get results from a custom table and I get an error when I echo the result:</p>
<pre><code>Notice: Undefined property: stdClass::$category in...
</code></pre>
<p>Here is the PHP code:</p>
<pre><code>global $wpdb;
$prodCat = $wpdb->get_results(
"SELECT * FROM product_category" , OBJECT_K);
foreach ( $prodCat as $row ){
echo $row->category-name;
}
</code></pre>
<p>Any help is appreciated.</p>
| [
{
"answer_id": 273875,
"author": "Maarten Heideman",
"author_id": 54693,
"author_profile": "https://wordpress.stackexchange.com/users/54693",
"pm_score": 2,
"selected": true,
"text": "<p>found it, first yes for meta data on a user you'll need a custom function like this:</p>\n\n<pre><code><?php\nfunction portal_add_user_field() {\n register_rest_field( 'user', 'userfields',\n array(\n 'get_callback' => function( $user, $field_name, $request ) {\n return get_user_meta( $user[ 'id' ], $field_name, true );\n },\n 'update_callback' => function($meta_value ) {\n $havemetafield = get_user_meta(1, 'userfields', false);\n if ($havemetafield) {\n $ret = update_user_meta(1, 'userfields', $meta_value );\n return true;\n } else {\n $ret = add_user_meta( 1, 'userfields', $meta_value ,true );\n return true;\n }\n },\n 'schema' => null\n )\n );\n}\nadd_action( 'rest_api_init', 'portal_add_user_field', 10, 2 );\n</code></pre>\n\n<p>?></p>\n\n<p>after that with ajax send it like this:</p>\n\n<pre><code>updateUser: function () {\n var data = {\n userfields: {\n somefield: this.somefield,\n somefield2: this.somefield2\n }\n };\n console.log(data);\n $.ajax({\n method: \"POST\",\n url: wpApiSettings.current_domain + '/wp-json/wp/v2/users/' + wpApiSettings.current_user.ID,\n data: data,\n beforeSend: function ( xhr ) {\n xhr.setRequestHeader( 'X-WP-Nonce', wpApiSettings.nonce );\n }\n })\n .done( $.proxy( function() {\n alert('Account saved');\n }, this ))\n .fail( $.proxy( function( response ) {\n alert('something went wrong');\n }, this ));\n }\n</code></pre>\n"
},
{
"answer_id": 278847,
"author": "Guilherme Sampaio",
"author_id": 108115,
"author_profile": "https://wordpress.stackexchange.com/users/108115",
"pm_score": 3,
"selected": false,
"text": "<p>I have managed to do this with hooking into <code>rest_insert_user</code>.\nI send an array like this: </p>\n\n<pre><code>var data = {\n first_name: user.first_name,\n last_name: user.last_name,\n name: user.display_name,\n email: user.email,\n description: user.description,\n meta: {\n 'wpcf-phone': user.phone,\n 'wpcf-institution': user.institution,\n 'wpcf-birthday': Math.round(new Date(user.birthday).getTime()/1000)\n }\n };\n</code></pre>\n\n<p>And treat only the meta data through the hook as this: </p>\n\n<pre><code>function aa_user_update($user, $request, $create)\n{\n if ($request['meta']) {\n $user_id = $user->ID;\n foreach ($request['meta'] as $key => $value) {\n update_user_meta( $user_id, $key, $value );\n }\n }\n}\nadd_action( 'rest_insert_user', 'aa_user_update', 12, 3 );\n</code></pre>\n\n<p>The ordinary fields of the user are updated normally by the API.</p>\n"
}
]
| 2017/07/18 | [
"https://wordpress.stackexchange.com/questions/273790",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/45250/"
]
| I am trying to use $wpdb object to get results from a custom table and I get an error when I echo the result:
```
Notice: Undefined property: stdClass::$category in...
```
Here is the PHP code:
```
global $wpdb;
$prodCat = $wpdb->get_results(
"SELECT * FROM product_category" , OBJECT_K);
foreach ( $prodCat as $row ){
echo $row->category-name;
}
```
Any help is appreciated. | found it, first yes for meta data on a user you'll need a custom function like this:
```
<?php
function portal_add_user_field() {
register_rest_field( 'user', 'userfields',
array(
'get_callback' => function( $user, $field_name, $request ) {
return get_user_meta( $user[ 'id' ], $field_name, true );
},
'update_callback' => function($meta_value ) {
$havemetafield = get_user_meta(1, 'userfields', false);
if ($havemetafield) {
$ret = update_user_meta(1, 'userfields', $meta_value );
return true;
} else {
$ret = add_user_meta( 1, 'userfields', $meta_value ,true );
return true;
}
},
'schema' => null
)
);
}
add_action( 'rest_api_init', 'portal_add_user_field', 10, 2 );
```
?>
after that with ajax send it like this:
```
updateUser: function () {
var data = {
userfields: {
somefield: this.somefield,
somefield2: this.somefield2
}
};
console.log(data);
$.ajax({
method: "POST",
url: wpApiSettings.current_domain + '/wp-json/wp/v2/users/' + wpApiSettings.current_user.ID,
data: data,
beforeSend: function ( xhr ) {
xhr.setRequestHeader( 'X-WP-Nonce', wpApiSettings.nonce );
}
})
.done( $.proxy( function() {
alert('Account saved');
}, this ))
.fail( $.proxy( function( response ) {
alert('something went wrong');
}, this ));
}
``` |
273,801 | <p>I've got a local install of WP and I've copied my live site's uploads dir to the proper spot in wp-content, but Media Library isn't showing a single image.</p>
<p>I've recursively set uploads and subsequent dirs to 755, that didn't fix it. I checked the upload_path in wp_options and it's blank like it is on the live server.</p>
<p>FYI, the import of posts I did came from a multi-site install where the live site is.</p>
<p>I'm at a loss as to where I can fix this missing link to the uploads folder. Posts are seeing the images in the uploads and rendering fine with the local dev url path in the images.</p>
<p>Thanks for any guidance!</p>
<p><a href="https://i.stack.imgur.com/ifxLM.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ifxLM.png" alt="my empty media library on local"></a></p>
<p><a href="https://i.stack.imgur.com/icQFi.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/icQFi.png" alt="my folder structure for the local install"></a></p>
| [
{
"answer_id": 273875,
"author": "Maarten Heideman",
"author_id": 54693,
"author_profile": "https://wordpress.stackexchange.com/users/54693",
"pm_score": 2,
"selected": true,
"text": "<p>found it, first yes for meta data on a user you'll need a custom function like this:</p>\n\n<pre><code><?php\nfunction portal_add_user_field() {\n register_rest_field( 'user', 'userfields',\n array(\n 'get_callback' => function( $user, $field_name, $request ) {\n return get_user_meta( $user[ 'id' ], $field_name, true );\n },\n 'update_callback' => function($meta_value ) {\n $havemetafield = get_user_meta(1, 'userfields', false);\n if ($havemetafield) {\n $ret = update_user_meta(1, 'userfields', $meta_value );\n return true;\n } else {\n $ret = add_user_meta( 1, 'userfields', $meta_value ,true );\n return true;\n }\n },\n 'schema' => null\n )\n );\n}\nadd_action( 'rest_api_init', 'portal_add_user_field', 10, 2 );\n</code></pre>\n\n<p>?></p>\n\n<p>after that with ajax send it like this:</p>\n\n<pre><code>updateUser: function () {\n var data = {\n userfields: {\n somefield: this.somefield,\n somefield2: this.somefield2\n }\n };\n console.log(data);\n $.ajax({\n method: \"POST\",\n url: wpApiSettings.current_domain + '/wp-json/wp/v2/users/' + wpApiSettings.current_user.ID,\n data: data,\n beforeSend: function ( xhr ) {\n xhr.setRequestHeader( 'X-WP-Nonce', wpApiSettings.nonce );\n }\n })\n .done( $.proxy( function() {\n alert('Account saved');\n }, this ))\n .fail( $.proxy( function( response ) {\n alert('something went wrong');\n }, this ));\n }\n</code></pre>\n"
},
{
"answer_id": 278847,
"author": "Guilherme Sampaio",
"author_id": 108115,
"author_profile": "https://wordpress.stackexchange.com/users/108115",
"pm_score": 3,
"selected": false,
"text": "<p>I have managed to do this with hooking into <code>rest_insert_user</code>.\nI send an array like this: </p>\n\n<pre><code>var data = {\n first_name: user.first_name,\n last_name: user.last_name,\n name: user.display_name,\n email: user.email,\n description: user.description,\n meta: {\n 'wpcf-phone': user.phone,\n 'wpcf-institution': user.institution,\n 'wpcf-birthday': Math.round(new Date(user.birthday).getTime()/1000)\n }\n };\n</code></pre>\n\n<p>And treat only the meta data through the hook as this: </p>\n\n<pre><code>function aa_user_update($user, $request, $create)\n{\n if ($request['meta']) {\n $user_id = $user->ID;\n foreach ($request['meta'] as $key => $value) {\n update_user_meta( $user_id, $key, $value );\n }\n }\n}\nadd_action( 'rest_insert_user', 'aa_user_update', 12, 3 );\n</code></pre>\n\n<p>The ordinary fields of the user are updated normally by the API.</p>\n"
}
]
| 2017/07/18 | [
"https://wordpress.stackexchange.com/questions/273801",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/124126/"
]
| I've got a local install of WP and I've copied my live site's uploads dir to the proper spot in wp-content, but Media Library isn't showing a single image.
I've recursively set uploads and subsequent dirs to 755, that didn't fix it. I checked the upload\_path in wp\_options and it's blank like it is on the live server.
FYI, the import of posts I did came from a multi-site install where the live site is.
I'm at a loss as to where I can fix this missing link to the uploads folder. Posts are seeing the images in the uploads and rendering fine with the local dev url path in the images.
Thanks for any guidance!
[](https://i.stack.imgur.com/ifxLM.png)
[](https://i.stack.imgur.com/icQFi.png) | found it, first yes for meta data on a user you'll need a custom function like this:
```
<?php
function portal_add_user_field() {
register_rest_field( 'user', 'userfields',
array(
'get_callback' => function( $user, $field_name, $request ) {
return get_user_meta( $user[ 'id' ], $field_name, true );
},
'update_callback' => function($meta_value ) {
$havemetafield = get_user_meta(1, 'userfields', false);
if ($havemetafield) {
$ret = update_user_meta(1, 'userfields', $meta_value );
return true;
} else {
$ret = add_user_meta( 1, 'userfields', $meta_value ,true );
return true;
}
},
'schema' => null
)
);
}
add_action( 'rest_api_init', 'portal_add_user_field', 10, 2 );
```
?>
after that with ajax send it like this:
```
updateUser: function () {
var data = {
userfields: {
somefield: this.somefield,
somefield2: this.somefield2
}
};
console.log(data);
$.ajax({
method: "POST",
url: wpApiSettings.current_domain + '/wp-json/wp/v2/users/' + wpApiSettings.current_user.ID,
data: data,
beforeSend: function ( xhr ) {
xhr.setRequestHeader( 'X-WP-Nonce', wpApiSettings.nonce );
}
})
.done( $.proxy( function() {
alert('Account saved');
}, this ))
.fail( $.proxy( function( response ) {
alert('something went wrong');
}, this ));
}
``` |
273,805 | <p>When I write answers for questions on WPSE, or when I want to try a piece of short and simple code, I need a place to quickly test the results without actually doing permanent change to any file. </p>
<p>For example, let's say I want to test this:</p>
<pre><code><?php echo get_post_meta(); ?>
</code></pre>
<p>I can put this at the end of my <code>single.php</code> and open a single post to check the results, but then each time I need to modify my templates and then revert the changes.</p>
<p>Is there any way to test WordPress codes quickly? </p>
<p>A method that crossed my mind was to create a php file and then load WordPress by using <code>require_once( dirname(__FILE__) . '/wp-load.php' );</code> for development purposes. However I'm not sure if it's the best way to do this.</p>
| [
{
"answer_id": 273807,
"author": "kero",
"author_id": 108180,
"author_profile": "https://wordpress.stackexchange.com/users/108180",
"pm_score": 1,
"selected": false,
"text": "<p>The answer is quite simple: test your code in WordPress environment.</p>\n\n<p>I have a standard WordPress instance running (and if I don't, I create one via <a href=\"https://easyengine.io/\" rel=\"nofollow noreferrer\">EasyEngine</a>) in my local environment with a custom _<a href=\"https://github.com/Automattic/_s\" rel=\"nofollow noreferrer\">s</a> child theme and a custom plugin (<a href=\"https://github.com/MNKYlab/wordpress-demoplugin\" rel=\"nofollow noreferrer\">this one</a>, though I realize the repo needs to be updated) . Both are Git repositories, so every change I make can be <code>diff</code>ed and in the end it is simple to undo.</p>\n\n<p><a href=\"https://wp-cli.org/\" rel=\"nofollow noreferrer\">WP-CLI</a> makes this even simpler to maintain:</p>\n\n<pre><code>$ wp core update && wp theme update --all && wp plugin update --all\n</code></pre>\n"
},
{
"answer_id": 273830,
"author": "Digvijayad",
"author_id": 118765,
"author_profile": "https://wordpress.stackexchange.com/users/118765",
"pm_score": 3,
"selected": true,
"text": "<p>I actually use free online development environments to test, such as <a href=\"http://c9.io\" rel=\"nofollow noreferrer\">c9</a>. It allows very quick installation and setup of wordpress. You can easily try different plugins/codes without endangering your files.</p>\n\n<p>Moreover, if you mess any thing up you can always delete that installation and create a new one. </p>\n\n<p>Another great feature is the cloning of the environment. So if you are about to work on something dangerous. You can clone your environment prior to it and work freely on the new plugins/themes you are working on. </p>\n\n<p>It provides a very nice text editor with similar functions to sublime and great test environment. You can use command line just like any normal server. The only thing to keep in mind is that it is only a development environment. It does not support Production. </p>\n\n<p>Besides wordpress, it also provides other dev environment for many other languages. </p>\n\n<p><strong>Edit</strong></p>\n\n<p>Additional Tip: I keep a separate Wordpress installation in c9 with the <a href=\"https://wpcom-themes.svn.automattic.com/demo/theme-unit-test-data.xml\" rel=\"nofollow noreferrer\">unit test data</a> imported. Follow <a href=\"https://codex.wordpress.org/Theme_Unit_Test\" rel=\"nofollow noreferrer\">here</a> for more instructions and the benefit for having test data. </p>\n\n<p>This allows me to quickly test someone's code or a new plugin without having to mess with my actual project. </p>\n\n<p>This is especially beneficial for <a href=\"https://wordpress.stackexchange.com\">stack</a> members.</p>\n\n<p><a href=\"https://i.stack.imgur.com/zpy5V.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/zpy5V.png\" alt=\"Image is from their official website\"></a></p>\n\n<p><strong>Edit 5/9/2018</strong></p>\n\n<p>As of July 14, 2016, Cloud9 is part of Amazon AWS. you can read the announcement of the c9's acquisition by AWS <a href=\"https://c9.io/announcement\" rel=\"nofollow noreferrer\">here</a>.</p>\n\n<p>Some of the benefits listed on the <a href=\"https://aws.amazon.com/cloud9/?origin=c9io\" rel=\"nofollow noreferrer\">official AWS Cloud9</a> are:</p>\n\n<ul>\n<li><p><strong>CODE WITH JUST A BROWSER</strong></p>\n\n<p><em>AWS Cloud9 gives you the flexibility to run your development environment on a managed Amazon EC2 instance or any existing Linux server that supports SSH</em></p></li>\n<li><p><strong>CODE TOGETHER IN REAL TIME</strong></p>\n\n<p><em>AWS Cloud9 makes collaborating on code easy. You can share your development environment with your team in just a few clicks and pair program together. While collaborating, your team members can see each other type in real time, and instantly chat with one another from within the IDE.</em></p></li>\n<li><p><strong>BUILD SERVERLESS APPLICATIONS WITH EASE</strong></p>\n\n<p><em>AWS Cloud9 makes it easy to write, run, and debug serverless application</em></p></li>\n<li><p><strong>DIRECT TERMINAL ACCESS TO AWS</strong></p>\n\n<p><em>AWS Cloud9 comes with a terminal that includes sudo privileges to the managed Amazon EC2 instance that is hosting your development environment and a preauthenticated AWS Command Line Interface.</em></p></li>\n<li><p><strong>START NEW PROJECTS QUICKLY</strong></p>\n\n<p><em>AWS Cloud9 makes it easy for you to start new projects. Cloud9’s development environment comes prepackaged with tooling for over 40 programming languages, including Node.js, JavaScript, Python, PHP, Ruby, Go, and C++.</em></p></li>\n</ul>\n"
}
]
| 2017/07/18 | [
"https://wordpress.stackexchange.com/questions/273805",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/94498/"
]
| When I write answers for questions on WPSE, or when I want to try a piece of short and simple code, I need a place to quickly test the results without actually doing permanent change to any file.
For example, let's say I want to test this:
```
<?php echo get_post_meta(); ?>
```
I can put this at the end of my `single.php` and open a single post to check the results, but then each time I need to modify my templates and then revert the changes.
Is there any way to test WordPress codes quickly?
A method that crossed my mind was to create a php file and then load WordPress by using `require_once( dirname(__FILE__) . '/wp-load.php' );` for development purposes. However I'm not sure if it's the best way to do this. | I actually use free online development environments to test, such as [c9](http://c9.io). It allows very quick installation and setup of wordpress. You can easily try different plugins/codes without endangering your files.
Moreover, if you mess any thing up you can always delete that installation and create a new one.
Another great feature is the cloning of the environment. So if you are about to work on something dangerous. You can clone your environment prior to it and work freely on the new plugins/themes you are working on.
It provides a very nice text editor with similar functions to sublime and great test environment. You can use command line just like any normal server. The only thing to keep in mind is that it is only a development environment. It does not support Production.
Besides wordpress, it also provides other dev environment for many other languages.
**Edit**
Additional Tip: I keep a separate Wordpress installation in c9 with the [unit test data](https://wpcom-themes.svn.automattic.com/demo/theme-unit-test-data.xml) imported. Follow [here](https://codex.wordpress.org/Theme_Unit_Test) for more instructions and the benefit for having test data.
This allows me to quickly test someone's code or a new plugin without having to mess with my actual project.
This is especially beneficial for [stack](https://wordpress.stackexchange.com) members.
[](https://i.stack.imgur.com/zpy5V.png)
**Edit 5/9/2018**
As of July 14, 2016, Cloud9 is part of Amazon AWS. you can read the announcement of the c9's acquisition by AWS [here](https://c9.io/announcement).
Some of the benefits listed on the [official AWS Cloud9](https://aws.amazon.com/cloud9/?origin=c9io) are:
* **CODE WITH JUST A BROWSER**
*AWS Cloud9 gives you the flexibility to run your development environment on a managed Amazon EC2 instance or any existing Linux server that supports SSH*
* **CODE TOGETHER IN REAL TIME**
*AWS Cloud9 makes collaborating on code easy. You can share your development environment with your team in just a few clicks and pair program together. While collaborating, your team members can see each other type in real time, and instantly chat with one another from within the IDE.*
* **BUILD SERVERLESS APPLICATIONS WITH EASE**
*AWS Cloud9 makes it easy to write, run, and debug serverless application*
* **DIRECT TERMINAL ACCESS TO AWS**
*AWS Cloud9 comes with a terminal that includes sudo privileges to the managed Amazon EC2 instance that is hosting your development environment and a preauthenticated AWS Command Line Interface.*
* **START NEW PROJECTS QUICKLY**
*AWS Cloud9 makes it easy for you to start new projects. Cloud9’s development environment comes prepackaged with tooling for over 40 programming languages, including Node.js, JavaScript, Python, PHP, Ruby, Go, and C++.* |
273,806 | <p>In my WordPress site, I created a <code>Singleton</code> inside a custom plugin I have, like this:</p>
<pre><code>class VBWpdb {
private $trace = array();
public static function get_instance() {
static $instance = null;
if(null === $instance) {
$instance = new static();
}
return $instance;
}
//...
</code></pre>
<p>So, I'm using <code>VBWpdb::get_instance()</code> in a lot of places of my code to populate <code>$trace</code> array (first var of the class). It works for the purpose of having a trace along my code and this static class is being the only instance during the plugin execution. I tested with arbitrary <code>var_dump</code>'s...</p>
<p>The problem is... I want to print that trace once my page is loaded and I'm doing this:</p>
<pre><code>add_action('wp_loaded', 'vb_dump_wpdb_trace');
function vb_dump_wpdb_trace() {
VBWpdb::get_instance()->dump();
}
</code></pre>
<p>It seems that this instance is not being created again, but <code>$trace</code> is <code>NULL</code>.</p>
<p>Am I missing something related to object living span on WordPress layers?</p>
| [
{
"answer_id": 273828,
"author": "Frank P. Walentynowicz",
"author_id": 32851,
"author_profile": "https://wordpress.stackexchange.com/users/32851",
"pm_score": 0,
"selected": false,
"text": "<p>Your function <code>get_instance</code> will never create an instance of the class because of this line:</p>\n\n<pre><code>$instance = new static();\n</code></pre>\n\n<p>it should be:</p>\n\n<pre><code>$instance = new VBWpdb();\n</code></pre>\n"
},
{
"answer_id": 273831,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 2,
"selected": true,
"text": "<p>You are just doing it wrong. The problem starts with using a singleton, just never do it.</p>\n\n<p>You have a class of loggers which logs into some internal buffer. All loggers log into the same buffer, therefor the buffer (<code>trace</code> in your case) a static array in the class.\nNo more <code>get_intance</code>, just instantiate a new logger and log. This gives you the added flexibility of having several classes of loggers that \"output\" to the same buffer.</p>\n\n<p>We are left with a question of how to inspect the log, and this you do with a static method.</p>\n\n<p>I am sure this scheme can be improved by people that are more hard core OOP than me, using singleton is equivalent to using a <code>namespace</code> and code written under a namespace is easier to read and use than the singleton, just call a function directly with no need to handle the complications of getting an object first, it is easier to use a function in a hook, etc.</p>\n"
}
]
| 2017/07/18 | [
"https://wordpress.stackexchange.com/questions/273806",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/77513/"
]
| In my WordPress site, I created a `Singleton` inside a custom plugin I have, like this:
```
class VBWpdb {
private $trace = array();
public static function get_instance() {
static $instance = null;
if(null === $instance) {
$instance = new static();
}
return $instance;
}
//...
```
So, I'm using `VBWpdb::get_instance()` in a lot of places of my code to populate `$trace` array (first var of the class). It works for the purpose of having a trace along my code and this static class is being the only instance during the plugin execution. I tested with arbitrary `var_dump`'s...
The problem is... I want to print that trace once my page is loaded and I'm doing this:
```
add_action('wp_loaded', 'vb_dump_wpdb_trace');
function vb_dump_wpdb_trace() {
VBWpdb::get_instance()->dump();
}
```
It seems that this instance is not being created again, but `$trace` is `NULL`.
Am I missing something related to object living span on WordPress layers? | You are just doing it wrong. The problem starts with using a singleton, just never do it.
You have a class of loggers which logs into some internal buffer. All loggers log into the same buffer, therefor the buffer (`trace` in your case) a static array in the class.
No more `get_intance`, just instantiate a new logger and log. This gives you the added flexibility of having several classes of loggers that "output" to the same buffer.
We are left with a question of how to inspect the log, and this you do with a static method.
I am sure this scheme can be improved by people that are more hard core OOP than me, using singleton is equivalent to using a `namespace` and code written under a namespace is easier to read and use than the singleton, just call a function directly with no need to handle the complications of getting an object first, it is easier to use a function in a hook, etc. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.