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 |
|---|---|---|---|---|---|---|
231,114 | <p>I have a loop that pulls in all sites in my multisite site network and loops through them to get variables located in their ACF options. Here is an excerpt from the code I am using:</p>
<pre><code> $stageurl = array();
$args = array(
'public' => true,
'limit' => 500
);
$sites = wp_get_sites($args);
foreach ($sites as $site) {
switch_to_blog($site['blog_id']);
$stage = get_field('stage', 'option');
if (isset($stage)) {
$stageurl[] = $site['domain'];
}
restore_current_blog();
}
foreach ($stageurl as $i => $stages) {
...
}
</code></pre>
<p>Using wp_get_sites, how are sites sorted by default?</p>
<p>Ideally I would like to sort sites by their creation date before adding them to my foreach loop. Is it possible to find a network site's creation date and use it to sort my $stageurl array?</p>
| [
{
"answer_id": 231121,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 3,
"selected": true,
"text": "<h2>Using <code>get_sites()</code> in WP 4.6+</h2>\n\n<p>It looks like <code>wp_get_sites()</code> will be <a hre... | 2016/06/30 | [
"https://wordpress.stackexchange.com/questions/231114",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/88515/"
] | I have a loop that pulls in all sites in my multisite site network and loops through them to get variables located in their ACF options. Here is an excerpt from the code I am using:
```
$stageurl = array();
$args = array(
'public' => true,
'limit' => 500
);
$sites = wp_get_sites($args);
foreach ($sites as $site) {
switch_to_blog($site['blog_id']);
$stage = get_field('stage', 'option');
if (isset($stage)) {
$stageurl[] = $site['domain'];
}
restore_current_blog();
}
foreach ($stageurl as $i => $stages) {
...
}
```
Using wp\_get\_sites, how are sites sorted by default?
Ideally I would like to sort sites by their creation date before adding them to my foreach loop. Is it possible to find a network site's creation date and use it to sort my $stageurl array? | Using `get_sites()` in WP 4.6+
------------------------------
It looks like `wp_get_sites()` will be [deprecated](https://github.com/WordPress/WordPress/blob/858fb83f57a2aa916f29bdb04f2d5335c78d5903/wp-includes/ms-deprecated.php#L442) in WP 4.6.
The [new replacement](https://github.com/WordPress/WordPress/blob/858fb83f57a2aa916f29bdb04f2d5335c78d5903/wp-includes/ms-blogs.php#L608-612) is:
```
function get_sites( $args = array() ) {
$query = new WP_Site_Query();
return $query->query( $args );
}
```
Very similar to `get_posts()` and `WP_Query`.
It supports various useful parameters and filters.
Here's what the [inline documentation says](https://github.com/WordPress/WordPress/blob/858fb83f57a2aa916f29bdb04f2d5335c78d5903/wp-includes/class-wp-site-query.php#L120) about the `orderby` input parameter:
* Site status or array of statuses.
* Default `id`
* Accepts:
+ `id`
+ `domain`
+ `path`
+ `network_id`
+ `last_updated`
+ `registered`
+ `domain_length`
+ `path_length`
+ `site__in`
+ `network__in`
* Also accepts the following to disable `ORDER BY` clause:
+ `false`
+ an empty array
+ `none`
The default of the `order` parameter is `DESC`.
Example
-------
Here's an example (untested) how we might try to order *public* sites by *registration* date:
```
$mysites = get_sites(
[
'public' => 1,
'number' => 500,
'orderby' => 'registered',
'order' => 'DESC',
]
);
```
and returning at max 500 sites.
Update
------
Thanks to @fostertime for noticing that the *boolean* value of the `public` parameter. It's not supported. It should be `1` not `true` in the example here above.
I therefore filed a ticket [here](https://core.trac.wordpress.org/ticket/37937) (#37937) to support *boolean* strings for the `public`, `archived`, `mature`, `spam` and `deleted` attributes in `WP_Site_Query`. |
231,118 | <p>I hope this is not too specific to WooCommerce.</p>
<p>I have a nifty shortcode that displays a list of all my products with SKUs. However, it also includes products that I have published but have set the catalog visibility to "hidden." </p>
<p>I can't find an argument / parameter to exclude hidden products (or only include those marked as Catalog/Search).</p>
<p>I know it must be simple; I just haven't found it. Thanks for any help.</p>
<p>Here is the code:</p>
<pre><code><?php
$params = array('posts_per_page' => -1, 'post_type' => 'product', 'orderby' => 'menu-order', 'order' => 'asc');
$wc_query = new WP_Query($params);
?>
<table class="product-list tablesorter"><thead><tr><th>SKU</th><th>Product Name</th></tr></thead><tbody>
<?php if ($wc_query->have_posts()) : ?>
<?php while ($wc_query->have_posts()) :
$wc_query->the_post(); ?>
<tr>
<td><?php global $product; echo $product->get_sku(); ?></td>
<td><a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a></td>
</tr>
<?php endwhile; ?>
<?php wp_reset_postdata(); ?>
<?php else: ?>
<tr><td>
<?php _e( 'No Products' ); ?>
</td> </tr>
<?php endif; ?>
</tbody>
</table>
</code></pre>
| [
{
"answer_id": 231120,
"author": "Howdy_McGee",
"author_id": 7355,
"author_profile": "https://wordpress.stackexchange.com/users/7355",
"pm_score": 3,
"selected": true,
"text": "<p><strong>Important:</strong> The following only works for WooCommerce versions less than 3.0. For a more up-t... | 2016/06/30 | [
"https://wordpress.stackexchange.com/questions/231118",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/97616/"
] | I hope this is not too specific to WooCommerce.
I have a nifty shortcode that displays a list of all my products with SKUs. However, it also includes products that I have published but have set the catalog visibility to "hidden."
I can't find an argument / parameter to exclude hidden products (or only include those marked as Catalog/Search).
I know it must be simple; I just haven't found it. Thanks for any help.
Here is the code:
```
<?php
$params = array('posts_per_page' => -1, 'post_type' => 'product', 'orderby' => 'menu-order', 'order' => 'asc');
$wc_query = new WP_Query($params);
?>
<table class="product-list tablesorter"><thead><tr><th>SKU</th><th>Product Name</th></tr></thead><tbody>
<?php if ($wc_query->have_posts()) : ?>
<?php while ($wc_query->have_posts()) :
$wc_query->the_post(); ?>
<tr>
<td><?php global $product; echo $product->get_sku(); ?></td>
<td><a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a></td>
</tr>
<?php endwhile; ?>
<?php wp_reset_postdata(); ?>
<?php else: ?>
<tr><td>
<?php _e( 'No Products' ); ?>
</td> </tr>
<?php endif; ?>
</tbody>
</table>
``` | **Important:** The following only works for WooCommerce versions less than 3.0. For a more up-to-date answer please see the other [answer by kalle](https://wordpress.stackexchange.com/a/262628/7355).
WooCommerce save this data as `metadata` so you'll need to run a [Meta Query](https://codex.wordpress.org/Class_Reference/WP_Query#Custom_Field_Parameters) against the name `_visibility`. Something like:
```
'meta_query' => array(
array(
'key' => '_visibility',
'value' => 'hidden',
'compare' => '!=',
)
)
```
This will pull all posts that **do not** have meta `_visibility` equal to `hidden`. |
231,123 | <p>I have used <code>WP-Mail-SMTP</code> to setup the mailer on my WordPress installation.
I have tested it by sending email to my private mail.</p>
<p>I am now trying to send the form data using wp_mail() function[WP]. </p>
<p>Below is the code.</p>
<pre><code><?php
if(isset($_POST["button_pressed"])){
// Checking For Blank Fields..
if($_POST["dname"]==""){
echo "Fill All Fields..";
}
else {
$email=$_POST['email'];
$message = $_POST['dname'];
$headers = 'From:' . "\r\n"; // Sender's Email
$headers .= 'Cc:' . "\r\n"; // Carbon copy to Sender
// Message lines should not exceed 70 characters (PHP rule), so wrap it
// $message = wordwrap($message, 70);
wp_mail("PRIVATE-EMAIL-ADDRESS", $subject, $message, $headers)
echo "Your mail has been sent successfully ! Thank you for your feedback";
}
?>
</code></pre>
<p>HTML form</p>
<pre><code><form>
<div class="row">
<div class="form-group">
<div class="col-sm-6"><input class="form-control" type="text" placeholder="ENTER DOG'S NAME" id="dname" /></div>
<div class="col-sm-6"><input class="form-control" type="text" placeholder="ENTER OWNER'S NAME" id="name" /></div>
</div>
</div>
<input type="submit" value="SUBMIT" />
<input type="hidden" name="button_pressed" value="1" />
</form>
</code></pre>
<p>I have tried many tutorials, but none helped.
Your comments and suggestions will be very helpful to me.
Thanks for your time.</p>
| [
{
"answer_id": 231129,
"author": "Syed Fakhar Abbas",
"author_id": 90591,
"author_profile": "https://wordpress.stackexchange.com/users/90591",
"pm_score": 0,
"selected": false,
"text": "<p>I have checked your code. I think header not defined properly.Please check the code below:</p>\n\n<... | 2016/06/30 | [
"https://wordpress.stackexchange.com/questions/231123",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/97618/"
] | I have used `WP-Mail-SMTP` to setup the mailer on my WordPress installation.
I have tested it by sending email to my private mail.
I am now trying to send the form data using wp\_mail() function[WP].
Below is the code.
```
<?php
if(isset($_POST["button_pressed"])){
// Checking For Blank Fields..
if($_POST["dname"]==""){
echo "Fill All Fields..";
}
else {
$email=$_POST['email'];
$message = $_POST['dname'];
$headers = 'From:' . "\r\n"; // Sender's Email
$headers .= 'Cc:' . "\r\n"; // Carbon copy to Sender
// Message lines should not exceed 70 characters (PHP rule), so wrap it
// $message = wordwrap($message, 70);
wp_mail("PRIVATE-EMAIL-ADDRESS", $subject, $message, $headers)
echo "Your mail has been sent successfully ! Thank you for your feedback";
}
?>
```
HTML form
```
<form>
<div class="row">
<div class="form-group">
<div class="col-sm-6"><input class="form-control" type="text" placeholder="ENTER DOG'S NAME" id="dname" /></div>
<div class="col-sm-6"><input class="form-control" type="text" placeholder="ENTER OWNER'S NAME" id="name" /></div>
</div>
</div>
<input type="submit" value="SUBMIT" />
<input type="hidden" name="button_pressed" value="1" />
</form>
```
I have tried many tutorials, but none helped.
Your comments and suggestions will be very helpful to me.
Thanks for your time. | After fiddling around for hours, I found the problem.
It was the form not the PHP.
```
<div class="col-sm-6">
<input class="form-control" type="text" placeholder="ENTER DOG'S NAME" id="dname" /></div>
<div class="col-sm-6">
<input class="form-control" type="text" placeholder="ENTER OWNER'S NAME" id="name" /></div>
```
`id` attribute needs to be `name`.
**Corrected**
```
<div class="col-sm-6">
<input class="form-control" type="text" placeholder="ENTER DOG'S NAME" name="dname" /></div>
<div class="col-sm-6">
<input class="form-control" type="text" placeholder="ENTER OWNER'S NAME" name="name" /></div>
</div>
``` |
231,125 | <p>If set <code>show_ui</code> <code>false</code>, this hide the taxonomy meta box and admin menu link both, how to hide only meta box?</p>
<pre><code>$args = array(
'hierarchical' => true,
'labels' => $labels,
'show_ui' => false,
'show_admin_column' => false,
'show_in_menu' => true,
'show_in_nav_menus' => true,
'query_var' => true,
'rewrite' => array( 'slug' => 'wheel' ),
);
register_taxonomy( 'wheel', array( 'product' ), $args );
</code></pre>
| [
{
"answer_id": 231174,
"author": "NateWr",
"author_id": 39309,
"author_profile": "https://wordpress.stackexchange.com/users/39309",
"pm_score": 4,
"selected": true,
"text": "<p>You're looking for the <code>meta_box_cb</code> argument.</p>\n\n<pre><code>$args = array(\n 'hierarchical' ... | 2016/06/30 | [
"https://wordpress.stackexchange.com/questions/231125",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/97619/"
] | If set `show_ui` `false`, this hide the taxonomy meta box and admin menu link both, how to hide only meta box?
```
$args = array(
'hierarchical' => true,
'labels' => $labels,
'show_ui' => false,
'show_admin_column' => false,
'show_in_menu' => true,
'show_in_nav_menus' => true,
'query_var' => true,
'rewrite' => array( 'slug' => 'wheel' ),
);
register_taxonomy( 'wheel', array( 'product' ), $args );
``` | You're looking for the `meta_box_cb` argument.
```
$args = array(
'hierarchical' => true,
'labels' => $labels,
'show_ui' => false,
'show_admin_column' => false,
'show_in_menu' => true,
'show_in_nav_menus' => true,
'query_var' => true,
'rewrite' => array( 'slug' => 'wheel' ),
'meta_box_cb' => false,
);
register_taxonomy( 'wheel', array( 'product' ), $args );
```
You can also define a custom callback function for displaying your own metabox if you'd like. Refer to the [documentation for register\_taxonomy()](https://developer.wordpress.org/reference/functions/register_taxonomy/). |
231,130 | <p>Looking at <a href="https://codex.wordpress.org/Function_Reference/human_time_diff" rel="nofollow">https://codex.wordpress.org/Function_Reference/human_time_diff</a></p>
<p>I'm using an English version of Wordpress.</p>
<p>In my theme template, I would like to define custom text of min, hour, day, week, month, year in Chinese using <code>human_time_diff()</code> when looping through posts.</p>
<p>According to the instruction in the Codex documentation:</p>
<pre><code><?php
printf( _x( '%s ago', '%s = human-readable time difference',
'your-text-domain' ), human_time_diff( get_the_time( 'U' ),
current_time( 'timestamp' ) ) );
?>
</code></pre>
<p>I still don't know how to make the implementation to do the swap using the code above. eg.</p>
<pre><code>min -> 分鐘
hour -> 小時
dat -> 天
week -> 週
month -> 月
year -> 年
</code></pre>
<p><code>ago</code> part should be straight forward.</p>
<p>Is there an example that can demonstrate how it works?</p>
<p>Also, do I need to worry about plurals in English?</p>
| [
{
"answer_id": 231176,
"author": "TheDeadMedic",
"author_id": 1685,
"author_profile": "https://wordpress.stackexchange.com/users/1685",
"pm_score": 2,
"selected": false,
"text": "<p>If you check out the source of <code>human_time_diff</code>:</p>\n\n<pre><code>if ( $diff < HOUR_IN_SEC... | 2016/06/30 | [
"https://wordpress.stackexchange.com/questions/231130",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/92505/"
] | Looking at <https://codex.wordpress.org/Function_Reference/human_time_diff>
I'm using an English version of Wordpress.
In my theme template, I would like to define custom text of min, hour, day, week, month, year in Chinese using `human_time_diff()` when looping through posts.
According to the instruction in the Codex documentation:
```
<?php
printf( _x( '%s ago', '%s = human-readable time difference',
'your-text-domain' ), human_time_diff( get_the_time( 'U' ),
current_time( 'timestamp' ) ) );
?>
```
I still don't know how to make the implementation to do the swap using the code above. eg.
```
min -> 分鐘
hour -> 小時
dat -> 天
week -> 週
month -> 月
year -> 年
```
`ago` part should be straight forward.
Is there an example that can demonstrate how it works?
Also, do I need to worry about plurals in English? | The full solution that works for me without modifying the Wordpress core is to clone the `human_time_diff()` function and place it inside `functions.php` as a renamed `human_time_diff_chinese()`, then swap all occurrence of `human_time_diff()` function with this new `human_time_diff_chinese()` function.
```
function human_time_diff_chinese( $from, $to = '' ) {
if ( empty( $to ) ) {
$to = time();
}
$diff = (int) abs( $to - $from );
if ( $diff < HOUR_IN_SECONDS ) {
$mins = round( $diff / MINUTE_IN_SECONDS );
if ( $mins <= 1 )
$mins = 1;
/* translators: min=minute */
$since = sprintf( _n( '%s 分鐘', '%s 分鐘', $mins ), $mins );
} elseif ( $diff < DAY_IN_SECONDS && $diff >= HOUR_IN_SECONDS ) {
$hours = round( $diff / HOUR_IN_SECONDS );
if ( $hours <= 1 )
$hours = 1;
$since = sprintf( _n( '%s 小時', '%s 小時', $hours ), $hours );
} elseif ( $diff < WEEK_IN_SECONDS && $diff >= DAY_IN_SECONDS ) {
$days = round( $diff / DAY_IN_SECONDS );
if ( $days <= 1 )
$days = 1;
$since = sprintf( _n( '%s 天', '%s 天', $days ), $days );
} elseif ( $diff < MONTH_IN_SECONDS && $diff >= WEEK_IN_SECONDS ) {
$weeks = round( $diff / WEEK_IN_SECONDS );
if ( $weeks <= 1 )
$weeks = 1;
$since = sprintf( _n( '%s 週', '%s 週', $weeks ), $weeks );
} elseif ( $diff < YEAR_IN_SECONDS && $diff >= MONTH_IN_SECONDS ) {
$months = round( $diff / MONTH_IN_SECONDS );
if ( $months <= 1 )
$months = 1;
$since = sprintf( _n( '%s 個月', '%s 個月', $months ), $months );
} elseif ( $diff >= YEAR_IN_SECONDS ) {
$years = round( $diff / YEAR_IN_SECONDS );
if ( $years <= 1 )
$years = 1;
$since = sprintf( _n( '%s 年', '%s 年', $years ), $years );
}
return apply_filters( 'human_time_diff_chinese', $since, $diff, $from, $to );
}
``` |
231,137 | <p>I'm very new to this API, in fact I've only spent couple hours on it so far. I've done my research but cannot find anything about it...</p>
<p>The issue is, I can't seem to get the featured image of a post. The JSON returns <code>"featured_media: 0"</code>.</p>
<pre><code>getPosts: function() {
var burl = "http://www.example.com/wp-json/wp/v2/posts";
var dataDiv = document.getElementById('cards');
$.ajax({
url: burl,
data: data,
type: 'GET',
async: false,
processData: false,
beforeSend: function (xhr) {
if (xhr && xhr.overrideMimeType) {
xhr.overrideMimeType('application/json;charset=utf-8');
}
},
dataType: 'json',
success: function (data) {
console.log(data);
//question: data->featured_image: 0?!
var theUl = document.getElementById('cards');
for (var key in data) {
//data[key]['']...
//doing my stuff here
}
},
error: function(e) {
console.log('Error: '+e);
}
});
}
</code></pre>
<p>I have definitely, set a featured image on the post but data returns:</p>
<p><a href="https://i.stack.imgur.com/ZGzzL.png" rel="noreferrer"><img src="https://i.stack.imgur.com/ZGzzL.png" alt="featured media?"></a></p>
<p>Any help will be appreciated.</p>
| [
{
"answer_id": 231138,
"author": "Michael Cropper",
"author_id": 91911,
"author_profile": "https://wordpress.stackexchange.com/users/91911",
"pm_score": 3,
"selected": false,
"text": "<p>Take a look at a plugin called <a href=\"https://wordpress.org/plugins/better-rest-api-featured-image... | 2016/06/30 | [
"https://wordpress.stackexchange.com/questions/231137",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/97623/"
] | I'm very new to this API, in fact I've only spent couple hours on it so far. I've done my research but cannot find anything about it...
The issue is, I can't seem to get the featured image of a post. The JSON returns `"featured_media: 0"`.
```
getPosts: function() {
var burl = "http://www.example.com/wp-json/wp/v2/posts";
var dataDiv = document.getElementById('cards');
$.ajax({
url: burl,
data: data,
type: 'GET',
async: false,
processData: false,
beforeSend: function (xhr) {
if (xhr && xhr.overrideMimeType) {
xhr.overrideMimeType('application/json;charset=utf-8');
}
},
dataType: 'json',
success: function (data) {
console.log(data);
//question: data->featured_image: 0?!
var theUl = document.getElementById('cards');
for (var key in data) {
//data[key]['']...
//doing my stuff here
}
},
error: function(e) {
console.log('Error: '+e);
}
});
}
```
I have definitely, set a featured image on the post but data returns:
[](https://i.stack.imgur.com/ZGzzL.png)
Any help will be appreciated. | You can get it without plugins by adding `_embed`as param to your query
```
/?rest_route=/wp/v2/posts&_embed
/wp-json/wp/v2/posts?_embed
``` |
231,144 | <p>Basically a post is an event therefor will be displayed once or twice, depending on meta key.
Every post has at least two meta keys <code>$start_time_1</code> and <code>$end_time_1</code>. Let's say i have two posts, title: "Radio Show" and "TV Show". </p>
<pre><code>Radio Show - start @ 2016-07-01 12:00
TV Show - start @ 2016-07-01 15:00
</code></pre>
<p>My code below, works fine. But what if i add another start time like <code>$start_time_2</code>and <code>$end_time_2</code> and all post sorted by start time.
Just like this:</p>
<pre><code>Radio Show - start @ 2016-07-01 12:30
TV Show - start @ 2016-07-01 15:30
TV Show - start @ 2016-07-02 21:00
Radio Show - start @ 2016-02-01 23:00
</code></pre>
<p>This the query i'using but i cant make to show the post twice.</p>
<pre><code>$start_time_1 = '2016-07-01 12:30';
$end_time_1 = '2016-07-01 14:30';
$args = array(
'post_type' => 'post',
'posts_per_page' => -1,
'post_status' => 'publish',
'meta_query' => array(
array(
'key' => $end_time_1, // if the time() is greater than end time dont display post
'value' => date('Y-m-d H:i'),
'compare' => '>='
)),
'meta_key' => $start_time_1, // for sorting posts
'orderby' => array(
'meta_value' => 'ASC',
'post_date' => 'ASC',
),
'order' => 'ASC',
);
</code></pre>
| [
{
"answer_id": 231153,
"author": "Samuel E. Cerezo",
"author_id": 97635,
"author_profile": "https://wordpress.stackexchange.com/users/97635",
"pm_score": 0,
"selected": false,
"text": "<p>What about using this?</p>\n\n<pre>\n$args = array(\n 'post_type' => 'post',\n 'posts_per_page... | 2016/07/01 | [
"https://wordpress.stackexchange.com/questions/231144",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/97628/"
] | Basically a post is an event therefor will be displayed once or twice, depending on meta key.
Every post has at least two meta keys `$start_time_1` and `$end_time_1`. Let's say i have two posts, title: "Radio Show" and "TV Show".
```
Radio Show - start @ 2016-07-01 12:00
TV Show - start @ 2016-07-01 15:00
```
My code below, works fine. But what if i add another start time like `$start_time_2`and `$end_time_2` and all post sorted by start time.
Just like this:
```
Radio Show - start @ 2016-07-01 12:30
TV Show - start @ 2016-07-01 15:30
TV Show - start @ 2016-07-02 21:00
Radio Show - start @ 2016-02-01 23:00
```
This the query i'using but i cant make to show the post twice.
```
$start_time_1 = '2016-07-01 12:30';
$end_time_1 = '2016-07-01 14:30';
$args = array(
'post_type' => 'post',
'posts_per_page' => -1,
'post_status' => 'publish',
'meta_query' => array(
array(
'key' => $end_time_1, // if the time() is greater than end time dont display post
'value' => date('Y-m-d H:i'),
'compare' => '>='
)),
'meta_key' => $start_time_1, // for sorting posts
'orderby' => array(
'meta_value' => 'ASC',
'post_date' => 'ASC',
),
'order' => 'ASC',
);
``` | As Tim Malone said, WP\_Query isn't going to return multiple copies of the same post in its result set. I think you have a design problem and I would suggest you use parent/child posts rather than post meta to accomplish what you want.
The following is one approach to doing this. First, register both post types:
```
// The parent event type
// There will be one of these for Radio Show and TV Show
register_post_type( 'event', $args );
// A non-public event type for each "occurrence" of an event
// There will be two of these for each Radio Show and TV Show
register_post_type( 'event_occurrence', array(
// add all of your usual $args and then set public to false
'public' => false,
) );
```
Then, when saving your `event` post, don't save the start/end times as post meta on that post object. Instead use those dates to create `event_occurrence` posts for each occurrence, with the start and end times saved there.
```
$occurrence_id = wp_insert_post( array(
// add all of your occurrence details and then set the parent
// to the `event` post that's being saved
'post_parent' => <event_post_id>,
// Set the post date to the start time for efficient ordering
'post_date' => $start_time,
) );
// Save the end time as post meta
// Save it as a Unix timestamp so that we can compare it in the query
update_post_meta( $occurrence_id, 'end_time', strtotime( $end_time ) );
```
Now you should have the following posts in the database:
```
Radio Show
Radio Show Instance 1
Radio Show Instance 2
TV Show
TV Show Instance 1
TV Show Instance 2
```
You can then query the occurrences like this:
```
$args = array(
// Only fetch occurrences
'post_type' => 'event_occurrence',
// Retrieve only future occurrences
'date_query' => array(
array(
'after' => 'now',
)
),
// use a reasonably high posts_per_page instead of -1
// otherwise you could accidentally cripple a site
// with an expensive query
'posts_per_page' => 500,
'post_status' => 'publish',
'meta_query' => array(
array(
'key' => 'end_time',
'value' => time(),
'compare' => '>='
),
),
// They'll be ordered by start date.
// ASC starts with earliest first
'order' => 'ASC',
);
```
Our loop will now contain four posts:
```
Radio Show Instance 1
Radio Show Instance 2
TV Show Instance 1
TV Show Instance 2
```
So while you're looping through the occurrences, you can access the parent post of each occurrence to get the overall event data. You can do this with a simple function:
```
$parent_event_id = wp_get_post_parent_id( get_the_ID() );
```
However, this will result in a lot of extra queries to the database which will effect performance. Instead, I'd recommend you run a separate query for the primary `event` posts, and then pull them from those results, so you're only making one additional query to the database:
```
$args = array(
'post_type' => 'event',
'date_query' => array(
array(
'after' => 'now',
)
),
'posts_per_page' => 500,
'post_status' => 'publish',
'meta_query' => array(
array(
'key' => 'end_time',
'value' => time(),
'compare' => '>='
),
),
'order' => 'ASC',
);
$events = new WP_Query( $args );
```
So your $occurrences loop would look like this:
```
$occurrences = new WP_Query( $occurrences_args );
while( $occurrences->have_posts() ) {
$occurrences->the_post();
// Get the parent event data
$parent_event_id = wp_get_post_parent_id( get_the_ID() );
$parent_event = null;
foreach ( $events->posts as $post ) {
if ( $post->ID == $parent_event_id ) {
$parent_event = $post;
break;
}
}
// Now you can use the loop to access the
// occurrence data and use $parent_event to
// access the overall event data
}
``` |
231,152 | <p>I am very well aware of <code>how to make multiple sidebars</code>. But I believe my way is not proper way of adding multiple sidebars.</p>
<p><strong>This is how I add multiple sidebars</strong></p>
<p>If I simply wants to create a sidebar then I use sidebar.php file. BUT if I want to use another sidebar then I have to create another php file
like <code>sidebar-new.php</code>. Then call this file as </p>
<pre><code> <?php
get_sidebar('new');
?>
</code></pre>
<p>That mean if I want to create 4 sidebar then I have to make 4 php files!</p>
<p>BUT I have seen many themes (In wordpress market) that provide many sidebars but they contains only one php file for sidebar (sidebar.php)!
How do they do that? I have learned about making sidebars from google earlier but in search I only get the results that I am using right now (create multiple files for multiple sidebars).</p>
<p>So how can I create multiple sidebar without making Multiple php files!!???</p>
| [
{
"answer_id": 231160,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 2,
"selected": false,
"text": "<p>You can differentiate between sidebars <strong>inside</strong> <code>sidebar.php</code>. I don't know what your ... | 2016/07/01 | [
"https://wordpress.stackexchange.com/questions/231152",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/81621/"
] | I am very well aware of `how to make multiple sidebars`. But I believe my way is not proper way of adding multiple sidebars.
**This is how I add multiple sidebars**
If I simply wants to create a sidebar then I use sidebar.php file. BUT if I want to use another sidebar then I have to create another php file
like `sidebar-new.php`. Then call this file as
```
<?php
get_sidebar('new');
?>
```
That mean if I want to create 4 sidebar then I have to make 4 php files!
BUT I have seen many themes (In wordpress market) that provide many sidebars but they contains only one php file for sidebar (sidebar.php)!
How do they do that? I have learned about making sidebars from google earlier but in search I only get the results that I am using right now (create multiple files for multiple sidebars).
So how can I create multiple sidebar without making Multiple php files!!??? | Defining new sidebar with in your functions.php
```
<?php
if ( function_exists('register_sidebar') ) {
register_sidebar(array(
'before_widget' => '<li id="%1$s" class="widget %2$s">',
'after_widget' => '</li>',
'before_title' => '<h2 class="widgettitle">',
'after_title' => '</h2>'
));
}?>
```
Once these are functions are defined, you will notice the extra sidebar appear in the WordPress Dashboard under the Appearance > Widgets option. It’s here that you can drag and drop all your widgets into your various sidebars.
```
<?php
if ( function_exists('register_sidebar') ) {
register_sidebar(array(
'name' => 'sidebar 1',
'before_widget' => '<div id="%1$s" class="widget %2$s">',
'after_widget' => '</div>',
'before_title' => '<h2>',
'after_title' => '</h2>'
));
register_sidebar(array(
'name' => 'footer sidebar 1',
'before_widget' => '<div id="%1$s" class="widget %2$s">',
'after_widget' => '</div>',
'before_title' => '<h2>',
'after_title' => '</h2>'
));
}?>
```
Adding new sidebar to your template
Within your sidebar.php file, change the call to your existing sidebar to include its name that you defined within the functions.php file earlier.
```
<?php if ( !function_exists('dynamic_sidebar') || !dynamic_sidebar('sidebar 1') ) : ?>
<h2>Articles by month</h2>
<ul>
<?php wp_get_archives('title_li=&type=monthly'); ?>
</ul>
<h2>Categories</h2>
<ul>
<?php wp_list_categories('show_count=0&title_li='); ?>
</ul>
<?php endif; ?>
```
To add your new sidebar, you can either copy the above code or you can simply copy the following lines. Add these lines to wherever you’d like your new widgets to appear. In this example you can see from the name that I’m placing mine in the footer of my website. As before, don’t forget to specify the correct sidebar name. In the above code, the html that appears between the php statements is what will appear when there are no widgets added to your sidebar. This ‘default’ code can obviously be modified to suit your theme. In the following code, since there is no extra html, nothing will be displayed unless a widget has been added into the sidebar within your WordPress dashboard.
```
<?php if ( !function_exists('dynamic_sidebar') || !dynamic_sidebar('footer sidebar 1') ) : ?>
<?php endif; ?>
``` |
231,154 | <p>I am new with word press and I want to show the post of a specific category on my page. The name of the category which i want to show is <code>home slider</code>. Below is the code which I have used to display all the posts <code>title</code>, <code>image</code> and <code>content</code>.</p>
<pre><code><div class="row">
<?php $myposts = get_posts( 'numberposts=6&offset=$debut' );
foreach( $myposts as $post) : setup_postdata( $post ) ?>
<div class="col-sm-4 col-lg-4 col-md-4">
<div class="thumbnail">
<?php the_post_thumbnail( 'thumbnail'); ?>
<div class="caption">
<h4 class="pull-right">$94.99</h4>
<a> <?php the_title(); ?> </a>
<!--I have used this substr here to set the limit of the text, and if do not want to set the limit simply use this line of code <?php //the_content(); ?>-->
<?php echo substr(get_the_excerpt(), 0,30); ?>...
<a href="#" >read more</a>
</div>
<div class="ratings">
<p class="pull-right">18 reviews</p>
<p>
<span class="glyphicon glyphicon-star"></span>
<span class="glyphicon glyphicon-star"></span>
<span class="glyphicon glyphicon-star"></span>
<span class="glyphicon glyphicon-star"></span>
<span class="glyphicon glyphicon-star-empty"></span>
</p>
</div>
</div>
</div>
<?php endforeach; ?>
</div>
</code></pre>
<p>Can please anyone edit this code so that I can show posts of the specific category which in my case is <code>home slider</code>.
Thank you.</p>
| [
{
"answer_id": 231160,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 2,
"selected": false,
"text": "<p>You can differentiate between sidebars <strong>inside</strong> <code>sidebar.php</code>. I don't know what your ... | 2016/07/01 | [
"https://wordpress.stackexchange.com/questions/231154",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/97583/"
] | I am new with word press and I want to show the post of a specific category on my page. The name of the category which i want to show is `home slider`. Below is the code which I have used to display all the posts `title`, `image` and `content`.
```
<div class="row">
<?php $myposts = get_posts( 'numberposts=6&offset=$debut' );
foreach( $myposts as $post) : setup_postdata( $post ) ?>
<div class="col-sm-4 col-lg-4 col-md-4">
<div class="thumbnail">
<?php the_post_thumbnail( 'thumbnail'); ?>
<div class="caption">
<h4 class="pull-right">$94.99</h4>
<a> <?php the_title(); ?> </a>
<!--I have used this substr here to set the limit of the text, and if do not want to set the limit simply use this line of code <?php //the_content(); ?>-->
<?php echo substr(get_the_excerpt(), 0,30); ?>...
<a href="#" >read more</a>
</div>
<div class="ratings">
<p class="pull-right">18 reviews</p>
<p>
<span class="glyphicon glyphicon-star"></span>
<span class="glyphicon glyphicon-star"></span>
<span class="glyphicon glyphicon-star"></span>
<span class="glyphicon glyphicon-star"></span>
<span class="glyphicon glyphicon-star-empty"></span>
</p>
</div>
</div>
</div>
<?php endforeach; ?>
</div>
```
Can please anyone edit this code so that I can show posts of the specific category which in my case is `home slider`.
Thank you. | Defining new sidebar with in your functions.php
```
<?php
if ( function_exists('register_sidebar') ) {
register_sidebar(array(
'before_widget' => '<li id="%1$s" class="widget %2$s">',
'after_widget' => '</li>',
'before_title' => '<h2 class="widgettitle">',
'after_title' => '</h2>'
));
}?>
```
Once these are functions are defined, you will notice the extra sidebar appear in the WordPress Dashboard under the Appearance > Widgets option. It’s here that you can drag and drop all your widgets into your various sidebars.
```
<?php
if ( function_exists('register_sidebar') ) {
register_sidebar(array(
'name' => 'sidebar 1',
'before_widget' => '<div id="%1$s" class="widget %2$s">',
'after_widget' => '</div>',
'before_title' => '<h2>',
'after_title' => '</h2>'
));
register_sidebar(array(
'name' => 'footer sidebar 1',
'before_widget' => '<div id="%1$s" class="widget %2$s">',
'after_widget' => '</div>',
'before_title' => '<h2>',
'after_title' => '</h2>'
));
}?>
```
Adding new sidebar to your template
Within your sidebar.php file, change the call to your existing sidebar to include its name that you defined within the functions.php file earlier.
```
<?php if ( !function_exists('dynamic_sidebar') || !dynamic_sidebar('sidebar 1') ) : ?>
<h2>Articles by month</h2>
<ul>
<?php wp_get_archives('title_li=&type=monthly'); ?>
</ul>
<h2>Categories</h2>
<ul>
<?php wp_list_categories('show_count=0&title_li='); ?>
</ul>
<?php endif; ?>
```
To add your new sidebar, you can either copy the above code or you can simply copy the following lines. Add these lines to wherever you’d like your new widgets to appear. In this example you can see from the name that I’m placing mine in the footer of my website. As before, don’t forget to specify the correct sidebar name. In the above code, the html that appears between the php statements is what will appear when there are no widgets added to your sidebar. This ‘default’ code can obviously be modified to suit your theme. In the following code, since there is no extra html, nothing will be displayed unless a widget has been added into the sidebar within your WordPress dashboard.
```
<?php if ( !function_exists('dynamic_sidebar') || !dynamic_sidebar('footer sidebar 1') ) : ?>
<?php endif; ?>
``` |
231,165 | <p>We have created a CPT which allows our customer to upload files from the admin page to a folder outside of the wp-content/uploads folder. Files are uploaded and manipulated using wp_handle_upload and wp_insert_attachment.</p>
<p>How do we prevent these files from showing in the media library? Can we filter by post type?</p>
<p>Thanks in advance for any help!</p>
<p><strong>UPDATE:</strong> here's the code we've implemented so far. New uploads are still not showing in the media library.</p>
<pre><code>/*FORCE LIST VIEW IN MEDIA LIBRARY*/
add_action('admin_init', function() {
$_GET['mode'] = 'list';
}, 100);
/*HIDE GRID BUTTON IN MEDIA LIBRARY*/
add_action('admin_head', function() {
$css = '<style type="text/css">
.view-switch .view-grid {
display: none;
}
<style>';
echo $css;
});
/*REGISTER CUSTOM TAXONOMY*/
function create_hidden_taxonomy() {
register_taxonomy(
'hidden_taxonomy',
'attachment',
array(
'label' => __( 'Hidden Taxonomy' ),
'public' => false,
'rewrite' => false,
'hierarchical' => false,
)
);
}
add_action( 'init', 'create_hidden_taxonomy' );
/*CHECK IF PARENT POST TYPE IS ASSET. IF NOT ADD 'show_in_media_library' TERM*/
function assets_add_term( $post_id, \WP_Post $p, $update ) {
if ( 'attachment' !== $p->post_type ) {
error_log("fail1");
return;
}
if ( wp_is_post_revision( $post_id ) ) {
error_log("fail2");
return;
}
if ( $post->post_parent ) {
$excluded_types = array( 'assets' );
if ( in_array( get_post_type( $p->post_parent ), $excluded_types ) ) {
error_log("fail3");
return;
}
}
$result = wp_set_object_terms( $post_id, 'show_in_media_library', 'hidden_taxonomy', false );
if ( !is_array( $result ) || is_wp_error( $result ) ) {
error_log("fail4");
}else{
error_log("it worked!");
}
}
add_action( 'save_post', 'assets_add_term', 10, 2 );
/*HIDE MEDIA WITH CPT ASSETS FROM MEDIA LIBRARY*/
function assets_load_media() {
add_action('pre_get_posts','assets_hide_media',10,1);
}
add_action( 'load-upload.php' , 'assets_load_media' );
function assets_hide_media($query){
global $pagenow;
// there is no need to check for update.php as we are already hooking to it, but anyway
if( 'upload.php' != $pagenow || !is_admin())
return;
if(is_main_query()){
$excluded_cpt_ids = get_posts('post_type=assets&posts_per_page=-1&fields=ids');
$query->set('post_parent__not_in', $excluded_cpt_ids);
//$query->set('hidden_taxonomy', 'show_in_media_library' );
}
return $query;
}
/*HIDE MEDIA WITH CPT ASSETS FROM MEDIA LIBRARY MODAL*/
function assets_hide_media_modal( $query = array() ){
$query['post_parent__not_in'] = $excluded_cpt_ids;
return $query;
}
add_action('ajax_query_attachments_args','assets_hide_media_modal',10,1);
</code></pre>
| [
{
"answer_id": 231201,
"author": "bravokeyl",
"author_id": 43098,
"author_profile": "https://wordpress.stackexchange.com/users/43098",
"pm_score": 4,
"selected": true,
"text": "<p>Media items are just like posts with <strong><code>post_type = attachment</code></strong> and <strong><code>... | 2016/07/01 | [
"https://wordpress.stackexchange.com/questions/231165",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/84924/"
] | We have created a CPT which allows our customer to upload files from the admin page to a folder outside of the wp-content/uploads folder. Files are uploaded and manipulated using wp\_handle\_upload and wp\_insert\_attachment.
How do we prevent these files from showing in the media library? Can we filter by post type?
Thanks in advance for any help!
**UPDATE:** here's the code we've implemented so far. New uploads are still not showing in the media library.
```
/*FORCE LIST VIEW IN MEDIA LIBRARY*/
add_action('admin_init', function() {
$_GET['mode'] = 'list';
}, 100);
/*HIDE GRID BUTTON IN MEDIA LIBRARY*/
add_action('admin_head', function() {
$css = '<style type="text/css">
.view-switch .view-grid {
display: none;
}
<style>';
echo $css;
});
/*REGISTER CUSTOM TAXONOMY*/
function create_hidden_taxonomy() {
register_taxonomy(
'hidden_taxonomy',
'attachment',
array(
'label' => __( 'Hidden Taxonomy' ),
'public' => false,
'rewrite' => false,
'hierarchical' => false,
)
);
}
add_action( 'init', 'create_hidden_taxonomy' );
/*CHECK IF PARENT POST TYPE IS ASSET. IF NOT ADD 'show_in_media_library' TERM*/
function assets_add_term( $post_id, \WP_Post $p, $update ) {
if ( 'attachment' !== $p->post_type ) {
error_log("fail1");
return;
}
if ( wp_is_post_revision( $post_id ) ) {
error_log("fail2");
return;
}
if ( $post->post_parent ) {
$excluded_types = array( 'assets' );
if ( in_array( get_post_type( $p->post_parent ), $excluded_types ) ) {
error_log("fail3");
return;
}
}
$result = wp_set_object_terms( $post_id, 'show_in_media_library', 'hidden_taxonomy', false );
if ( !is_array( $result ) || is_wp_error( $result ) ) {
error_log("fail4");
}else{
error_log("it worked!");
}
}
add_action( 'save_post', 'assets_add_term', 10, 2 );
/*HIDE MEDIA WITH CPT ASSETS FROM MEDIA LIBRARY*/
function assets_load_media() {
add_action('pre_get_posts','assets_hide_media',10,1);
}
add_action( 'load-upload.php' , 'assets_load_media' );
function assets_hide_media($query){
global $pagenow;
// there is no need to check for update.php as we are already hooking to it, but anyway
if( 'upload.php' != $pagenow || !is_admin())
return;
if(is_main_query()){
$excluded_cpt_ids = get_posts('post_type=assets&posts_per_page=-1&fields=ids');
$query->set('post_parent__not_in', $excluded_cpt_ids);
//$query->set('hidden_taxonomy', 'show_in_media_library' );
}
return $query;
}
/*HIDE MEDIA WITH CPT ASSETS FROM MEDIA LIBRARY MODAL*/
function assets_hide_media_modal( $query = array() ){
$query['post_parent__not_in'] = $excluded_cpt_ids;
return $query;
}
add_action('ajax_query_attachments_args','assets_hide_media_modal',10,1);
``` | Media items are just like posts with **`post_type = attachment`** and **`post_status = inherit`**.
when we are on `upload.php` page, we have two views:
* List View
* Grid View
Grid view is populated via JavaScript and list view is extending normal **`WP_List_Table`**.
Since it (List view) is using normal post query we can use **`pre_get_posts`** to alter the query to hide required media items.
>
> How do we prevent these files from showing in the media library?
> Can
> we filter by post type?
>
>
>
We can't just filter the media items by `post_type` since media items post\_type is `attachment`. What you want is to filter media items by their **`post_parent's`** post ids.
```
add_action( 'load-upload.php' , 'wp_231165_load_media' );
function wp_231165_load_media() {
add_action('pre_get_posts','wp_231165_hide_media',10,1);
}
function wp_231165_hide_media($query){
global $pagenow;
// there is no need to check for update.php as we are already hooking to it, but anyway
if( 'upload.php' != $pagenow || !is_admin())
return;
if(is_main_query()){
$excluded_cpt_ids = array();//find a way to get all cpt post ids
$query->set('post_parent__not_in', $excluded_cpt_ids);
}
return $query;
}
```
Check [this question](https://wordpress.stackexchange.com/questions/165900/getting-the-ids-of-a-custom-post-type/165916) to get id's of a certain post type.
As @tomjnowell pointed out it works for list view but it's an expensive query.
One thing you can do is that add some meta value while uploading and query against that meta value |
231,185 | <p>I installed WordPress in my root directory <code>http://coinauctionshelp.com</code>. I want to redirect pages in the root to the new wordpress pages using an .htaccess file like this </p>
<p>301 redirect </p>
<pre><code>http://coinauctionshelp.com/United_States_Coin_Mintages_Price_Guides.html
http://coinauctionshelp.com/us-coin-values/
</code></pre>
<p>When I tried to do that I got a 500 internal server error so is there a quick fix for this?</p>
| [
{
"answer_id": 231201,
"author": "bravokeyl",
"author_id": 43098,
"author_profile": "https://wordpress.stackexchange.com/users/43098",
"pm_score": 4,
"selected": true,
"text": "<p>Media items are just like posts with <strong><code>post_type = attachment</code></strong> and <strong><code>... | 2016/07/01 | [
"https://wordpress.stackexchange.com/questions/231185",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/-1/"
] | I installed WordPress in my root directory `http://coinauctionshelp.com`. I want to redirect pages in the root to the new wordpress pages using an .htaccess file like this
301 redirect
```
http://coinauctionshelp.com/United_States_Coin_Mintages_Price_Guides.html
http://coinauctionshelp.com/us-coin-values/
```
When I tried to do that I got a 500 internal server error so is there a quick fix for this? | Media items are just like posts with **`post_type = attachment`** and **`post_status = inherit`**.
when we are on `upload.php` page, we have two views:
* List View
* Grid View
Grid view is populated via JavaScript and list view is extending normal **`WP_List_Table`**.
Since it (List view) is using normal post query we can use **`pre_get_posts`** to alter the query to hide required media items.
>
> How do we prevent these files from showing in the media library?
> Can
> we filter by post type?
>
>
>
We can't just filter the media items by `post_type` since media items post\_type is `attachment`. What you want is to filter media items by their **`post_parent's`** post ids.
```
add_action( 'load-upload.php' , 'wp_231165_load_media' );
function wp_231165_load_media() {
add_action('pre_get_posts','wp_231165_hide_media',10,1);
}
function wp_231165_hide_media($query){
global $pagenow;
// there is no need to check for update.php as we are already hooking to it, but anyway
if( 'upload.php' != $pagenow || !is_admin())
return;
if(is_main_query()){
$excluded_cpt_ids = array();//find a way to get all cpt post ids
$query->set('post_parent__not_in', $excluded_cpt_ids);
}
return $query;
}
```
Check [this question](https://wordpress.stackexchange.com/questions/165900/getting-the-ids-of-a-custom-post-type/165916) to get id's of a certain post type.
As @tomjnowell pointed out it works for list view but it's an expensive query.
One thing you can do is that add some meta value while uploading and query against that meta value |
231,212 | <p>How to get term by custom term meta and taxonomy or how to filter <code>tax_query</code> by term meta instead <code>slug</code>/<code>id</code>?</p>
<pre><code>function custom_pre_get_posts($query)
{
global $wp_query;
if ( !is_admin() && is_shop() && $query->is_main_query() && is_post_type_archive( "product" ))
{
$term = ???get_term_by_meta_and_taxonomy???('custom_meta_term','my_taxonomy');
$t_id = $term['term_id'];
$tax_query = array
(
array
(
'taxonomy' => 'my_taxoomy',
'field' => 'id',
'terms' => $t_id
)
);
$query->set( 'tax_query', $tax_query );
}
}
add_action( 'pre_get_posts', 'custom_pre_get_posts' );
</code></pre>
| [
{
"answer_id": 231242,
"author": "edwardr",
"author_id": 25724,
"author_profile": "https://wordpress.stackexchange.com/users/25724",
"pm_score": 2,
"selected": false,
"text": "<p>You'll need to loop through each of the terms in your main query conditional. Assuming there will likely be m... | 2016/07/01 | [
"https://wordpress.stackexchange.com/questions/231212",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/97619/"
] | How to get term by custom term meta and taxonomy or how to filter `tax_query` by term meta instead `slug`/`id`?
```
function custom_pre_get_posts($query)
{
global $wp_query;
if ( !is_admin() && is_shop() && $query->is_main_query() && is_post_type_archive( "product" ))
{
$term = ???get_term_by_meta_and_taxonomy???('custom_meta_term','my_taxonomy');
$t_id = $term['term_id'];
$tax_query = array
(
array
(
'taxonomy' => 'my_taxoomy',
'field' => 'id',
'terms' => $t_id
)
);
$query->set( 'tax_query', $tax_query );
}
}
add_action( 'pre_get_posts', 'custom_pre_get_posts' );
``` | Try This:
```
$args = array(
'hide_empty' => false, // also retrieve terms which are not used yet
'meta_query' => array(
array(
'key' => 'feature-group',
'value' => 'kitchen',
'compare' => 'LIKE'
)
),
'taxonomy' => 'category',
);
$terms = get_terms( $args );
``` |
231,229 | <p>I'm trying to determine if there's more than one page of comments in single.php. </p>
<p>In archive.php I can do something like this to check if there's more than one page of posts:</p>
<pre><code>if ( $wp_query->max_num_pages > 1 ) {
// There's more than one page of posts in this archive.
}
</code></pre>
<p>As far as I can tell, this doesn't work for comments. How can I check if comments are paginated in single.php?</p>
| [
{
"answer_id": 231237,
"author": "Ismail",
"author_id": 70833,
"author_profile": "https://wordpress.stackexchange.com/users/70833",
"pm_score": 1,
"selected": false,
"text": "<p>Try this, <code>get_option( 'page_comments' )</code> will check if pagination is checked in options > discussi... | 2016/07/01 | [
"https://wordpress.stackexchange.com/questions/231229",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/22599/"
] | I'm trying to determine if there's more than one page of comments in single.php.
In archive.php I can do something like this to check if there's more than one page of posts:
```
if ( $wp_query->max_num_pages > 1 ) {
// There's more than one page of posts in this archive.
}
```
As far as I can tell, this doesn't work for comments. How can I check if comments are paginated in single.php? | *Just some additional info for the main comment query:*
Since you mentioned the global `$wp_query` object, we can see that it stores:
```
$wp_query->max_num_comment_pages = $comment_query->max_num_pages;
```
in the main comment query in the comments template.
There [exists a wrapper](https://codex.wordpress.org/Function_Reference/get_comment_pages_count) for this, namely:
```
get_comment_pages_count();
```
that's available after the main comment query.
If we need it before the main comment query runs, then we might check if
`get_comments_number( $post_id )` is greater than `get_option( 'comments_per_page' )`. But we should keep in mind that the `comments_per_page` parameter can be modified through e.g. the `comments_template_query_args` filter. |
231,251 | <p>I have a typical shortcode which prints some html on a page. The shortcode will only be used on pages where visitors are logged in.</p>
<p>As a separate operation, I've been using a custom field to trigger an action which performs that test and then does the redirect.</p>
<p>But I was wondering if it was possible to combine that action into the shortcode and get rid of the custom field.</p>
<p>IOW: Can I make the shortcode print code in some tag in the header which tests to see if the visitor is logged in and if not, redirect them to the home page.</p>
<p>Eg.</p>
<pre><code>function jchForm() {
add_action( 'no idea where this would go', 'my_redirect_function' );
$s ='<div class="clearboth">';
$s .='<form id="my_form" action="" method="post">';
$s .='<p><label>Your Name</label><input id="user_name" type="text" name="user_name" class="text" value="" /></p>';
$s .='<p><label>Your Email Address</label><input id="user_email" type="text" name="user_email" class="text" value="" /></p>';
$s .='<p><input type="submit" id="my_submit" name="submit" value="Register" /></p>';
$s .='</form>';
$s .='</div>';
return $s;
</code></pre>
<p>}</p>
<p>UPDATE: I tried this, per the has_shortcode() function reference, but although it fires, $post always returns NULL. How do I get this to print -before- any other html but -after- the query grabs $post?</p>
<pre><code>function custom_shortcode_script() {
global $post;
if( is_user_logged_in() && has_shortcode( $post->post_content, 'jchForm') ) {
var_dump($post->post_content); // always prints NULL
wp_redirect( '/someplace');
}
}
add_action( 'init', 'custom_shortcode_script' );
</code></pre>
| [
{
"answer_id": 231254,
"author": "Andy Macaulay-Brook",
"author_id": 94267,
"author_profile": "https://wordpress.stackexchange.com/users/94267",
"pm_score": 5,
"selected": true,
"text": "<p>Shortcode functions are only called when the content of the visual editor is processed and display... | 2016/07/02 | [
"https://wordpress.stackexchange.com/questions/231251",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/17248/"
] | I have a typical shortcode which prints some html on a page. The shortcode will only be used on pages where visitors are logged in.
As a separate operation, I've been using a custom field to trigger an action which performs that test and then does the redirect.
But I was wondering if it was possible to combine that action into the shortcode and get rid of the custom field.
IOW: Can I make the shortcode print code in some tag in the header which tests to see if the visitor is logged in and if not, redirect them to the home page.
Eg.
```
function jchForm() {
add_action( 'no idea where this would go', 'my_redirect_function' );
$s ='<div class="clearboth">';
$s .='<form id="my_form" action="" method="post">';
$s .='<p><label>Your Name</label><input id="user_name" type="text" name="user_name" class="text" value="" /></p>';
$s .='<p><label>Your Email Address</label><input id="user_email" type="text" name="user_email" class="text" value="" /></p>';
$s .='<p><input type="submit" id="my_submit" name="submit" value="Register" /></p>';
$s .='</form>';
$s .='</div>';
return $s;
```
}
UPDATE: I tried this, per the has\_shortcode() function reference, but although it fires, $post always returns NULL. How do I get this to print -before- any other html but -after- the query grabs $post?
```
function custom_shortcode_script() {
global $post;
if( is_user_logged_in() && has_shortcode( $post->post_content, 'jchForm') ) {
var_dump($post->post_content); // always prints NULL
wp_redirect( '/someplace');
}
}
add_action( 'init', 'custom_shortcode_script' );
``` | Shortcode functions are only called when the content of the visual editor is processed and displayed, so nothing in your shortcode function will run early enough.
Have a look at the `has_shortcode` function. If you hook in early enough to send headers and late enough for the query to be set up you can check if the content contains your shortcode and redirect then. The template\_redirect hook is handy for this as it's about the last hook to be called before your theme sends output to the browser, which triggers PHP to send the headers. |
231,282 | <p>I can't find if WordPress stores the number of items in a menu. Basically I need to find out how many items are in a menu to work out the percentage each item should take up in the header bar. Is there a function? Or is the best way to achieve this doing something with <code>WP_Query</code>?</p>
| [
{
"answer_id": 231288,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 4,
"selected": true,
"text": "<p>I was curious and decided to check it out, regardless if it's relevant for a CSS problem ;-)</p>\n\n<p>I first... | 2016/07/02 | [
"https://wordpress.stackexchange.com/questions/231282",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/75780/"
] | I can't find if WordPress stores the number of items in a menu. Basically I need to find out how many items are in a menu to work out the percentage each item should take up in the header bar. Is there a function? Or is the best way to achieve this doing something with `WP_Query`? | I was curious and decided to check it out, regardless if it's relevant for a CSS problem ;-)
I first peeked into the database tables to find more about the menu structure:
Menu - building blocks
----------------------
Each navigational menu is registered as a term in the `nav_menu` taxonomy.
Then when we add items to that menu, we are creating new post objects of the type `nav_menu_item`.
Now the tricky part, where's the tree structure for that menu stored?
It's not the stored in the `post_parent` field of the `nav_menu_item` posts, as expected.
We actually find it in the post meta table where it's stored under the `_menu_item_menu_item_parent` meta key, for each `nav_menu_item` post.
Now there are various ways to get the count. Here are few examples:
Example - `get_term_by()` / `wp_get_nav_menu_object()`
------------------------------------------------------
First the easy one: If we need to get the number of items in a particular menu we can actually get it from a term query, because it's stored in the `count` column of the `wp_term_taxonomy` table.
First we get the menu term with:
```
$menuterm = get_term_by( 'slug', 'some-menu-slug', 'nav_menu' );
```
There's exists a wrapper for this, namely:
```
$menuterm = wp_get_nav_menu_object( 'some-menu-slug' );
```
To get the total count of items in the menu, we can then use:
```
$total_count = ( $menuterm instanceof \WP_Term ) ? $menuterm->count : 0;
```
Example - `WP_Query()` / `get_posts()`
--------------------------------------
If we only want to count menu items without parents, then we can collect all the post objects within our menu with:
```
if( $menuterm instanceof \WP_Term )
$pids = get_objects_in_term( $menuterm->term_id, 'nav_menu' );
```
where `$pids` is an array of post IDs.
Then we can make the following meta query:
```
$args = [
'post__in' => $pids,
'post_type' => 'nav_menu_item',
'fields' => 'ids',
'ignore_sticky_posts' => true,
'nopaging' => true,
'meta_query' => [
[
'key' => '_menu_item_menu_item_parent',
'value' => 0,
'compare' => '=',
]
]
];
$count = count( get_posts( $args ) );
```
There's also a way with:
```
$q = new WP_Query();
$count = count( $q->query( $args ) );
```
or just:
```
$count = $q->found_posts;
```
with the common trick, `posts_per_page` as 1, to reduce fetched data.
Example - `wp_get_nav_menu_items()`
-----------------------------------
There exists handy wrappers in core, like `wp_get_nav_menu_items( $menu, $args )` where `$args` are `get_posts()` arguments.
Here's one way:
```
$count = count(
wp_list_filter(
wp_get_nav_menu_items( 'some-menu-slug' ),
[ 'menu_item_parent' => 0 ]
)
);
```
We can also use:
```
$args = [
'meta_query' => [
[
'key' => '_menu_item_menu_item_parent',
'value' => 0,
'compare' => '=',
]
]
];
$count = count( wp_get_nav_menu_items( 'some-menu-slug', $args ) );
```
Example - filter/hooks
----------------------
There are many filters/actions that we could hook into to do the counting, e.g. the `wp_get_nav_menu_items` filter. Even hooks within the nav menu walker.
We could even hook into the `wp_update_nav_menu` that fires when the menu is updated. Then we could count the items with no parents and store it e.g. as term meta data.
Then there are also various ways with javascript.
Hopefully this will give you some ideas to take this further. |
231,296 | <p>A non-profit organisation (NPO) has a Wordpress website. The URL (example.com) carries the name of the NPO. The name of the NPO has changed so now we need to change the URL to reflect the new name. How do we do this, please?</p>
| [
{
"answer_id": 231309,
"author": "ido barnea",
"author_id": 97755,
"author_profile": "https://wordpress.stackexchange.com/users/97755",
"pm_score": 0,
"selected": false,
"text": "<p>If you already own name 2 as a domain,\nBuild your web site on it, and when you are done you can redirect ... | 2016/07/03 | [
"https://wordpress.stackexchange.com/questions/231296",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/97744/"
] | A non-profit organisation (NPO) has a Wordpress website. The URL (example.com) carries the name of the NPO. The name of the NPO has changed so now we need to change the URL to reflect the new name. How do we do this, please? | The easiest way is to use [search and replace for wordpress databases](https://interconnectit.com/products/search-and-replace-for-wordpress-databases/)
Then you should do a 301 redirect the old domain to the new domain to keep visitors and indexed in Google.
```
RewriteEngine On
RewriteCond %{HTTP_HOST} !^old-domain\.com [NC]
RewriteRule (.*) http://new-domain.com/$1 [R=301,L]
```
I hope I've helped you with my answer. |
231,327 | <p>How to configure .htaccess to this:
I need that my home page is <a href="http://mydomain.cl/c/news/" rel="nofollow">http://mydomain.cl/c/news/</a> but I cant do this.
Anyone want help me please?
Thanks!</p>
<p>Now, my htaccess is :</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>
</code></pre>
<h1>END WordPress</h1>
| [
{
"answer_id": 231309,
"author": "ido barnea",
"author_id": 97755,
"author_profile": "https://wordpress.stackexchange.com/users/97755",
"pm_score": 0,
"selected": false,
"text": "<p>If you already own name 2 as a domain,\nBuild your web site on it, and when you are done you can redirect ... | 2016/07/03 | [
"https://wordpress.stackexchange.com/questions/231327",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/73011/"
] | How to configure .htaccess to this:
I need that my home page is <http://mydomain.cl/c/news/> but I cant do this.
Anyone want help me please?
Thanks!
Now, my htaccess is :
```
# 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
============= | The easiest way is to use [search and replace for wordpress databases](https://interconnectit.com/products/search-and-replace-for-wordpress-databases/)
Then you should do a 301 redirect the old domain to the new domain to keep visitors and indexed in Google.
```
RewriteEngine On
RewriteCond %{HTTP_HOST} !^old-domain\.com [NC]
RewriteRule (.*) http://new-domain.com/$1 [R=301,L]
```
I hope I've helped you with my answer. |
231,348 | <p>I have a frustrating issue. I am using the <code>date_query</code> as referenced in the Codex: </p>
<pre><code><?php
$today = getdate();
$args = array(
'post_type' => 'Lighting',
'post_status' => 'publish',
'posts_per_page' => 1,
'date_query' => array(
array(
'year' => $today['year'],
'month' => $today['mon'],
'day' => $today['mday'],
),
),
);
$the_query = new WP_Query( $args );
</code></pre>
<p>While I can display custom posts as expected if I exclude <code>'day'</code>, I get no posts when it is included in the query. I am using <em>Advanced Custom Fields Pro</em> with the <code>date-picker</code>. I have no idea why this is happening, and I've searched tirelessly to determine why my <code>date_query</code> is not working. I am able to echo the date, so I don't understand where the disconnect is.</p>
<p>/****** RESPONSE TO ANSWERS ******/</p>
<p>Thanks for the responses. I have done a meta_query with what I think is the proper date format, but I am still unable to query only today's post. Here is the new query:</p>
<pre><code><?php // Let's get the data we need to loop through below
$args = array(
'post_type' => 'carillon', // Tell WordPress which post type we want
'orderby' => 'meta_value', // We want to organize the events by date
'meta_key' => 'date_of_lighting', // Grab the "date_of_event" field created via "date-picker" plugin (stored in ‘YYYYMMDD’)
'posts_per_page' => '1', // Let's show just one post.
'meta_query' => array( // WordPress has all the results, now, return only the event on today's date
array(
'key' => 'date_of_lighting', // Check the s"date_of_lighting field
'value' => date("Y-M-D"), // Set today's date (note the similar format)
'compare' => '=', // Return only today's post
'type' => 'NUMERIC' // Let WordPress know we're working with numbers
)
)
);
</code></pre>
<p>Any suggestions? Thanks, again.</p>
<p>/******** SOLUTION **********/</p>
<p>Hi Everyone,</p>
<p>So, I found a solution that works. I changed the type to "DATE". It's interesting that in other examples where folks want to show todays date and beyond, they use a "Numeric" type. I guess it makes some sense, but I'm going to jump into the Codex to understand this more. I appreciate all of your help. Here is the solution that works:</p>
<pre><code> <?php // Let's get the data we need to loop through below
$args = array(
'post_type' => 'carillon', // Tell WordPress which post type we want
'orderby' => 'meta_value', // We want to organize the events by date
'meta_key' => 'date_of_lighting', // Grab the "date_of_event" field created via "date-picker" plugin (stored in ‘YYYYMMDD’)
'posts_per_page' => '1', // Let's show just one post.
'meta_query' => array( // WordPress has all the results, now, return only the event for today's date
array(
'key' => 'date_of_lighting', // Check the s"date_of_lighting field
'value' => date("Y-m-d"), // Set today's date (note the similar format)
'compare' => '=', // Return only today's post
'type' => 'DATE' // Let WordPress know we're working with a date
)
)
);
</code></pre>
| [
{
"answer_id": 231309,
"author": "ido barnea",
"author_id": 97755,
"author_profile": "https://wordpress.stackexchange.com/users/97755",
"pm_score": 0,
"selected": false,
"text": "<p>If you already own name 2 as a domain,\nBuild your web site on it, and when you are done you can redirect ... | 2016/07/04 | [
"https://wordpress.stackexchange.com/questions/231348",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/97783/"
] | I have a frustrating issue. I am using the `date_query` as referenced in the Codex:
```
<?php
$today = getdate();
$args = array(
'post_type' => 'Lighting',
'post_status' => 'publish',
'posts_per_page' => 1,
'date_query' => array(
array(
'year' => $today['year'],
'month' => $today['mon'],
'day' => $today['mday'],
),
),
);
$the_query = new WP_Query( $args );
```
While I can display custom posts as expected if I exclude `'day'`, I get no posts when it is included in the query. I am using *Advanced Custom Fields Pro* with the `date-picker`. I have no idea why this is happening, and I've searched tirelessly to determine why my `date_query` is not working. I am able to echo the date, so I don't understand where the disconnect is.
/\*\*\*\*\*\* RESPONSE TO ANSWERS \*\*\*\*\*\*/
Thanks for the responses. I have done a meta\_query with what I think is the proper date format, but I am still unable to query only today's post. Here is the new query:
```
<?php // Let's get the data we need to loop through below
$args = array(
'post_type' => 'carillon', // Tell WordPress which post type we want
'orderby' => 'meta_value', // We want to organize the events by date
'meta_key' => 'date_of_lighting', // Grab the "date_of_event" field created via "date-picker" plugin (stored in ‘YYYYMMDD’)
'posts_per_page' => '1', // Let's show just one post.
'meta_query' => array( // WordPress has all the results, now, return only the event on today's date
array(
'key' => 'date_of_lighting', // Check the s"date_of_lighting field
'value' => date("Y-M-D"), // Set today's date (note the similar format)
'compare' => '=', // Return only today's post
'type' => 'NUMERIC' // Let WordPress know we're working with numbers
)
)
);
```
Any suggestions? Thanks, again.
/\*\*\*\*\*\*\*\* SOLUTION \*\*\*\*\*\*\*\*\*\*/
Hi Everyone,
So, I found a solution that works. I changed the type to "DATE". It's interesting that in other examples where folks want to show todays date and beyond, they use a "Numeric" type. I guess it makes some sense, but I'm going to jump into the Codex to understand this more. I appreciate all of your help. Here is the solution that works:
```
<?php // Let's get the data we need to loop through below
$args = array(
'post_type' => 'carillon', // Tell WordPress which post type we want
'orderby' => 'meta_value', // We want to organize the events by date
'meta_key' => 'date_of_lighting', // Grab the "date_of_event" field created via "date-picker" plugin (stored in ‘YYYYMMDD’)
'posts_per_page' => '1', // Let's show just one post.
'meta_query' => array( // WordPress has all the results, now, return only the event for today's date
array(
'key' => 'date_of_lighting', // Check the s"date_of_lighting field
'value' => date("Y-m-d"), // Set today's date (note the similar format)
'compare' => '=', // Return only today's post
'type' => 'DATE' // Let WordPress know we're working with a date
)
)
);
``` | The easiest way is to use [search and replace for wordpress databases](https://interconnectit.com/products/search-and-replace-for-wordpress-databases/)
Then you should do a 301 redirect the old domain to the new domain to keep visitors and indexed in Google.
```
RewriteEngine On
RewriteCond %{HTTP_HOST} !^old-domain\.com [NC]
RewriteRule (.*) http://new-domain.com/$1 [R=301,L]
```
I hope I've helped you with my answer. |
231,361 | <p>I am trying to create a custom post type. All are working fine except archive page. My custom post type archive page is archive-courses.php but is is not working it is showing default archive.php . Is there any wrong in my code? </p>
<p>Can anyone help me, please? </p>
<pre><code>function td_courses() {
$labels = array(
'name' => _x( 'Courses', 'td' ),
'singular_name' => _x( 'Courses', 'td' ),
'add_new' => _x( 'Add New', 'td' ),
'add_new_item' => __( 'Add New course' ),
'edit_item' => __( 'Edit course' ),
'new_item' => __( 'New courses' ),
'all_items' => __( 'Courses' ),
'view_item' => __( 'View courses' ),
'search_items' => __( 'Search courses' ),
'not_found' => __( 'No courses found' ),
'not_found_in_trash' => __( 'No courses found in the Trash' ),
'menu_name' => 'Courses'
);
$args = array(
'labels' => $labels,
'public' => true,
'menu_position' => 10,
'menu_icon' => 'dashicons-welcome-learn-more',
'supports' => array( 'title', 'editor', 'thumbnail', 'author' ),
'has_archive' => true,
'capability_type' => 'page',
'rewrite' => array( 'slug' => 'course' ),
);
register_post_type( 'courses', $args );
}
add_action( 'init', 'td_courses' );
function td_courses_taxonomies() {
$labels = array(
'name' => _x( 'Course Categories', 'td' ),
'singular_name' => _x( 'Course Categories', 'td' ),
'search_items' => __( 'Search Course Categorie' ),
'all_items' => __( 'All Course Categories' ),
'parent_item' => __( 'Parent Course Categorie' ),
'parent_item_colon' => __( 'Parent Course Categorie:' ),
'edit_item' => __( 'Edit Course Categorie' ),
'update_item' => __( 'Update Course Categorie' ),
'add_new_item' => __( 'Add New Course Categorie' ),
'new_item_name' => __( 'New Course Categorie Name' ),
'menu_name' => __( 'Course Categorie' ),
);
$args = array(
'hierarchical' => true,
'labels' => $labels,
'show_ui' => true,
'show_admin_column' => true,
'query_var' => true,
'rewrite' => array( 'slug' => 'courses-list' ),
);
register_taxonomy( 'courses_category', array( 'courses' ), $args );
}
add_action( 'init', 'td_courses_taxonomies', 0 );
</code></pre>
<p>Thanks </p>
| [
{
"answer_id": 231365,
"author": "NateWr",
"author_id": 39309,
"author_profile": "https://wordpress.stackexchange.com/users/39309",
"pm_score": 3,
"selected": false,
"text": "<p>Your post type, <code>courses</code>, has a rewrite slug of <code>course</code>. So your archive template will... | 2016/07/04 | [
"https://wordpress.stackexchange.com/questions/231361",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/73498/"
] | I am trying to create a custom post type. All are working fine except archive page. My custom post type archive page is archive-courses.php but is is not working it is showing default archive.php . Is there any wrong in my code?
Can anyone help me, please?
```
function td_courses() {
$labels = array(
'name' => _x( 'Courses', 'td' ),
'singular_name' => _x( 'Courses', 'td' ),
'add_new' => _x( 'Add New', 'td' ),
'add_new_item' => __( 'Add New course' ),
'edit_item' => __( 'Edit course' ),
'new_item' => __( 'New courses' ),
'all_items' => __( 'Courses' ),
'view_item' => __( 'View courses' ),
'search_items' => __( 'Search courses' ),
'not_found' => __( 'No courses found' ),
'not_found_in_trash' => __( 'No courses found in the Trash' ),
'menu_name' => 'Courses'
);
$args = array(
'labels' => $labels,
'public' => true,
'menu_position' => 10,
'menu_icon' => 'dashicons-welcome-learn-more',
'supports' => array( 'title', 'editor', 'thumbnail', 'author' ),
'has_archive' => true,
'capability_type' => 'page',
'rewrite' => array( 'slug' => 'course' ),
);
register_post_type( 'courses', $args );
}
add_action( 'init', 'td_courses' );
function td_courses_taxonomies() {
$labels = array(
'name' => _x( 'Course Categories', 'td' ),
'singular_name' => _x( 'Course Categories', 'td' ),
'search_items' => __( 'Search Course Categorie' ),
'all_items' => __( 'All Course Categories' ),
'parent_item' => __( 'Parent Course Categorie' ),
'parent_item_colon' => __( 'Parent Course Categorie:' ),
'edit_item' => __( 'Edit Course Categorie' ),
'update_item' => __( 'Update Course Categorie' ),
'add_new_item' => __( 'Add New Course Categorie' ),
'new_item_name' => __( 'New Course Categorie Name' ),
'menu_name' => __( 'Course Categorie' ),
);
$args = array(
'hierarchical' => true,
'labels' => $labels,
'show_ui' => true,
'show_admin_column' => true,
'query_var' => true,
'rewrite' => array( 'slug' => 'courses-list' ),
);
register_taxonomy( 'courses_category', array( 'courses' ), $args );
}
add_action( 'init', 'td_courses_taxonomies', 0 );
```
Thanks | Your post type, `courses`, has a rewrite slug of `course`. So your archive template will be `archive-course.php`.
Your taxonomy, `courses_category`, has a rewrite slug of `course`, so your taxonomy archive template will be `taxonomy-courses.php`.
This complete [template hierarchy](https://developer.wordpress.org/themes/basics/template-hierarchy/#visual-overview) can be useful.
If you want an archive page showing *all* posts of the post type `courses` at `yoursite.com/courses`, you should assign the post type a rewrite slug of `courses`. (I believe this is the default since your post type is `courses`.)
The taxonomy archive template, `taxonomy-[slug].php`, will be invoked when viewing an archive page of all posts of the post type `courses` assigned to a specific taxonomy term. So if you had a term `beginner`, and the rewrite slug `courses` for the taxonomy term, you'd see an archive of beginner courses at `yoursite.com/courses/beginner`.
If you assign the same rewrite slug to the post type and the taxonomy, you may get some clashing. But I'm not sure.
As Pieter Goosen said, you will need to flush the rewrite rules whenever you make changes like this. |
231,362 | <p>Here I mentioned the url</p>
<pre><code>http://localhost/wp/2016/?category_name=cricket
</code></pre>
<p>now i need to rearrange the url like </p>
<pre><code>http://localhost/wp/cricket/2016.
</code></pre>
<p>here cricket is category name and 2016 is year.</p>
<p>Remove the ?Query String Variable not a value of the querystring in the wordpress URl.</p>
<p>I tried </p>
<pre><code>RewriteRule ^([0-9]{4})/?$/(.+)/([^/]+)/?$ /index.php/$1/?category_name=$2[QSA,L]
</code></pre>
<p>But Not Working</p>
| [
{
"answer_id": 231365,
"author": "NateWr",
"author_id": 39309,
"author_profile": "https://wordpress.stackexchange.com/users/39309",
"pm_score": 3,
"selected": false,
"text": "<p>Your post type, <code>courses</code>, has a rewrite slug of <code>course</code>. So your archive template will... | 2016/07/04 | [
"https://wordpress.stackexchange.com/questions/231362",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/97782/"
] | Here I mentioned the url
```
http://localhost/wp/2016/?category_name=cricket
```
now i need to rearrange the url like
```
http://localhost/wp/cricket/2016.
```
here cricket is category name and 2016 is year.
Remove the ?Query String Variable not a value of the querystring in the wordpress URl.
I tried
```
RewriteRule ^([0-9]{4})/?$/(.+)/([^/]+)/?$ /index.php/$1/?category_name=$2[QSA,L]
```
But Not Working | Your post type, `courses`, has a rewrite slug of `course`. So your archive template will be `archive-course.php`.
Your taxonomy, `courses_category`, has a rewrite slug of `course`, so your taxonomy archive template will be `taxonomy-courses.php`.
This complete [template hierarchy](https://developer.wordpress.org/themes/basics/template-hierarchy/#visual-overview) can be useful.
If you want an archive page showing *all* posts of the post type `courses` at `yoursite.com/courses`, you should assign the post type a rewrite slug of `courses`. (I believe this is the default since your post type is `courses`.)
The taxonomy archive template, `taxonomy-[slug].php`, will be invoked when viewing an archive page of all posts of the post type `courses` assigned to a specific taxonomy term. So if you had a term `beginner`, and the rewrite slug `courses` for the taxonomy term, you'd see an archive of beginner courses at `yoursite.com/courses/beginner`.
If you assign the same rewrite slug to the post type and the taxonomy, you may get some clashing. But I'm not sure.
As Pieter Goosen said, you will need to flush the rewrite rules whenever you make changes like this. |
231,374 | <p>I need to get the comment author ID by the comment ID.</p>
<p><strong>Example</strong></p>
<pre><code>functionName($commentID){
return $authorID;
}
</code></pre>
| [
{
"answer_id": 231399,
"author": "jgraup",
"author_id": 84219,
"author_profile": "https://wordpress.stackexchange.com/users/84219",
"pm_score": 2,
"selected": false,
"text": "<p>Use <a href=\"https://codex.wordpress.org/Function_Reference/get_comment\" rel=\"nofollow\"><code>get_comment<... | 2016/07/04 | [
"https://wordpress.stackexchange.com/questions/231374",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/97801/"
] | I need to get the comment author ID by the comment ID.
**Example**
```
functionName($commentID){
return $authorID;
}
``` | Use [`get_comment`](https://codex.wordpress.org/Function_Reference/get_comment) to return information about the comment like `comment_author_email`.
You can then try to get a user by email using [`get_user_by`('email', $comment\_author\_email)](https://developer.wordpress.org/reference/functions/get_user_by/).
Once you have the [`WP_User`](https://codex.wordpress.org/Class_Reference/WP_User) you should be able to access the `ID` of that user.
*All of this assumes, the comment author's email is used as the user's registration email.* |
231,377 | <p>Why file <code>plugins/woocommerce/assets/css/woocommerce.css</code>
for my template can not be read?</p>
<p>Please look this image :</p>
<p><a href="https://i.stack.imgur.com/1miMt.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1miMt.png" alt="enter image description here"></a></p>
| [
{
"answer_id": 231401,
"author": "Praveen",
"author_id": 97802,
"author_profile": "https://wordpress.stackexchange.com/users/97802",
"pm_score": 1,
"selected": false,
"text": "<pre><code>function woocommmerce_style() {\n wp_enqueue_style('woocommerce_stylesheet', WP_PLUGIN_URL. '/wooco... | 2016/07/04 | [
"https://wordpress.stackexchange.com/questions/231377",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/97803/"
] | Why file `plugins/woocommerce/assets/css/woocommerce.css`
for my template can not be read?
Please look this image :
[](https://i.stack.imgur.com/1miMt.png) | ```
function woocommmerce_style() {
wp_enqueue_style('woocommerce_stylesheet', WP_PLUGIN_URL. '/woocommerce/assets/css/woocommerce.css',false,'1.0',"all");
}
add_action( 'wp_head', 'woocommmerce_style' );
```
paste the above code in your "functions.php". woocommerce stylesheet will be executed to your site |
231,391 | <p>I have a site which uses Google's API's for jquery and a fallback for jquery. The problem is that I can't get the fallback to happen immediately after the jquery api attempt. What happens is that the fallback file is added after a range of plugin scripts which require jquery and then fails. How can I change the order or location where these plugin scripts are added? Below just gives me the registered files:</p>
<pre><code>var_dump( $GLOBALS['wp_scripts']->registered );
</code></pre>
| [
{
"answer_id": 231401,
"author": "Praveen",
"author_id": 97802,
"author_profile": "https://wordpress.stackexchange.com/users/97802",
"pm_score": 1,
"selected": false,
"text": "<pre><code>function woocommmerce_style() {\n wp_enqueue_style('woocommerce_stylesheet', WP_PLUGIN_URL. '/wooco... | 2016/07/04 | [
"https://wordpress.stackexchange.com/questions/231391",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/94998/"
] | I have a site which uses Google's API's for jquery and a fallback for jquery. The problem is that I can't get the fallback to happen immediately after the jquery api attempt. What happens is that the fallback file is added after a range of plugin scripts which require jquery and then fails. How can I change the order or location where these plugin scripts are added? Below just gives me the registered files:
```
var_dump( $GLOBALS['wp_scripts']->registered );
``` | ```
function woocommmerce_style() {
wp_enqueue_style('woocommerce_stylesheet', WP_PLUGIN_URL. '/woocommerce/assets/css/woocommerce.css',false,'1.0',"all");
}
add_action( 'wp_head', 'woocommmerce_style' );
```
paste the above code in your "functions.php". woocommerce stylesheet will be executed to your site |
231,394 | <p>I've got several search forms on my site and I want them to show different results. My website has a very strict hierarchy and the search form on a parent site should only show results from it's child pages.</p>
<p>My plan was to include different hidden fields on the different parent pages which contain the id of that particular page. In the <code>search.php</code> I then wanted to process the results and filter out the pages and posts that have no relation to the parent page.</p>
<p>Is there an easy way on how to achieve this?</p>
<p>Thanks in advance.</p>
<p><strong>EDIT 1</strong>
<hr>
This is my <code>search.php</code></p>
<pre><code><?php
if (have_posts()){
while(have_posts()){
the_post(); ?>
<div>
<h4><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h4>
<p><?php echo get_the_author(); ?> - <?php echo get_the_date(); ?></p>
<p><?php echo get_the_excerpt(); ?></p>
</div>
<?php
}
} else{ ?>
<h3>Sorry</h3>
<p>We are sorry but we could not find any matching articles on our site. Please try again with an other search request.</p>
<?php
get_search_form ();
}
?>
</code></pre>
<p>And the <code>searchform.php</code>:</p>
<pre><code><form role="search" method="get" id="searchform" action="<?php echo esc_url( home_url( '/' ) ); ?>">
<label>Search...</label>
<input type="text" name="s" id="s" value="<?php echo get_search_query(); ?>" placeholder="Search..." />
<input type="hidden" name="post_parent" value="<?php echo (int)get_the_ID(); ?>" />
<button type="submit"><i class="fa fa-search" aria-hidden="true"></i></button>
</form>
</code></pre>
<p><strong>EDIT 2</strong></p>
<p>I also added <code><?php wp_reset_query(); ?></code> before the <code>if(have_posts()){}</code>. This results in no change. The pages are still shown.</p>
| [
{
"answer_id": 231408,
"author": "user1049961",
"author_id": 47664,
"author_profile": "https://wordpress.stackexchange.com/users/47664",
"pm_score": 1,
"selected": false,
"text": "<p>You can use <code>pre_get_posts</code> filter to filter out what you need. There's an example on how to d... | 2016/07/04 | [
"https://wordpress.stackexchange.com/questions/231394",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/93282/"
] | I've got several search forms on my site and I want them to show different results. My website has a very strict hierarchy and the search form on a parent site should only show results from it's child pages.
My plan was to include different hidden fields on the different parent pages which contain the id of that particular page. In the `search.php` I then wanted to process the results and filter out the pages and posts that have no relation to the parent page.
Is there an easy way on how to achieve this?
Thanks in advance.
**EDIT 1**
---
This is my `search.php`
```
<?php
if (have_posts()){
while(have_posts()){
the_post(); ?>
<div>
<h4><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h4>
<p><?php echo get_the_author(); ?> - <?php echo get_the_date(); ?></p>
<p><?php echo get_the_excerpt(); ?></p>
</div>
<?php
}
} else{ ?>
<h3>Sorry</h3>
<p>We are sorry but we could not find any matching articles on our site. Please try again with an other search request.</p>
<?php
get_search_form ();
}
?>
```
And the `searchform.php`:
```
<form role="search" method="get" id="searchform" action="<?php echo esc_url( home_url( '/' ) ); ?>">
<label>Search...</label>
<input type="text" name="s" id="s" value="<?php echo get_search_query(); ?>" placeholder="Search..." />
<input type="hidden" name="post_parent" value="<?php echo (int)get_the_ID(); ?>" />
<button type="submit"><i class="fa fa-search" aria-hidden="true"></i></button>
</form>
```
**EDIT 2**
I also added `<?php wp_reset_query(); ?>` before the `if(have_posts()){}`. This results in no change. The pages are still shown. | You can use `pre_get_posts` filter to filter out what you need. There's an example on how to do this in Codex:
<https://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts#Exclude_Pages_from_Search_Results>
```
function search_filter($query) {
if ( !is_admin() && $query->is_main_query() ) {
if ($query->is_search) {
$query->set('post_type', 'post');
}
}
}
add_action('pre_get_posts','search_filter');
```
Also, [this](http://www.billerickson.net/wordpress-search-post-type/) article might get you in the direction of editing the search form... |
231,407 | <p>I am using the <a href="https://wordpress.org/plugins/wp-job-manager/" rel="nofollow">wp-job-manager plugin</a> and i want to add an Adsense code between the job listings ( after fifth job listing ) in the page with [jobs] shortcode.</p>
<p>The function that outputs the jobs resides in <a href="https://github.com/Automattic/WP-Job-Manager/blob/master/includes/class-wp-job-manager-shortcodes.php" rel="nofollow"><code>class-wp-job-manager-shortcodes.php</code></a> <strong>function <code>output_jobs( $atts )</code></strong></p>
<p>Because i don't know how to start to add that Adsense code to this function using action hooks or what else i need some help to make it work.</p>
| [
{
"answer_id": 231409,
"author": "user1049961",
"author_id": 47664,
"author_profile": "https://wordpress.stackexchange.com/users/47664",
"pm_score": 1,
"selected": false,
"text": "<p>There's a filter for the output</p>\n\n<pre><code> $job_listings_output = apply_filters( 'job_manager_... | 2016/07/04 | [
"https://wordpress.stackexchange.com/questions/231407",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/96329/"
] | I am using the [wp-job-manager plugin](https://wordpress.org/plugins/wp-job-manager/) and i want to add an Adsense code between the job listings ( after fifth job listing ) in the page with [jobs] shortcode.
The function that outputs the jobs resides in [`class-wp-job-manager-shortcodes.php`](https://github.com/Automattic/WP-Job-Manager/blob/master/includes/class-wp-job-manager-shortcodes.php) **function `output_jobs( $atts )`**
Because i don't know how to start to add that Adsense code to this function using action hooks or what else i need some help to make it work. | There's a filter for the output
```
$job_listings_output = apply_filters( 'job_manager_job_listings_output', ob_get_clean() );
```
so, you should just do
```
add_filter('job_manager_job_listings_output','my_job_manager_job_listings_output');
function my_job_manager_job_listings_output($output) {
$adsense_code = ' My adsense code';
return $output . $adsence_code;
}
``` |
231,415 | <p>I have a contact form in a WordPress page like this:</p>
<pre><code>$( '#contact_form' ).bootstrapValidator({
fields: {
// ...
},
submitHandler: function( formInstance ) {
$.post( "../send-message", $("#contact_form").serialize(), function( result ) {
alert( pw_script_vars.State );
});
}
});
</code></pre>
<p>When the form is submitted using the Ajax request it goes to another WordPress page titled <code>/send-message</code> that has PHP code to send an email, then it should return a success or failure value to the Ajax request to alert a success or failure message. I have tried using the <code>wp_localize_script</code> function in the <code>functions.php</code> file using a fixed value and it worked fine:</p>
<pre><code>function enqueue_scripts() {
wp_enqueue_script( 'pw_script', get_stylesheet_directory_uri().'/inc/js/functions.min.js', array( 'jquery' ) );
wp_localize_script( 'pw_script', 'pw_script_vars', array( 'State' => 'success' ) );
}
add_action( 'wp_enqueue_scripts', 'enqueue_scripts' );
</code></pre>
<p>But when I tried to use the <code>wp_localize_script</code> in the <code>/send-message</code> WordPress page it failed to work. Here are the contents of the '/send-message' page :</p>
<pre><code><?php
$sendSuccess = sendMessage();
if( $sendSuccess )
wp_localize_script( 'pw_script', 'pw_script_vars', array( 'State' => 'success' ) );
else
wp_localize_script( 'pw_script', 'pw_script_vars', array( 'State' => 'failure' ) );
function sendMessage() {
//This function will send the email then it will return true or false.
}
?>
</code></pre>
<p>Using <code>wp_localize_script</code> in the <code>/send-message</code> causes an undefined variable <code>pw_script_vars</code> in the JavaScript file.</p>
<p>How can I use <code>wp_localize_script</code> in a WordPress page other than <code>functions.php</code>?</p>
| [
{
"answer_id": 231418,
"author": "user1049961",
"author_id": 47664,
"author_profile": "https://wordpress.stackexchange.com/users/47664",
"pm_score": 2,
"selected": false,
"text": "<p>You cannot use <code>wp_localize_script</code> in page template. You have to use it in <code>functions.ph... | 2016/07/04 | [
"https://wordpress.stackexchange.com/questions/231415",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/97480/"
] | I have a contact form in a WordPress page like this:
```
$( '#contact_form' ).bootstrapValidator({
fields: {
// ...
},
submitHandler: function( formInstance ) {
$.post( "../send-message", $("#contact_form").serialize(), function( result ) {
alert( pw_script_vars.State );
});
}
});
```
When the form is submitted using the Ajax request it goes to another WordPress page titled `/send-message` that has PHP code to send an email, then it should return a success or failure value to the Ajax request to alert a success or failure message. I have tried using the `wp_localize_script` function in the `functions.php` file using a fixed value and it worked fine:
```
function enqueue_scripts() {
wp_enqueue_script( 'pw_script', get_stylesheet_directory_uri().'/inc/js/functions.min.js', array( 'jquery' ) );
wp_localize_script( 'pw_script', 'pw_script_vars', array( 'State' => 'success' ) );
}
add_action( 'wp_enqueue_scripts', 'enqueue_scripts' );
```
But when I tried to use the `wp_localize_script` in the `/send-message` WordPress page it failed to work. Here are the contents of the '/send-message' page :
```
<?php
$sendSuccess = sendMessage();
if( $sendSuccess )
wp_localize_script( 'pw_script', 'pw_script_vars', array( 'State' => 'success' ) );
else
wp_localize_script( 'pw_script', 'pw_script_vars', array( 'State' => 'failure' ) );
function sendMessage() {
//This function will send the email then it will return true or false.
}
?>
```
Using `wp_localize_script` in the `/send-message` causes an undefined variable `pw_script_vars` in the JavaScript file.
How can I use `wp_localize_script` in a WordPress page other than `functions.php`? | You cannot use `wp_localize_script` in page template. You have to use it in `functions.php` or your custom plugin, after you register your script, which is usually in the `wp_enqueue_scripts` action.
<https://codex.wordpress.org/Function_Reference/wp_localize_script> |
231,424 | <p>If I'm just echoing regular text, I do this:</p>
<pre><code><?php _e('This post is closed to new comments.','my-theme') ?>
</code></pre>
<p>But how would I translate the text in <code>comments_number();</code> so that the "Comments" text can be translated? Like this:</p>
<pre><code><?php comments_number( 'Comments (0)', 'Comments (1)', 'Comments (%)' ); ?>
</code></pre>
| [
{
"answer_id": 231426,
"author": "user1049961",
"author_id": 47664,
"author_profile": "https://wordpress.stackexchange.com/users/47664",
"pm_score": -1,
"selected": false,
"text": "<p>The <code>comments_number</code> function is calling <code>get_comments_number_text</code> function: <a ... | 2016/07/04 | [
"https://wordpress.stackexchange.com/questions/231424",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/91783/"
] | If I'm just echoing regular text, I do this:
```
<?php _e('This post is closed to new comments.','my-theme') ?>
```
But how would I translate the text in `comments_number();` so that the "Comments" text can be translated? Like this:
```
<?php comments_number( 'Comments (0)', 'Comments (1)', 'Comments (%)' ); ?>
``` | You have to make these strings translatable by using `__()` function:
```
comments_number( __('Comments (0)'), __('Comments (1)'), __('Comments (%)') );
```
If you want to use the custom `textdomain`, e.g. `'test'`:
```
comments_number( __('Comments (0)', 'test'), __('Comments (1)', 'test'), __('Comments (%)', 'test') );
```
For more information see:
* [\_\_()](https://codex.wordpress.org/Function_Reference/_2)
* [Theme internationalization](https://developer.wordpress.org/themes/functionality/internationalization/)
* Very good article by Samuel Wood a.k.a. Otto: [Internationalization: You’re probably doing it wrong](http://ottopress.com/2012/internationalization-youre-probably-doing-it-wrong/). |
231,448 | <p>How to add dot(<code>.</code>) in post slugs?</p>
<p>In our blog, we are writing about websites and would like to use their exact address as slug like this:</p>
<p><code>ourdomain.com/<strong>example1.com</strong></code></p>
<p>But dots are either removed when a post is saved, or WordPress doesn't find the post when we successfully add one.</p>
<p>Is there any option available?</p>
| [
{
"answer_id": 231952,
"author": "Andy",
"author_id": 43719,
"author_profile": "https://wordpress.stackexchange.com/users/43719",
"pm_score": 3,
"selected": true,
"text": "<p>WordPress runs slugs through its <code>sanitize_title_with_dashes()</code> filter function which replaces dots wi... | 2016/07/05 | [
"https://wordpress.stackexchange.com/questions/231448",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/48647/"
] | How to add dot(`.`) in post slugs?
In our blog, we are writing about websites and would like to use their exact address as slug like this:
`ourdomain.com/**example1.com**`
But dots are either removed when a post is saved, or WordPress doesn't find the post when we successfully add one.
Is there any option available? | WordPress runs slugs through its `sanitize_title_with_dashes()` filter function which replaces dots with dashes. Unfortunately the function doesn't give you any control over that or any ability to change what characters are stripped or replaced.
What we can do however is remove that filter and add our own version of it with a couple of modifications:
```
remove_filter( 'sanitize_title', 'sanitize_title_with_dashes', 10 );
add_filter( 'sanitize_title', 'wpse231448_sanitize_title_with_dashes', 10, 3 );
function wpse231448_sanitize_title_with_dashes( $title, $raw_title = '', $context = 'display' ) {
$title = strip_tags($title);
// Preserve escaped octets.
$title = preg_replace('|%([a-fA-F0-9][a-fA-F0-9])|', '---$1---', $title);
// Remove percent signs that are not part of an octet.
$title = str_replace('%', '', $title);
// Restore octets.
$title = preg_replace('|---([a-fA-F0-9][a-fA-F0-9])---|', '%$1', $title);
if (seems_utf8($title)) {
if (function_exists('mb_strtolower')) {
$title = mb_strtolower($title, 'UTF-8');
}
$title = utf8_uri_encode($title, 200);
}
$title = strtolower($title);
if ( 'save' == $context ) {
// Convert nbsp, ndash and mdash to hyphens
$title = str_replace( array( '%c2%a0', '%e2%80%93', '%e2%80%94' ), '-', $title );
// Convert nbsp, ndash and mdash HTML entities to hyphens
$title = str_replace( array( ' ', ' ', '–', '–', '—', '—' ), '-', $title );
// Strip these characters entirely
$title = str_replace( array(
// iexcl and iquest
'%c2%a1', '%c2%bf',
// angle quotes
'%c2%ab', '%c2%bb', '%e2%80%b9', '%e2%80%ba',
// curly quotes
'%e2%80%98', '%e2%80%99', '%e2%80%9c', '%e2%80%9d',
'%e2%80%9a', '%e2%80%9b', '%e2%80%9e', '%e2%80%9f',
// copy, reg, deg, hellip and trade
'%c2%a9', '%c2%ae', '%c2%b0', '%e2%80%a6', '%e2%84%a2',
// acute accents
'%c2%b4', '%cb%8a', '%cc%81', '%cd%81',
// grave accent, macron, caron
'%cc%80', '%cc%84', '%cc%8c',
), '', $title );
// Convert times to x
$title = str_replace( '%c3%97', 'x', $title );
}
$title = preg_replace('/&.+?;/', '', $title); // kill entities
// WPSE-231448: Commented out this line below to stop dots being replaced by dashes.
//$title = str_replace('.', '-', $title);
// WPSE-231448: Add the dot to the list of characters NOT to be stripped.
$title = preg_replace('/[^%a-z0-9 _\-\.]/', '', $title);
$title = preg_replace('/\s+/', '-', $title);
$title = preg_replace('|-+|', '-', $title);
$title = trim($title, '-');
return $title;
}
```
The lines I edited are commented with a "WPSE-231448" - First I commented out the line which does a `str_replace()` and replaces dots with dashes, then I added the dot to the list of characters to NOT be replaced in the `preg_replace()` function below that.
Please note that I have not tested this with pagination or anything like that, it simply stops dots being stripped from slugs on the front/backend and any issues that may arise from that will need to be handled accordingly. |
231,469 | <p>I basically need to change the date format to german date format all over the WordPress site and I succeed it by changing the date time settings from the WordPress admin panel.</p>
<blockquote>
<p><strong>Settings » General</strong> :</p>
<p><strong>Date Format</strong> - Custom : j. F Y</p>
<p>eg : 5. July 2016</p>
</blockquote>
<p>However I need to change the month names to german as well.</p>
<blockquote>
<p>eg : 5. Juli 2016</p>
</blockquote>
<p>How should I do that ?</p>
| [
{
"answer_id": 231472,
"author": "Aipo",
"author_id": 67135,
"author_profile": "https://wordpress.stackexchange.com/users/67135",
"pm_score": 1,
"selected": false,
"text": "<p>Use locale in <code>wp-config.php</code> de_DE, language settings depends on admin panel language, it is possibl... | 2016/07/05 | [
"https://wordpress.stackexchange.com/questions/231469",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/68403/"
] | I basically need to change the date format to german date format all over the WordPress site and I succeed it by changing the date time settings from the WordPress admin panel.
>
> **Settings » General** :
>
>
> **Date Format** - Custom : j. F Y
>
>
> eg : 5. July 2016
>
>
>
However I need to change the month names to german as well.
>
> eg : 5. Juli 2016
>
>
>
How should I do that ? | I have added the following code to child theme function and it works,
```
add_filter('the_time', 'modify_date_format');
function modify_date_format(){
$month_names = array(1=>'Januar','Februar','März','April','Mai','Juni','Juli','August','September','Oktober','November','Dezember');
return get_the_time('j').'. '.$month_names[get_the_time('n')].' '.get_the_time('Y');
}
```
But I'm not sure this is the correct way to do it. |
231,479 | <p>I've inherited a very poorly designed WordPress site that in part uses BuddyPress for a directory type section. Users are able to upload profile images and 'product' images to their profile.</p>
<p>As a result, we now have roughly 20GB of images on the site and desperately need to cut back on this. When users, stop paying a membership fee to the charity running the site, the users role is changed from one of several custom roles back to the WP 'Subscriber' role.</p>
<p>My hope is that there is a fairly simple and accurate way to find images associated with a user or users profile and then delete these images if the users is has the 'Subscriber' role.</p>
<p>At present I've not tried anything along these lines, and am hoping someone with more WP dev experience might be able to give me some tips / suggestions on how to approach this.</p>
<p>Thanks in advance.</p>
| [
{
"answer_id": 231499,
"author": "Conor",
"author_id": 47324,
"author_profile": "https://wordpress.stackexchange.com/users/47324",
"pm_score": 0,
"selected": false,
"text": "<p>You would need to do a <code>SELECT</code> statement against the <code>wp_posts</code> and <code>wp_users</code... | 2016/07/05 | [
"https://wordpress.stackexchange.com/questions/231479",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/55152/"
] | I've inherited a very poorly designed WordPress site that in part uses BuddyPress for a directory type section. Users are able to upload profile images and 'product' images to their profile.
As a result, we now have roughly 20GB of images on the site and desperately need to cut back on this. When users, stop paying a membership fee to the charity running the site, the users role is changed from one of several custom roles back to the WP 'Subscriber' role.
My hope is that there is a fairly simple and accurate way to find images associated with a user or users profile and then delete these images if the users is has the 'Subscriber' role.
At present I've not tried anything along these lines, and am hoping someone with more WP dev experience might be able to give me some tips / suggestions on how to approach this.
Thanks in advance. | Here's some code which pulls all subscriber IDs, then pulls all attachments from those subscribers and attempts to delete them. If it can't delete them it'll write to the error log letting you know.
```
$subscribers = get_users( array(
'role' => 'subscriber',
'fields'=> 'ID',
) );
if( ! empty( $subscribers ) ) {
$files = new WP_Query( array(
'post_type' => 'attachment',
'posts_per_page' => 200,
'author' => implode( ',', $subscribers ),
'fields' => 'ids',
) );
if( ! empty( $files ) ) {
foreach( $files->posts as $attachment_id ) {
$deleted = wp_delete_attachment( $attachment_id, true );
if( ! $deleted ) {
error_log( "Attachment {$deleted} Could Not Be Deleted!" );
}
}
}
}
```
Odds are you'll have more attachments than your server can handle loading at the same time so you'll probably hit the 200 limit a few times but some page refreshes ( or an actual offset / pagination script ) will do the trick. |
231,487 | <p>Okay, I've got the following issue. I'm trying to send a mail in HTML format. I made a class that returns an HTML string, and that works great.</p>
<p>When I pass that html-mail as $message in my function, works also. But it will not send as html, but plain text.</p>
<p>Now I've tried the following things:</p>
<p>1)
<code>$headers = array('Content-Type: text/html; charset=UTF-8');
wp_mail($to, $subject, $message, $headers);</code></p>
<p>2)
<code>$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";</code></p>
<p>3)
<code>$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=UTF-8' . "\r\n";</code></p>
<p>4)
<code>function wpse27856_set_content_type(){
return "text/html";
}
add_filter( 'wp_mail_content_type','wpse27856_set_content_type' );</code></p>
<p>What else could it be?</p>
| [
{
"answer_id": 231510,
"author": "Domain",
"author_id": 26523,
"author_profile": "https://wordpress.stackexchange.com/users/26523",
"pm_score": 1,
"selected": false,
"text": "<p>Try this one. </p>\n\n<pre><code> add_filter( 'wp_mail_content_type', 'wpdocs_set_html_mail_content_type' );... | 2016/07/05 | [
"https://wordpress.stackexchange.com/questions/231487",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/92815/"
] | Okay, I've got the following issue. I'm trying to send a mail in HTML format. I made a class that returns an HTML string, and that works great.
When I pass that html-mail as $message in my function, works also. But it will not send as html, but plain text.
Now I've tried the following things:
1)
`$headers = array('Content-Type: text/html; charset=UTF-8');
wp_mail($to, $subject, $message, $headers);`
2)
`$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";`
3)
`$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=UTF-8' . "\r\n";`
4)
`function wpse27856_set_content_type(){
return "text/html";
}
add_filter( 'wp_mail_content_type','wpse27856_set_content_type' );`
What else could it be? | Try this one.
```
add_filter( 'wp_mail_content_type', 'wpdocs_set_html_mail_content_type' );
$to = 'sendto@example.com';
$subject = 'The subject';
$body = 'The email body content';
$headers = array('Content-Type: text/html; charset=UTF-8');
wp_mail( $to, $subject, $body , $headers);
// Reset content-type to avoid conflicts -- https://core.trac.wordpress.org/ticket/23578
remove_filter( 'wp_mail_content_type', 'wpdocs_set_html_mail_content_type' );
function wpdocs_set_html_mail_content_type() {
return 'text/html';
}
``` |
231,511 | <p>I am struggling to get my settings page to save my options. I've got it showing up correctly and it hits the sanitize function</p>
<pre><code> register_setting(
'my_options', // Option group
'my_settings', // Option name
array($this, 'sanitize') // Sanitize
);
</code></pre>
<p>When I run the debugger on the sanitize function, $input is null:</p>
<pre><code>public function sanitize($input)
{
$new_input = array();
$new_input = $input;
//Sanitize the input actually
return $new_input;
}
</code></pre>
<p>The form itself is called like this:</p>
<pre><code><form id="my-admin-form" method="post" action="options.php">
<!-- Submission Notices -->
<div class="status-box notice notice-info" style="display: none;"></div>
<?php
settings_fields('my_options');
do_settings_sections('my_section');
submit_button();
?>
</form>
</code></pre>
| [
{
"answer_id": 259603,
"author": "dhuyvetter",
"author_id": 86095,
"author_profile": "https://wordpress.stackexchange.com/users/86095",
"pm_score": 2,
"selected": false,
"text": "<p>It turned out to be nonce related: the form didn't have a nonce. Solved this by adding <code>wp_nonce_fiel... | 2016/07/05 | [
"https://wordpress.stackexchange.com/questions/231511",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/86095/"
] | I am struggling to get my settings page to save my options. I've got it showing up correctly and it hits the sanitize function
```
register_setting(
'my_options', // Option group
'my_settings', // Option name
array($this, 'sanitize') // Sanitize
);
```
When I run the debugger on the sanitize function, $input is null:
```
public function sanitize($input)
{
$new_input = array();
$new_input = $input;
//Sanitize the input actually
return $new_input;
}
```
The form itself is called like this:
```
<form id="my-admin-form" method="post" action="options.php">
<!-- Submission Notices -->
<div class="status-box notice notice-info" style="display: none;"></div>
<?php
settings_fields('my_options');
do_settings_sections('my_section');
submit_button();
?>
</form>
``` | It turned out to be nonce related: the form didn't have a nonce. Solved this by adding `wp_nonce_field` to the form. |
231,541 | <p>I have a wordpress website where I post song lyrics.
I have written a wp query to list specific posts and order them by post views. However, I would like to order them by youtube views instead.</p>
<p>I have been able to get the youtube view counts for the posts (songs), the problem is ordering the posts with it. This is what the code looks like:-</p>
<pre><code><ul>
<?php $item=0; $loop = new WP_Query( array( 'post_type' => 'lyrics', 'date_query' => array( array( 'after' => '1 month ago' ) ), 'post_status'=> 'publish', 'meta_key' => 'post_view_count', 'orderby' => 'meta_value', 'posts_per_page' => 10 ) );
while ( $loop->have_posts() ) : $loop->the_post();
$song_name = get_the_title();
/*YOUTUBE QUERY HERE*/
$Yviews = 1234;
<li>
<?php echo esc_attr($song_name).' ('.$Yviews.' views)'; ?>
</li>
<?php endwhile; wp_reset_query(); ?>
</code></pre>
<p></p>
<p><strong>Things I Have Tried</strong></p>
<p>I created a custom field and tried updating the value (after the youtube code) with <code>update_post_meta(get_the_ID(), 'youtube_views', $Yviews);</code> and changed <code>'meta_key' => 'post_view_count'</code> to <code>'meta_key' => 'youtube_views'</code> but this either didn't work, or I wasn't doing it properly.</p>
<p>How do I achieve this?</p>
<p>PS: Ultimately, what I am trying to orderby is the sum of the post views and youtube views, but I can live without this.</p>
<p>Thanks in advance.</p>
<p>PS: I have omitted the youtube api query to make the code as simple as possible.</p>
| [
{
"answer_id": 250277,
"author": "Marco",
"author_id": 109575,
"author_profile": "https://wordpress.stackexchange.com/users/109575",
"pm_score": 4,
"selected": true,
"text": "<p>I've had the same problem, and in my case it was the Wordpress cronjob. I was calling the wp-cron.php as a roo... | 2016/07/05 | [
"https://wordpress.stackexchange.com/questions/231541",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/86102/"
] | I have a wordpress website where I post song lyrics.
I have written a wp query to list specific posts and order them by post views. However, I would like to order them by youtube views instead.
I have been able to get the youtube view counts for the posts (songs), the problem is ordering the posts with it. This is what the code looks like:-
```
<ul>
<?php $item=0; $loop = new WP_Query( array( 'post_type' => 'lyrics', 'date_query' => array( array( 'after' => '1 month ago' ) ), 'post_status'=> 'publish', 'meta_key' => 'post_view_count', 'orderby' => 'meta_value', 'posts_per_page' => 10 ) );
while ( $loop->have_posts() ) : $loop->the_post();
$song_name = get_the_title();
/*YOUTUBE QUERY HERE*/
$Yviews = 1234;
<li>
<?php echo esc_attr($song_name).' ('.$Yviews.' views)'; ?>
</li>
<?php endwhile; wp_reset_query(); ?>
```
**Things I Have Tried**
I created a custom field and tried updating the value (after the youtube code) with `update_post_meta(get_the_ID(), 'youtube_views', $Yviews);` and changed `'meta_key' => 'post_view_count'` to `'meta_key' => 'youtube_views'` but this either didn't work, or I wasn't doing it properly.
How do I achieve this?
PS: Ultimately, what I am trying to orderby is the sum of the post views and youtube views, but I can live without this.
Thanks in advance.
PS: I have omitted the youtube api query to make the code as simple as possible. | I've had the same problem, and in my case it was the Wordpress cronjob. I was calling the wp-cron.php as a root cron job, and this script also generates the monthly upload folder.
If you call wp-cron.php via cronjob you need to do this as the web server user (or i.e. in Plesk the site user and group psacln). The owner of the created monthly folder is always the user the wp-cron.php is called from. |
231,548 | <p>I just learned about child themes recently and was wondering if creating a child theme for every theme I create is necessary. I just find it weird how other themes work okay without child themes, and others do not. </p>
| [
{
"answer_id": 231549,
"author": "Yarwood",
"author_id": 32655,
"author_profile": "https://wordpress.stackexchange.com/users/32655",
"pm_score": 1,
"selected": false,
"text": "<p>For me the rule of thumb is am I extending/revising an existing theme? If so I'll want to be able to update t... | 2016/07/05 | [
"https://wordpress.stackexchange.com/questions/231548",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/68815/"
] | I just learned about child themes recently and was wondering if creating a child theme for every theme I create is necessary. I just find it weird how other themes work okay without child themes, and others do not. | Child themes are not the only way to extend a theme, not even the best.
Many themes offer hooks: actions and filters. You can use these to change the output per plugin.
Let’s say you have a theme named *Acme*, and its `index.php` contains the following code:
```
get_header();
do_action( 'acme.loop.before', 'index' );
?>
<div id="container">
<div id="content" role="main">
<?php
/*
* Run the loop to output the posts.
* If you want to overload this in a child theme then include a file
* called loop-index.php and that will be used instead.
*/
get_template_part( 'loop', 'index' );
?>
</div><!-- #content -->
</div><!-- #container -->
<?php
do_action( 'acme.loop.after', 'index' );
do_action( 'acme.sidebar.before', 'index' );
get_sidebar();
do_action( 'acme.sidebar.after', 'index' );
get_footer();
```
Now you can write a small plugin to add wrappers (maybe for a second background image) around these specific areas:
```
add_action( 'acme.loop.before', function( $template ) {
if ( 'index' === $template )
print "<div class='extra-background'>";
});
add_action( 'acme.loop.after', function( $template ) {
if ( 'index' === $template )
print "</div>";
});
```
Add other, separate plugins for other modifications.
This has four benefits:
1. You can turn off the extra behavior in your plugin administration if you don't want it anymore. In contrast to child themes, you do that for each plugin separately, you don't have to turn every customization like you do when you have only one child theme.
2. It is much faster than a child theme, because when WordPress is searching for a template and it cannot find it, it will search in both, child and parent themes. That cannot happen when there is no child theme.
3. It is easier to debug when something goes wrong. With child themes, it is hard to see where an error is coming from, child or parent theme. Or both, that's extra fun.
4. Safe updates. Sometimes, when you update a parent theme, the child theme doesn't work anymore, or worse: it works differently. It might even raise a fatal error, because you are using a function in the child theme that isn't available in the parent theme anymore.
**Summary:** Use hooks whenever you can, use a child theme only if the parent theme doesn't offer a good hook. Ask the theme author to add the missing hook. If you can offer a valid use case, I am sure s/he will implement it. |
231,557 | <p>I'm trying to create a custom widget to display contributing authors for the current category being viewed on a WordPress site. I have the following PHP code:</p>
<pre><code><?php
if (is_category()) {
?>
// Grab posts from the current category
<?php
$current_category = single_cat_title(“”, false);
$author_array = array();
$args = array(
‘numberposts’ => -1,
‘category_name’ => $current_category,
‘orderby’ => ‘author’,
‘order’ => ‘ASC’
);
// Get the posts in the array and create an array of the authors
$cat_posts = get_posts($args);
foreach ($cat_posts as $cat_post):
if (!in_array($cat_post->post_author, $author_array)) {
$author_array[] = $cat_post->post_author;
}
endforeach;
// Get the author information and build the output
foreach ($author_array as $author):
$auth = get_userdata($author)->display_name;
$auth_link = get_userdata($author)->user_login;
echo "<a href='/author/'" . $auth_link . "'>" . $auth . "</a>" . '<br \/>';
endforeach;
// Testing to make sure the current category is being pulled correctly
echo $current_category;
?>
<?php
}
?>
</code></pre>
<p>It's displaying authors from the site, but they're not changing from category to category - the same three are displayed in each section. The test statement at the end of the code block is working as expected - the displayed category in the widget matches the URI category.</p>
<p>Any thoughts on where I went wrong in creating the author array?</p>
| [
{
"answer_id": 231558,
"author": "Chinmoy Kumar Paul",
"author_id": 57436,
"author_profile": "https://wordpress.stackexchange.com/users/57436",
"pm_score": 0,
"selected": false,
"text": "<pre><code><?php\nif( is_category() ) {\n global $wp_query;\n $term_obj = $wp_query->get_quer... | 2016/07/06 | [
"https://wordpress.stackexchange.com/questions/231557",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/76765/"
] | I'm trying to create a custom widget to display contributing authors for the current category being viewed on a WordPress site. I have the following PHP code:
```
<?php
if (is_category()) {
?>
// Grab posts from the current category
<?php
$current_category = single_cat_title(“”, false);
$author_array = array();
$args = array(
‘numberposts’ => -1,
‘category_name’ => $current_category,
‘orderby’ => ‘author’,
‘order’ => ‘ASC’
);
// Get the posts in the array and create an array of the authors
$cat_posts = get_posts($args);
foreach ($cat_posts as $cat_post):
if (!in_array($cat_post->post_author, $author_array)) {
$author_array[] = $cat_post->post_author;
}
endforeach;
// Get the author information and build the output
foreach ($author_array as $author):
$auth = get_userdata($author)->display_name;
$auth_link = get_userdata($author)->user_login;
echo "<a href='/author/'" . $auth_link . "'>" . $auth . "</a>" . '<br \/>';
endforeach;
// Testing to make sure the current category is being pulled correctly
echo $current_category;
?>
<?php
}
?>
```
It's displaying authors from the site, but they're not changing from category to category - the same three are displayed in each section. The test statement at the end of the code block is working as expected - the displayed category in the widget matches the URI category.
Any thoughts on where I went wrong in creating the author array? | This can become a quite an expensive operation which can seriously damage page load time. At this stage, your code is quite expensive. Lets look a better way to tackle this issue.
What we need to do is to minimize the time spend in db, and to do this, we will only get the info we need, that is the `post_author` property of the post object. As we now, there is no native way to just get the `post_author` property from the db with `WP_Query`, we only have the possibility to get the complete object or just the post `ID`'s. To alter the behavior (*and the generated SQL*), we will make use of the `posts_fields` filter in which we can command the SQL query to just return the `post_author` field, which will save us a ton in time spend in the db as we only get what we need.
Secondly, to improve performance, we will tell `WP_Query` to not cache any post data or post term and post meta data. As we will not be needing any meta data or post term data, we can simply just ask `WP_Query` to not query these and cache them for later use, this also saves us a lot of extra time spend in db, time to add this data in cache, and we will also save on db queries.
Lets put this all in code: (***NOTE:*** All code is untested and require PHP 5.4+)
`posts_fields` FILTER
---------------------
```
add_filter( 'posts_fields', function ( $fields, \WP_Query $q ) use ( &$wpdb )
{
remove_filter( current_filter(), __FUNCTION__ );
// Only target a query where the new wpse_post_author parameter is set to true
if ( true === $q->get( 'wpse_post_author' ) ) {
// Only get the post_author column
$fields = "
$wpdb->posts.post_author
";
}
return $fields;
}, 10, 2);
```
You'll notice that we have a custom trigger called `wpse_post_author`. Whenever we pass a value of `true` to that custom trigger, our filter will fire.
`get_posts()` QUERY
-------------------
By default, `get_posts()` passes `suppress_filters=true` to `WP_Query` as to avoid filters acting on `get_posts()`, so in order to get our filter to work, we need to set that back to true.
Just another note, to get the current category reliably, use `$GLOBALS['wp_the_query']->get_queried_object()` and `$GLOBALS['wp_the_query']->get_queried_object_id()` for the category ID
```
if ( is_category() ) {
$current_category = get_term( $GLOBALS['wp_the_query']->get_queried_object() );
$args = [
'wpse_post_author' => true, // To trigger our filter
'posts_per_page' => -1,
'orderby' => 'author',
'order' => 'ASC',
'suppress_filters' => false, // Allow filters to alter query
'cache_results' => false, // Do not cache posts
'update_post_meta_cache' => false, // Do not cache custom field data
'update_post_term_cache' => false, // Do not cache post terms
'tax_query' => [
[
'taxonomy' => $current_category->taxonomy,
'terms' => $current_category->term_id,
'include_children' => true
]
]
];
$posts_array = get_posts( $args );
if ( $posts_array ) {
// Get all the post authors from the posts
$post_author_ids = wp_list_pluck( $posts_array, 'post_author' );
// Get a unique array of ids
$post_author_ids = array_unique( $post_author_ids );
// NOW WE CAN DO SOMETHING WITH THE ID'S, SEE BELOW TO INCLUDE HERE
}
}
```
As you can see, I used a `tax_query`, this is personal preference due to the flexibility of it, and also, you can reuse the code on any term page with no need to modify it. In this case, you only need to change the `is_category()` condition.
In my `tax_query` I have set `include_children` to `true`, which means that `WP_Query` will get posts from the current category and the posts that belongs to the child categories of the category being viewed. This is default behavior for all hierarchical term pages. If you really just need authors from the category being viewed, set `include_children` to `false`
QUERYING THE AUTHORS
--------------------
If you do a `var_dump( $post_author_ids )`, you will see that you have an array of post author ids. Now, instead of looping through each and every ID, you can just pass this array of id's to [`WP_User_Query`](https://codex.wordpress.org/Class_Reference/WP_User_Query), and then loop through the results from that query.
```
$user_args = [
'include' => $post_author_ids
];
$user_query = new \WP_User_Query( $user_args );
var_dump( $user_query->results ); // For debugging purposes
if ( $user_query->results ) {
foreach ( $user_query->results as $user ) {
echo $user->display_name;
}
}
```
We can take this even further and save everything in a transient, which will have us ending up only 2 db queries in =/- 0.002s.
THE TRANSIENT
-------------
To set a unique transient name, we will use the term object to create a unique name
```
if ( is_category() ) {
$current_category = get_term( $GLOBALS['wp_the_query']->get_queried_object() );
$transient_name = 'wpse231557_' . md5( json_encode( $current_category ) );
// Check if transient is set
if ( false === ( $user_query = get_transient( $transient_name ) ) ) {
// Our code above
// Set the transient for 3 days, adjust as needed
set_transient( $transient_name, $user_query, 72 * HOUR_IN_SECONDS );
}
// Run your foreach loop to display users
}
```
**FLUSHING THE TRANSIENT**
We can flush the transient whenever a new post is publish or when a post is edited, deleted, undeleted, etc. For this we can use the `transition_post_status` hook. You can also adjust it to fire only when certain things happens, like only when a new post is published. Anyways, here is the hook which will fire when anything happens to the post
```
add_action( 'transition_post_status', function () use ( &$wpdb )
{
$wpdb->query( "DELETE FROM $wpdb->options WHERE `option_name` LIKE ('_transient%_wpse231557_%')" );
$wpdb->query( "DELETE FROM $wpdb->options WHERE `option_name` LIKE ('_transient_timeout%_wpse231557_%')" );
});
```
ALL TOGETHER NOW!!!
===================
In a functions type file
```
add_filter( 'posts_fields', function ( $fields, \WP_Query $q ) use ( &$wpdb )
{
remove_filter( current_filter(), __FUNCTION__ );
// Only target a query where the new wpse_post_author parameter is set to true
if ( true === $q->get( 'wpse_post_author' ) ) {
// Only get the post_author column
$fields = "
$wpdb->posts.post_author
";
}
return $fields;
}, 10, 2);
add_action( 'transition_post_status', function () use ( &$wpdb )
{
$wpdb->query( "DELETE FROM $wpdb->options WHERE `option_name` LIKE ('_transient%_wpse231557_%')" );
$wpdb->query( "DELETE FROM $wpdb->options WHERE `option_name` LIKE ('_transient_timeout%_wpse231557_%')" );
});
```
In your widget
```
if ( is_category() ) {
$current_category = get_term( $GLOBALS['wp_the_query']->get_queried_object() );
$transient_name = 'wpse231557_' . md5( json_encode( $current_category ) );
// Check if transient is set
if ( false === ( $user_query = get_transient( $transient_name ) ) ) {
$args = [
'wpse_post_author' => true, // To trigger our filter
'posts_per_page' => -1,
'orderby' => 'author',
'order' => 'ASC',
'suppress_filters' => false, // Allow filters to alter query
'cache_results' => false, // Do not cache posts
'update_post_meta_cache' => false, // Do not cache custom field data
'update_post_term_cache' => false, // Do not cache post terms
'tax_query' => [
[
'taxonomy' => $current_category->taxonomy,
'terms' => $current_category->term_id,
'include_children' => true
]
]
];
$posts_array = get_posts( $args );
$user_query = false;
if ( $posts_array ) {
// Get all the post authors from the posts
$post_author_ids = wp_list_pluck( $posts_array, 'post_author' );
// Get a unique array of ids
$post_author_ids = array_unique( $post_author_ids );
$user_args = [
'include' => $post_author_ids
];
$user_query = new \WP_User_Query( $user_args );
}
// Set the transient for 3 days, adjust as needed
set_transient( $transient_name, $user_query, 72 * HOUR_IN_SECONDS );
}
if ( false !== $user_query
&& $user_query->results
) {
foreach ( $user_query->results as $user ) {
echo $user->display_name;
}
}
}
```
EDIT
====
All code is now tested and works as expected |
231,589 | <p><br />
I've been trying to redirect a page but with no success. <br />
My purpose is to redirect <code>example.com/me/name</code> to <code>example.com/me?n=name</code><br />
I've tried with <code>add_rewrite_rule</code>, write conditions in .htaccess, but nothing worked.
Any clue?
<br/>
Edit:<br/>
The full htaccess code is this:<br/></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
<IfModule mod_deflate.c>
# Compress HTML, CSS, JavaScript, Text, XML and fonts
AddOutputFilterByType DEFLATE application/javascript
AddOutputFilterByType DEFLATE application/rss+xml
AddOutputFilterByType DEFLATE application/vnd.ms-fontobject
AddOutputFilterByType DEFLATE application/x-font
AddOutputFilterByType DEFLATE application/x-font-opentype
AddOutputFilterByType DEFLATE application/x-font-otf
AddOutputFilterByType DEFLATE application/x-font-truetype
AddOutputFilterByType DEFLATE application/x-font-ttf
AddOutputFilterByType DEFLATE application/x-javascript
AddOutputFilterByType DEFLATE application/xhtml+xml
AddOutputFilterByType DEFLATE application/xml
AddOutputFilterByType DEFLATE font/opentype
AddOutputFilterByType DEFLATE font/otf
AddOutputFilterByType DEFLATE font/ttf
AddOutputFilterByType DEFLATE image/svg+xml
AddOutputFilterByType DEFLATE image/x-icon
AddOutputFilterByType DEFLATE text/css
AddOutputFilterByType DEFLATE text/html
AddOutputFilterByType DEFLATE text/javascript
AddOutputFilterByType DEFLATE text/plain
AddOutputFilterByType DEFLATE text/xml
# Remove browser bugs (only needed for really old browsers)
BrowserMatch ^Mozilla/4 gzip-only-text/html
BrowserMatch ^Mozilla/4\.0[678] no-gzip
BrowserMatch \bMSIE !no-gzip !gzip-only-text/html
Header append Vary User-Agent
</IfModule>
## EXPIRES CACHING ##
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpg "access plus 1 year"
ExpiresByType image/jpeg "access plus 1 year"
ExpiresByType image/gif "access plus 1 year"
ExpiresByType image/png "access plus 1 year"
ExpiresByType text/css "access plus 1 month"
ExpiresByType application/pdf "access plus 1 month"
ExpiresByType text/x-javascript "access plus 1 month"
ExpiresByType application/x-shockwave-flash "access plus 1 month"
ExpiresByType image/x-icon "access plus 1 year"
ExpiresDefault "access plus 2 days"
</IfModule>
## EXPIRES CACHING ##
</code></pre>
<p>Edit 2:<br/>
The code for redirect I was trying to use is this:<br/></p>
<pre><code>#RewriteRule (http://example.com/me/*) http://example.com/me?n=$1
</code></pre>
<p><br/><br/>
Edit 3:<br/>
The "name" in the code does not stay the same, it is variable depending on person. It can be Ash, George, Mike, whatever.</p>
| [
{
"answer_id": 231581,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 1,
"selected": false,
"text": "<p>This is an interesting question, though a bit too broad for a Q&A model. Here is what I would do:</p>\n\n<ol... | 2016/07/06 | [
"https://wordpress.stackexchange.com/questions/231589",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/97913/"
] | I've been trying to redirect a page but with no success.
My purpose is to redirect `example.com/me/name` to `example.com/me?n=name`
I've tried with `add_rewrite_rule`, write conditions in .htaccess, but nothing worked.
Any clue?
Edit:
The full htaccess code is this:
```
# 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
<IfModule mod_deflate.c>
# Compress HTML, CSS, JavaScript, Text, XML and fonts
AddOutputFilterByType DEFLATE application/javascript
AddOutputFilterByType DEFLATE application/rss+xml
AddOutputFilterByType DEFLATE application/vnd.ms-fontobject
AddOutputFilterByType DEFLATE application/x-font
AddOutputFilterByType DEFLATE application/x-font-opentype
AddOutputFilterByType DEFLATE application/x-font-otf
AddOutputFilterByType DEFLATE application/x-font-truetype
AddOutputFilterByType DEFLATE application/x-font-ttf
AddOutputFilterByType DEFLATE application/x-javascript
AddOutputFilterByType DEFLATE application/xhtml+xml
AddOutputFilterByType DEFLATE application/xml
AddOutputFilterByType DEFLATE font/opentype
AddOutputFilterByType DEFLATE font/otf
AddOutputFilterByType DEFLATE font/ttf
AddOutputFilterByType DEFLATE image/svg+xml
AddOutputFilterByType DEFLATE image/x-icon
AddOutputFilterByType DEFLATE text/css
AddOutputFilterByType DEFLATE text/html
AddOutputFilterByType DEFLATE text/javascript
AddOutputFilterByType DEFLATE text/plain
AddOutputFilterByType DEFLATE text/xml
# Remove browser bugs (only needed for really old browsers)
BrowserMatch ^Mozilla/4 gzip-only-text/html
BrowserMatch ^Mozilla/4\.0[678] no-gzip
BrowserMatch \bMSIE !no-gzip !gzip-only-text/html
Header append Vary User-Agent
</IfModule>
## EXPIRES CACHING ##
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpg "access plus 1 year"
ExpiresByType image/jpeg "access plus 1 year"
ExpiresByType image/gif "access plus 1 year"
ExpiresByType image/png "access plus 1 year"
ExpiresByType text/css "access plus 1 month"
ExpiresByType application/pdf "access plus 1 month"
ExpiresByType text/x-javascript "access plus 1 month"
ExpiresByType application/x-shockwave-flash "access plus 1 month"
ExpiresByType image/x-icon "access plus 1 year"
ExpiresDefault "access plus 2 days"
</IfModule>
## EXPIRES CACHING ##
```
Edit 2:
The code for redirect I was trying to use is this:
```
#RewriteRule (http://example.com/me/*) http://example.com/me?n=$1
```
Edit 3:
The "name" in the code does not stay the same, it is variable depending on person. It can be Ash, George, Mike, whatever. | I evaluated the different options and went with a plugin "Page Builder". While the technical aspects are not great (e.g. data persisting: all content gets serialized) is was the only option to give me enough flexibility and enough comfort so that the customer could make changes to the structure of each page.
Migrating from dev to stage to live was also a pain due to the serializing and only possible with yet another plugin (duplicator).
Thanks everyone for the input! |
231,597 | <p>Following <a href="http://keithclark.co.uk/articles/loading-css-without-blocking-render/" rel="nofollow">Keith Clarks advice</a>, i'd like to load my fonts asynchronously. I try to achieve that by adding: </p>
<pre><code>wp_enqueue_style( 'font-awesome', URI . '/fonts/font-awesome/css/font-awesome.min.css' );
wp_style_add_data( 'font-awesome', 'onload', 'if(media!=\'all\')media=\'all\'');
</code></pre>
<p>to my <code>scripts.php</code> file, but apparently this argument is not well taken by that function, because there is no onload attribute. How properly can I do that in WordPress?</p>
| [
{
"answer_id": 231603,
"author": "bravokeyl",
"author_id": 43098,
"author_profile": "https://wordpress.stackexchange.com/users/43098",
"pm_score": 3,
"selected": false,
"text": "<p>We can use <a href=\"https://developer.wordpress.org/reference/hooks/style_loader_tag/\" rel=\"noreferrer\"... | 2016/07/06 | [
"https://wordpress.stackexchange.com/questions/231597",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/97916/"
] | Following [Keith Clarks advice](http://keithclark.co.uk/articles/loading-css-without-blocking-render/), i'd like to load my fonts asynchronously. I try to achieve that by adding:
```
wp_enqueue_style( 'font-awesome', URI . '/fonts/font-awesome/css/font-awesome.min.css' );
wp_style_add_data( 'font-awesome', 'onload', 'if(media!=\'all\')media=\'all\'');
```
to my `scripts.php` file, but apparently this argument is not well taken by that function, because there is no onload attribute. How properly can I do that in WordPress? | We can use [`style_loader_tag`](https://developer.wordpress.org/reference/hooks/style_loader_tag/) filter to filter the link that is being output.
Here is the filter:
```
$tag = apply_filters( 'style_loader_tag', "<link rel='$rel' id='$handle-css' $title href='$href' type='text/css' media='$media' />\n", $handle, $href, $media);
```
Here the link $handle for which you want to add attribute is **`font-awesome`** so if the handle, so you can replace `font-awesome-css` with extra info.
```
add_filter('style_loader_tag', 'wpse_231597_style_loader_tag');
function wpse_231597_style_loader_tag($tag){
$tag = preg_replace("/id='font-awesome-css'/", "id='font-awesome-css' online=\"if(media!='all')media='all'\"", $tag);
return $tag;
}
``` |
231,623 | <p>A site I'm currently working on has a page structure like this</p>
<pre><code>About Us
|
|_People
| |
| _ Person 1
| _ Person 2
| _ Person 3
|... etc ...
</code></pre>
<p>Every 'Person' page is a separate page, but they all have the same structure using a few ACF fields to display a person's bio, photo etc.</p>
<p>I know how to create a custom page template for one specific page, i.e. page-<em>slug</em>.php, but I want to use one page template for all of those subpages.</p>
<p>What would be the easiest way to accomplish this?</p>
| [
{
"answer_id": 231625,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 2,
"selected": false,
"text": "<p>The easiest way would be to create a <a href=\"https://codex.wordpress.org/Post_Types#Custom_Post_Types\" rel=\"... | 2016/07/06 | [
"https://wordpress.stackexchange.com/questions/231623",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/37750/"
] | A site I'm currently working on has a page structure like this
```
About Us
|
|_People
| |
| _ Person 1
| _ Person 2
| _ Person 3
|... etc ...
```
Every 'Person' page is a separate page, but they all have the same structure using a few ACF fields to display a person's bio, photo etc.
I know how to create a custom page template for one specific page, i.e. page-*slug*.php, but I want to use one page template for all of those subpages.
What would be the easiest way to accomplish this? | You can always make use of the `page_template` filter to tell WordPress to use a specific page template for all child pages of a certain parent. It is as easy as creating a special page template, lets call it `page-wpse-person.php`.
Now it is as easy as including that template whenever a child page of `people` is being viewed. For the sake of example, lets say the page ID of `people` is `10`
```
add_filter( 'page_template', function ( $template ) use ( &$post )
{
// Check if we have page which is a child of people, ID 10
if ( 10 !== $post->post_parent )
return $template;
// This is a person page, child of people, try to locate our custom page
$locate_template = locate_template( 'page-wpse-person.php' );
// Check if our template was found, if not, bail
if ( !$locate_template )
return $template;
return $locate_template;
});
``` |
231,653 | <p>I'm recoding my website with custom post types to be better organized, have a better search experience and being able to hide some pages from other contributors, but I have a little problem.</p>
<p>I've set up a post type named <em>Files</em> which contains some files that my contributors should not see. Basically the legal pages, the contact page and so on.</p>
<p>As I had all the pages in the default <em>Pages</em> post type I was able to select a template for each page in the page attributes. Now in my new custom page type, I can only select the order of the page and nothing else. So I have a template for the legal pages and another one for the contact page, which includes all the PHP code. How can I select these templates in my new custom post type?</p>
<hr>
<p><strong>EDIT</strong></p>
<p>Okay, I've understood, that it's only possible to set a template by setting up a PHP file named <code>single-*(post_type_name)*</code>. But as I said, I've two different templates, and more will come very soon, so how can I set these to one or maybe two posts inside that post_type. There must be a possibility, isn't it? The makers of WordPress will unlikely have us create a new post_type for a single file...</p>
| [
{
"answer_id": 231812,
"author": "Faye",
"author_id": 76600,
"author_profile": "https://wordpress.stackexchange.com/users/76600",
"pm_score": 2,
"selected": true,
"text": "<p>From what I understand, you've got THREE options (updated).</p>\n<p><strong>Option 1: Dynamic Solution</strong> C... | 2016/07/06 | [
"https://wordpress.stackexchange.com/questions/231653",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/93282/"
] | I'm recoding my website with custom post types to be better organized, have a better search experience and being able to hide some pages from other contributors, but I have a little problem.
I've set up a post type named *Files* which contains some files that my contributors should not see. Basically the legal pages, the contact page and so on.
As I had all the pages in the default *Pages* post type I was able to select a template for each page in the page attributes. Now in my new custom page type, I can only select the order of the page and nothing else. So I have a template for the legal pages and another one for the contact page, which includes all the PHP code. How can I select these templates in my new custom post type?
---
**EDIT**
Okay, I've understood, that it's only possible to set a template by setting up a PHP file named `single-*(post_type_name)*`. But as I said, I've two different templates, and more will come very soon, so how can I set these to one or maybe two posts inside that post\_type. There must be a possibility, isn't it? The makers of WordPress will unlikely have us create a new post\_type for a single file... | From what I understand, you've got THREE options (updated).
**Option 1: Dynamic Solution** Create categories for your custom post type - each category is going to have its own template.
You then create a single template that splits off based on category. Meaning you use the general header and footer in your single-postypename.php and anything else that you want to apply to both templates, but in the meat of it, you then create some php logic for "if category x, use content y template (or partial, I like partials)" and "if category z, use content z template (or partial)". I assume that if you're working in templates you're okay with the code for that, but if not just comment and I can put together an example.
**Option 2: Static Solution** Each post inside your custom post type gets its own template.
You need the single-posttypename.php as your default, but then you can create single-postypename-postslug.php and presto, you have a custom template for that specific post that you can mess around in. As long as your slugs match, it'll just know what to do.
Example:
single-file.php (as your default template)
single-file-legaldocument2.php (as a custom template for yourdomain.ca/file/legaldocument2 )
**Option 3: Identify a template**
WordPress now offers the ability to [assign a template](https://make.wordpress.org/core/2016/11/03/post-type-templates-in-4-7/) based on post type. I don't think this can get as granular for categories of a post type or a specific post, for that you would still need solution #2.
Example:
```
<?php
/*
Template Name: Full-width layout
Template Post Type: post, page, product
*/
``` |
231,685 | <p>I was wandering... All the translation functions (<code>__(), _e(), _x()</code> and so on) use the current/active language. Is there a way to get a translation from another language than the current one? For example, I'm on a French page and I want and english translation: how to?</p>
| [
{
"answer_id": 231888,
"author": "J.D.",
"author_id": 27757,
"author_profile": "https://wordpress.stackexchange.com/users/27757",
"pm_score": 2,
"selected": false,
"text": "<p>To find the answer to this question, you just need to look at how WordPress retrieves the translations. Ultimate... | 2016/07/07 | [
"https://wordpress.stackexchange.com/questions/231685",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/10381/"
] | I was wandering... All the translation functions (`__(), _e(), _x()` and so on) use the current/active language. Is there a way to get a translation from another language than the current one? For example, I'm on a French page and I want and english translation: how to? | So thanks to J.D., I finally ended up with this code:
```
function __2($string, $textdomain, $locale){
global $l10n;
if(isset($l10n[$textdomain])) $backup = $l10n[$textdomain];
load_textdomain($textdomain, get_template_directory() . '/languages/'. $locale . '.mo');
$translation = __($string,$textdomain);
if(isset($bkup)) $l10n[$textdomain] = $backup;
return $translation;
}
function _e2($string, $textdomain, $locale){
echo __2($string, $textdomain, $locale);
}
```
Now, I know it shouldn't be, as per this famous article:
<http://ottopress.com/2012/internationalization-youre-probably-doing-it-wrong/>
But, I don't know, it works... And bonus: say you want to use it in admin, because the admin language is x, but you want to get/save data in lang y, and you're using polylang. So i.e. your admin is english, but you're on the spanish translation of a post, and you need to get spanish data from your theme locales:
```
global $polylang;
$p_locale = $polylang->curlang->locale; // will be es_ES
_e2('your string', 'yourtextdomain', $p_locale)
``` |
231,693 | <p>I am developing a theme with Underscores for WordPress. </p>
<p>When the user adds an image using the TinyMCE editor the following code is inserted: </p>
<pre><code><img class="wp-image-45 size-full aligncenter" src="http://example.com/wp-content/uploads/2016/06/process.png" alt="process" width="849" height="91" />
</code></pre>
<p>When I look at the final page generated by Wordpress, the HTML appears in the DOM</p>
<pre><code><img class="wp-image-45 size-full aligncenter" src="http://example.com/wp-content/uploads/2016/06/process.png" alt="process" width="849" height="91" srcset="http://example.com/wp-content/uploads/2016/06/process.png 849w, http://example.com/wp-content/uploads/2016/06/process-300x32.png 300w, http://example.com/wp-content/uploads/2016/06/process-768x82.png 768w" sizes="(max-width: 849px) 100vw, 849px">
</code></pre>
<p>I have created a function to generate a thumbnail with a width of 300px: </p>
<pre><code>add_action( 'after_setup_theme', 'images_theme_setup' );
function images_theme_setup() {
add_image_size( 'preload-thumb', 300 ); // 300 pixels wide (and unlimited height)
}
</code></pre>
<p>Now I want to use Pil (<a href="https://github.com/gilbitron/Pil" rel="nofollow">https://github.com/gilbitron/Pil</a>) compatible markup to serve images so I can serve the <code>preload-thumb</code> and then serve the larger image</p>
<p>I need to change to the markup to match this below </p>
<pre><code><figure class="pil">
<img src="img/my-image.jpg" data-pil-thumb-url="img/thumb-my-image.jpg" data-full-width="5616" data-full-height="3744" alt="">
</figure>
</code></pre>
| [
{
"answer_id": 231695,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 2,
"selected": false,
"text": "<p>There's a filter called <a href=\"https://developer.wordpress.org/reference/hooks/image_send_to_editor/\" rel=\"... | 2016/07/07 | [
"https://wordpress.stackexchange.com/questions/231693",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/82713/"
] | I am developing a theme with Underscores for WordPress.
When the user adds an image using the TinyMCE editor the following code is inserted:
```
<img class="wp-image-45 size-full aligncenter" src="http://example.com/wp-content/uploads/2016/06/process.png" alt="process" width="849" height="91" />
```
When I look at the final page generated by Wordpress, the HTML appears in the DOM
```
<img class="wp-image-45 size-full aligncenter" src="http://example.com/wp-content/uploads/2016/06/process.png" alt="process" width="849" height="91" srcset="http://example.com/wp-content/uploads/2016/06/process.png 849w, http://example.com/wp-content/uploads/2016/06/process-300x32.png 300w, http://example.com/wp-content/uploads/2016/06/process-768x82.png 768w" sizes="(max-width: 849px) 100vw, 849px">
```
I have created a function to generate a thumbnail with a width of 300px:
```
add_action( 'after_setup_theme', 'images_theme_setup' );
function images_theme_setup() {
add_image_size( 'preload-thumb', 300 ); // 300 pixels wide (and unlimited height)
}
```
Now I want to use Pil (<https://github.com/gilbitron/Pil>) compatible markup to serve images so I can serve the `preload-thumb` and then serve the larger image
I need to change to the markup to match this below
```
<figure class="pil">
<img src="img/my-image.jpg" data-pil-thumb-url="img/thumb-my-image.jpg" data-full-width="5616" data-full-height="3744" alt="">
</figure>
``` | As far as I know you could hook into the filter [`image_send_to_editor`](https://developer.wordpress.org/reference/hooks/image_send_to_editor/) like this:
```
function html5_insert_image($html, $id, $caption, $title, $align, $url) {
$url = wp_get_attachment_url($id);
$html5 = "<figure id='post-$id media-$id' class='align-$align'>";
$html5 .= "<img src='$url' alt='$title' />";
$html5 .= "</figure>";
return $html5;
}
add_filter( 'image_send_to_editor', 'html5_insert_image', 10, 9 );
```
For additional tags like `data-pil-thumb-url` and `data-full-width` and `data-full-height`you could add the appropriate code inside that function and add them to the `$html5` string.
See also [this page](https://css-tricks.com/snippets/wordpress/insert-images-within-figure-element-from-media-uploader/) for an example featuring a caption `<figcaption>` at css-tricks or check [this](http://synapticism.com/dev/experimenting-with-html5-image-markup-and-shortcodes-in-wordpress/) more detailed 'walk through'. |
231,711 | <p>I have six regular categories, not custom (each category having between 5 and 10 posts) and I am trying to display one random post from each category on the page. </p>
<p>The problem with the output is getting the random posts is fine, but some posts are taken from the same category which I do not want. Here is the code I am using it:</p>
<pre><code>$args_ = array(
'posts_per_page' => 6,
'orderby' => 'rand',
'exclude' => $postid , // the current post ID
'category' => $cat_id_array // here is the array of categories
);
$myposts = get_posts( $args_ );
//var_dump($myposts); // I have duplicate category here
foreach ( $myposts as $post ) : setup_postdata( $post ); ?>
<div class="col-md-4">
<?php the_post_thumbnail( 'medium', array( 'class' => 'img-responsive' ) );?><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
</div>
<?php endforeach;
wp_reset_postdata();
</code></pre>
<p>Any help would be appreciated. </p>
| [
{
"answer_id": 231715,
"author": "cadobe",
"author_id": 58295,
"author_profile": "https://wordpress.stackexchange.com/users/58295",
"pm_score": 1,
"selected": false,
"text": "<p>I just fix it using bueltge sugestion such us:</p>\n\n<pre><code>foreach ( $cat_id_array as $cat ) :\n\n $a... | 2016/07/07 | [
"https://wordpress.stackexchange.com/questions/231711",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/58295/"
] | I have six regular categories, not custom (each category having between 5 and 10 posts) and I am trying to display one random post from each category on the page.
The problem with the output is getting the random posts is fine, but some posts are taken from the same category which I do not want. Here is the code I am using it:
```
$args_ = array(
'posts_per_page' => 6,
'orderby' => 'rand',
'exclude' => $postid , // the current post ID
'category' => $cat_id_array // here is the array of categories
);
$myposts = get_posts( $args_ );
//var_dump($myposts); // I have duplicate category here
foreach ( $myposts as $post ) : setup_postdata( $post ); ?>
<div class="col-md-4">
<?php the_post_thumbnail( 'medium', array( 'class' => 'img-responsive' ) );?><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
</div>
<?php endforeach;
wp_reset_postdata();
```
Any help would be appreciated. | Random ordering is quite expensive operations in SQL and can become a headache on very big sites. Getting a random post from a category for 6 categories will mean you might need to run 6 separate queries, each ordered randomly. This can really break the bank and leave you bankrupt.
From your answer and looking at the fact that you said you are running 30 queries, this is quite evident. Also, what really makes this expensive is that post thumbnails aren't cached for custom queries, so you are making a db call everytime you query a post thumbnail.
Lets trey a different approach, and if we are clever, we can reduce your queries to almost nothing. This is what we will do
* Query all the posts from the db. It is here where we need to be clever as this is an extremely expensive operation. The only thing that we really need from the posts is their ID's, so we will only query the post ID's, and that will drastically reduce db queries and time spend to run the query
* Once we have all the post ID's, we will sort them according to categories
* We will then pick 6 random ids from the sorted array, one per category, and this will be passed to our "main" query which will output the posts.
The first two operations will only require 2 or three queries, this you can verify with a plugin like *Query Monitor*
Lets look at some code: (*NOTE: All code is untested and requires PHP 5.4+*)
THE QUERY
---------
```
// Lets get all the post ids
$args = [
'posts_per_page' => -1,
'fields' => 'ids' // Only get the post ID's
];
$ids_array = get_posts( $args );
// Make sure we have a valid array of ids
if ( $ids_array ) {
// Lets update the post term cache
update_object_term_cache( $ids_array, 'post' );
// Loop through the post ids and create an array with post ids and terms
$id_and_term_array = [];
foreach ( $ids_array as $id ) {
// Get all the post categories
$terms = get_the_terms( $id, 'category' );
// Make sure we have a valid array of terms
if ( $terms
&& !is_wp_error( $terms )
) {
// Loop through the terms and create our array with post ids and term
foreach ( $terms as $term )
$id_and_term_array[$term->term_id][] = $id;
}
}
// TO BE CONTINUED......
}
```
Great, `$id_and_term_array` should now contain an array with arrays where the keys are term ids and the values are an array of post ids. We have created all of this without breaking the bank. If you check query monitor, you will see all of this required only 2 db calls in about no time. We have slightly abused memory, but we will later look at something to avoid eating up memory.
SELECTING RANDOM ID'S
---------------------
What we will do next is to loop through `$id_and_term_array` and pick a random post id from each term id array. We also need to exclude the current post id and need to avoid duplicate post id's which we will certainly have if posts belongs to more than one term.
So lets continue where we last placed *TO BE CONTINUED....*
```
// Make sure we have a valid array
if ( $id_and_term_array ) {
// Get the current post ID
$current_post_id = get_the_ID();
// If this is a single post page, we can do
// $current_post_id = $GLOBALS['wp_the_query']->get_queried_object_id();
// Lets loop through $id_and_term_array
$unique_rand_array = [];
foreach ( $id_and_term_array as $value ) {
// Shuffle the $value array to randomize it
shuffle ( $value );
// Loop through $value and get the first post id
foreach ( $value as $v ) {
// Skip the post ID if it mathes the current post or if it is a duplicate
if ( $v == $current_post_id )
continue;
if ( in_array( $v, $unique_rand_array ) )
continue;
// We have a unique id, lets store it and bail
$unique_rand_array[] = $v;
break;
}
}
}
```
We now have an array with x amount of unique post id's which is stored in `$unique_rand_array`. We can now pass that array of id's to our final query
FINAL QUERY
-----------
```
// First see if we have post ids in array
if ( $unique_rand_array ) {
// Lets run our query
$final_args = [
'posts_per_page' => 6,
'post__in' => shuffle( $unique_rand_array ), // Randomize posts
'orderby' => 'post__in' // Keep post order the same as the order of post ids
];
$q = new WP_Query( $final_args );
// Lets cache our post thumbnails
update_post_thumbnail_cache( $q );
while ( $q->have_posts() ) :
$q->the_post();
?>
<div class="col-md-4">
<?php the_post_thumbnail( 'medium', array( 'class' => 'img-responsive' ) );?>
<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
</div>
<?php
endwhile;
wp_reset_postdata();
}
```
TRANSIENTS
----------
One last thing we can do is to savethe results for our first query in transient because we do not want to run that query on every page load. This will reduce memory abuse and avoid. We will also delete our transient when we publish a new post
ALL TOGETHER NOW
================
Let put everything together.
```
// Check if we have a transient
if ( false === ( $id_and_term_array = get_transient( 'random_term_post_ids' ) ) ) {
// Lets get all the post ids
$args = [
'posts_per_page' => -1,
'fields' => 'ids' // Only get the post ID's
];
$ids_array = get_posts( $args );
// Define the array which will hold the term and post_ids
$id_and_term_array = [];
// Make sure we have a valid array of ids
if ( $ids_array ) {
// Lets update the post term cache
update_object_term_cache( $ids_array, 'post' );
// Loop through the post ids and create an array with post ids and terms
foreach ( $ids_array as $id ) {
// Get all the post categories
$terms = get_the_terms( $id, 'category' );
// Make sure we have a valid array of terms
if ( $terms
&& !is_wp_error( $terms )
) {
// Loop through the terms and create our array with post ids and term
foreach ( $terms as $term )
$id_and_term_array[$term->term_id][] = $id;
}
}
}
// Set our transient for 30 days
set_transient( 'random_term_post_ids', $id_and_term_array, 30 * DAYS_IN_SECONDS );
}
// Make sure we have a valid array
if ( $id_and_term_array ) {
// Get the current post ID
$current_post_id = get_the_ID();
// If this is a single post page, we can do
// $current_post_id = $GLOBALS['wp_the_query']->get_queried_object_id();
// Lets loop through $id_and_term_array
$unique_rand_array = [];
foreach ( $id_and_term_array as $value ) {
// Shuffle the $value array to randomize it
shuffle ( $value );
// Loop through $value and get the first post id
foreach ( $value as $v ) {
// Skip the post ID if it mathes the current post or if it is a duplicate
if ( $v == $current_post_id )
continue;
if ( in_array( $v, $unique_rand_array ) )
continue;
// We have a unique id, lets store it and bail
$unique_rand_array[] = $v;
break;
}
}
// First see if we have post ids in array
if ( $unique_rand_array ) {
// Lets run our query
$final_args = [
'posts_per_page' => 6,
'post__in' => shuffle( $unique_rand_array ), // Randomize posts
'orderby' => 'post__in' // Keep post order the same as the order of post ids
];
$q = new WP_Query( $final_args );
// Lets cache our post thumbnails
update_post_thumbnail_cache( $q );
while ( $q->have_posts() ) :
$q->the_post();
?>
<div class="col-md-4">
<?php the_post_thumbnail( 'medium', array( 'class' => 'img-responsive' ) );?>
<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
</div>
<?php
endwhile;
wp_reset_postdata();
}
}
```
Finally, the following code goes into your functions file. This will flush the transient when a new post is published, a post is deleted, updated or undeleted
```
add_action( 'transition_post_status', function ()
{
delete_transient( 'random_term_post_ids' );
});
``` |
231,815 | <p>Is there a way to remove styles added with wp_add_inline_style?</p>
<p>I noticed if I call wp_add_inline_style multiple times, it just keeps adding style, it does not overwrite what was added before.</p>
<p>The plugin is adding styles:</p>
<pre><code>$inline_css = '#selector{
color:red;
}';
wp_add_inline_style($style, $inline_css);
</code></pre>
<p>If I do this again:</p>
<pre><code>$inline_css = '#other-selector{
color:blue;
}';
wp_add_inline_style($style, $inline_css);
</code></pre>
<p>It will just append those css, I would like to clear css before calling wp_add_inline_style again. </p>
| [
{
"answer_id": 231820,
"author": "Ismail",
"author_id": 70833,
"author_profile": "https://wordpress.stackexchange.com/users/70833",
"pm_score": 2,
"selected": false,
"text": "<p>Looking into <code>wp-includes/class.wp-styles.php</code> core file I found a filter to use:</p>\n\n<pre><code... | 2016/07/08 | [
"https://wordpress.stackexchange.com/questions/231815",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/45321/"
] | Is there a way to remove styles added with wp\_add\_inline\_style?
I noticed if I call wp\_add\_inline\_style multiple times, it just keeps adding style, it does not overwrite what was added before.
The plugin is adding styles:
```
$inline_css = '#selector{
color:red;
}';
wp_add_inline_style($style, $inline_css);
```
If I do this again:
```
$inline_css = '#other-selector{
color:blue;
}';
wp_add_inline_style($style, $inline_css);
```
It will just append those css, I would like to clear css before calling wp\_add\_inline\_style again. | Remove styles added with `wp_add_inline_style()`
------------------------------------------------
If we want to keep the `custom-style-css` but only remove the `custom-style-inline-css`, then we can try e.g.
```
add_action( 'wp_print_styles', function()
{
// Remove previous inline style
wp_styles()->add_data( 'custom-style', 'after', '' );
} );
```
where `after` is data key for the inline style corresponding to the `custom-style` handler.
There is exists a wrapper for `wp_styles()->add_data()`, namely [`wp_style_add_data()`](https://developer.wordpress.org/reference/functions/wp_style_add_data/).
We could then define the helper function:
```
function wpse_remove_inline_style( $handler )
{
wp_style_is( $handler, 'enqueued' )
&& wp_style_add_data( $handler, 'after', '' );
}
```
and use it like:
```
add_action( 'wp_print_styles', function()
{
// Remove previous inline style
wpse_remove_inline_style( 'custom-style' );
} );
```
I'm skipping the `function_exists` check here.
To override the inline-style, added by another plugin, with our own:
```
add_action( 'wp_print_styles', function()
{
// Remove previous inline style
wpse_remove_inline_style( 'custom-style' );
// New inline style
$custom_css = ".mycolor{
background: {blue};
}";
wp_add_inline_style( 'custom-style', $custom_css );
} );
```
Note
----
The reason why it doesn't work to override previous inline style with `wp_add_inline_style()` is because the `WP_Style::add_inline_style()` appends each incoming CSS string into an array. Internally it uses `WP_Style::add_data()` to store the accumulated CSS. Here we are using it to overcome the *appending* restriction of `wp_add_inline_style()`. |
231,816 | <p>I have created a simple plugin that locks down content for users not logged in and it is working fine. However any user on a multi-author site could use the same short code in his post to lock down content too. I do not want this to happen. </p>
<p>How may I restrict this functionality to administrators only?
This current code thows up a fatal error:Fatal error: Call to undefined function wp_get_current_user()</p>
<pre><code>public function check_user_role() {
if(current_user_can( 'activate_plugins' )) {
return true;
}
}
</code></pre>
<p>I then intended to use this method in my class constructor to determine if the add_shortcode() function should run. Any clues how I should go about implementing this shall be appreciated.</p>
| [
{
"answer_id": 231818,
"author": "Ismail",
"author_id": 70833,
"author_profile": "https://wordpress.stackexchange.com/users/70833",
"pm_score": 0,
"selected": false,
"text": "<blockquote>\n <p>Fatal error: Call to undefined function wp_get_current_user()</p>\n</blockquote>\n\n<p>This ca... | 2016/07/08 | [
"https://wordpress.stackexchange.com/questions/231816",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/96667/"
] | I have created a simple plugin that locks down content for users not logged in and it is working fine. However any user on a multi-author site could use the same short code in his post to lock down content too. I do not want this to happen.
How may I restrict this functionality to administrators only?
This current code thows up a fatal error:Fatal error: Call to undefined function wp\_get\_current\_user()
```
public function check_user_role() {
if(current_user_can( 'activate_plugins' )) {
return true;
}
}
```
I then intended to use this method in my class constructor to determine if the add\_shortcode() function should run. Any clues how I should go about implementing this shall be appreciated. | >
> Fatal error: Call to undefined function wp\_get\_current\_user()
>
>
>
This can be fixed by declaring `check_user_role` only when WP is ready, hooking into `wp` (to use WordPress functions and methods) or performing other workaround.
Simply check if `manage_options` capability is there for the user too ( or verify if administrator is in the roles list `in_array( "administrator", $current_user->roles )` ):
```
add_action("wp", function() {
function check_user_role() {
return current_user_can( "manage_options" ) && current_user_can( 'activate_plugins' );
}
});
```
Hope that helps. |
231,838 | <p>I have created custom page template. Now I have to make it configurable, however since I am using more than one template in my theme I would like to make sure that configuration will be available only when the user chooses this template for a page. Is there an option to do so? </p>
<p><code>add_meta_box</code> accepts different <code>$post_type</code>, so the closest I can get is to add metabox to all pages, which I would like to avoid. </p>
| [
{
"answer_id": 231839,
"author": "tillinberlin",
"author_id": 26059,
"author_profile": "https://wordpress.stackexchange.com/users/26059",
"pm_score": 0,
"selected": false,
"text": "<p>\"<em>available only when user choose this template</em>\" ? I'm not sure (I doubt it) if this is even p... | 2016/07/09 | [
"https://wordpress.stackexchange.com/questions/231838",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/77480/"
] | I have created custom page template. Now I have to make it configurable, however since I am using more than one template in my theme I would like to make sure that configuration will be available only when the user chooses this template for a page. Is there an option to do so?
`add_meta_box` accepts different `$post_type`, so the closest I can get is to add metabox to all pages, which I would like to avoid. | ```
<?
// Check:
// 1. If you are editing post, CPT, or page
// 2. If post type IS NOT SET
if( 'post.php' == basename($_SERVER['REQUEST_URI'], '?' . $_SERVER['QUERY_STRING']) && !isset($_GET['post_type']) ) {
// get post ID
$postid = $_GET['post'];
// check the template file name
if ('my_template.php' == get_page_template_slug($postid) ) {
// add your metabox here
add_action( 'add_meta_boxes', 'my_metabox' );
}
}
```
I don't remember why I was checking post type, not post ID, but you can change
```
!isset($_GET['post_type'])
```
to check if post ID is set:
```
isset($_GET['post'])
```
**Note**: meta box will be available only after you save your post (page) using appropriate template. |
231,862 | <p>I am adding a function to the header:</p>
<pre><code>add_action('wp_head', 'mine');
function mine() {
global $authordata;
$avatar_url = get_avatar_ur($authordata->user_email);
// ....
}
</code></pre>
<p>But I am getting the error: <code>trying to get property of non-object</code>.
I guess this is because I am in the header and not inside the post.</p>
<p>How can I access the authordata data from the header, and only when in a post page?</p>
| [
{
"answer_id": 231876,
"author": "wpclevel",
"author_id": 92212,
"author_profile": "https://wordpress.stackexchange.com/users/92212",
"pm_score": 2,
"selected": false,
"text": "<p>The global <code>$authordata</code> variable is only available by default when <a href=\"https://core.trac.w... | 2016/07/09 | [
"https://wordpress.stackexchange.com/questions/231862",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/98079/"
] | I am adding a function to the header:
```
add_action('wp_head', 'mine');
function mine() {
global $authordata;
$avatar_url = get_avatar_ur($authordata->user_email);
// ....
}
```
But I am getting the error: `trying to get property of non-object`.
I guess this is because I am in the header and not inside the post.
How can I access the authordata data from the header, and only when in a post page? | The global `$authordata` variable is only available by default when [`$wp_query->is_author() && isset($wp_query->post)` condition](https://core.trac.wordpress.org/browser/tags/4.5/src/wp-includes/class-wp.php#L583) is satisfied.
It means that you can't access `$authordata` inside a single post page.
You may try to get author data via `$wp_query`:
```
add_action('wp_head', function()
{
global $wp_query;
$userdata = get_userdata($wp_query->post->post_author);
$avatar_url = get_avatar_ur($userdata->user_email);
...
}, 10, 0);
``` |
231,898 | <p>I'm using a WP plugin Called <a href="https://wordpress.org/plugins/search-filter/" rel="nofollow">Search and Filter</a> to filter a custom post type — a user directory.</p>
<p>The plugin lets a user filter the directory by specifying terms.</p>
<p>It will also let a user filter the directoy by MULTIPLE terms.</p>
<p>When it does so, I get a slug constructed like this:</p>
<p><a href="http://www.consular-corps-college.org/dir-type/chiefs-of-protocol/?country=united-states-of-america" rel="nofollow">http://www.consular-corps-college.org/dir-type/chiefs-of-protocol/?country=united-states-of-america</a></p>
<p>Posts are returned via the <code>taxonomy.php</code> page.</p>
<p>First, I didn't even know you could do this, so that's cool.</p>
<p>But my question is, how do I display the second term in the slug query?</p>
<p>In other words, I can get the taxonomy.php page to display the term "Chiefs of Protocol" with <code>single_term_title()</code>.</p>
<p>But how can I get WordPress to display the second term which is queried in the slug — in this case "United States of America"?</p>
| [
{
"answer_id": 231876,
"author": "wpclevel",
"author_id": 92212,
"author_profile": "https://wordpress.stackexchange.com/users/92212",
"pm_score": 2,
"selected": false,
"text": "<p>The global <code>$authordata</code> variable is only available by default when <a href=\"https://core.trac.w... | 2016/07/10 | [
"https://wordpress.stackexchange.com/questions/231898",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/98107/"
] | I'm using a WP plugin Called [Search and Filter](https://wordpress.org/plugins/search-filter/) to filter a custom post type — a user directory.
The plugin lets a user filter the directory by specifying terms.
It will also let a user filter the directoy by MULTIPLE terms.
When it does so, I get a slug constructed like this:
<http://www.consular-corps-college.org/dir-type/chiefs-of-protocol/?country=united-states-of-america>
Posts are returned via the `taxonomy.php` page.
First, I didn't even know you could do this, so that's cool.
But my question is, how do I display the second term in the slug query?
In other words, I can get the taxonomy.php page to display the term "Chiefs of Protocol" with `single_term_title()`.
But how can I get WordPress to display the second term which is queried in the slug — in this case "United States of America"? | The global `$authordata` variable is only available by default when [`$wp_query->is_author() && isset($wp_query->post)` condition](https://core.trac.wordpress.org/browser/tags/4.5/src/wp-includes/class-wp.php#L583) is satisfied.
It means that you can't access `$authordata` inside a single post page.
You may try to get author data via `$wp_query`:
```
add_action('wp_head', function()
{
global $wp_query;
$userdata = get_userdata($wp_query->post->post_author);
$avatar_url = get_avatar_ur($userdata->user_email);
...
}, 10, 0);
``` |
231,901 | <p>I've tagged some products with 'tag1', 'tag2' or sometimes both.</p>
<p>I want to list the categories that contain products with a specific tag, so 'Cat1' will only be listed if it has a product that is tagged 'tag1'.</p>
| [
{
"answer_id": 231876,
"author": "wpclevel",
"author_id": 92212,
"author_profile": "https://wordpress.stackexchange.com/users/92212",
"pm_score": 2,
"selected": false,
"text": "<p>The global <code>$authordata</code> variable is only available by default when <a href=\"https://core.trac.w... | 2016/07/10 | [
"https://wordpress.stackexchange.com/questions/231901",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/98112/"
] | I've tagged some products with 'tag1', 'tag2' or sometimes both.
I want to list the categories that contain products with a specific tag, so 'Cat1' will only be listed if it has a product that is tagged 'tag1'. | The global `$authordata` variable is only available by default when [`$wp_query->is_author() && isset($wp_query->post)` condition](https://core.trac.wordpress.org/browser/tags/4.5/src/wp-includes/class-wp.php#L583) is satisfied.
It means that you can't access `$authordata` inside a single post page.
You may try to get author data via `$wp_query`:
```
add_action('wp_head', function()
{
global $wp_query;
$userdata = get_userdata($wp_query->post->post_author);
$avatar_url = get_avatar_ur($userdata->user_email);
...
}, 10, 0);
``` |
231,926 | <p>I'm dynamically generating my category post by getting the Page title and match it with the category name. The category I'm posting sometimes has a subcategory now I need to separate this subcategory by groups. I'm using this code. </p>
<pre><code><ul>
<?php
global $post;
$post_slug = get_the_title();
$args = array ( 'category_name' => $post_slug, 'posts_per_page' => -1, 'orderby' => title, 'order' => ASC);
$myposts = get_posts( $args );
foreach( $myposts as $post ) : setup_postdata($post); ?>
<li>
<strong><?php the_title(); ?></strong>
<?php the_content(); ?>
</li>
<?php endforeach; ?>
</ul>
</code></pre>
<p>I need to call my category only by using the page title. since I'm using a template that post different category and controlling it by name title of the page. Not quite sure if I can convert that to <code>category => ID</code></p>
<p>Please see link <a href="http://prntscr.com/by26xn" rel="nofollow">here</a> for the explanation and mock</p>
<p>Found this <a href="http://www.wpbeginner.com/wp-tutorials/display-subcategories-on-category-pages-in-wordpress/" rel="nofollow">thread</a> not sure if its going to fit on what I did? also this <a href="https://yoast.com/showing-subcategories-on-wordpress-category-pages/" rel="nofollow">one</a> </p>
| [
{
"answer_id": 231928,
"author": "Milo",
"author_id": 4771,
"author_profile": "https://wordpress.stackexchange.com/users/4771",
"pm_score": 1,
"selected": false,
"text": "<p>You can use <a href=\"https://codex.wordpress.org/Function_Reference/get_term_by\" rel=\"nofollow\"><code>get_term... | 2016/07/11 | [
"https://wordpress.stackexchange.com/questions/231926",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/62183/"
] | I'm dynamically generating my category post by getting the Page title and match it with the category name. The category I'm posting sometimes has a subcategory now I need to separate this subcategory by groups. I'm using this code.
```
<ul>
<?php
global $post;
$post_slug = get_the_title();
$args = array ( 'category_name' => $post_slug, 'posts_per_page' => -1, 'orderby' => title, 'order' => ASC);
$myposts = get_posts( $args );
foreach( $myposts as $post ) : setup_postdata($post); ?>
<li>
<strong><?php the_title(); ?></strong>
<?php the_content(); ?>
</li>
<?php endforeach; ?>
</ul>
```
I need to call my category only by using the page title. since I'm using a template that post different category and controlling it by name title of the page. Not quite sure if I can convert that to `category => ID`
Please see link [here](http://prntscr.com/by26xn) for the explanation and mock
Found this [thread](http://www.wpbeginner.com/wp-tutorials/display-subcategories-on-category-pages-in-wordpress/) not sure if its going to fit on what I did? also this [one](https://yoast.com/showing-subcategories-on-wordpress-category-pages/) | You can use [`get_term_by`](https://codex.wordpress.org/Function_Reference/get_term_by) to get a category by `name`-
```
$category = get_term_by( 'name', $post_slug, 'category' );
echo $category->term_id;
``` |
231,942 | <p>I am trying to access a single value from my database through my <code>functions.php</code>. I have tried three different ways to get a result using a dynamic ID and none have worked. I always get NULL as the response. Using a WP_query is not possibility here, so I need to solve this using SQL.</p>
<p><strong>Attempt #1:</strong> </p>
<pre><code>global $post;
global $wpdb;
$post_ID = $post->ID;
$result = $wpdb->get_var($wpdb->prepare(
"
SELECT meta_value
FROM $wpdb->postmeta
WHERE post_id = %d
AND meta_key = 'wpcf-release-date'
",
$post_ID
) );
</code></pre>
<p><strong>Attempt #2:</strong></p>
<pre><code>$result = $wpdb->get_var("SELECT meta_value FROM $wpdb->postmeta WHERE meta_key = 'wpcf-release-date' AND post_id = $post_ID");
</code></pre>
<p><strong>Attempt #3:</strong> </p>
<pre><code>$result = $wpdb->get_var("SELECT meta_value FROM $wpdb->postmeta WHERE meta_key = 'wpcf-release-date' AND post_id = " . $post_ID);
</code></pre>
<p>I know my query works, I tested the SQL query in Phpmyadmin with a static ID. I can also set the ID manually in my function which will yield a result, but does not help me if it is not dynamic.</p>
<p><strong>SQL Query</strong> </p>
<pre><code>SELECT `meta_value`
FROM `wp_postmeta`
WHERE post_id = 249
AND meta_key = 'wpcf-release-date'
</code></pre>
<p>I assume I am overlooking something simple. </p>
| [
{
"answer_id": 231947,
"author": "Ehsaan",
"author_id": 54782,
"author_profile": "https://wordpress.stackexchange.com/users/54782",
"pm_score": 2,
"selected": false,
"text": "<p>I tested your all attempts in a shortcode:</p>\n\n<pre><code>function add_test_shortcode() {\n global $wpdb;\... | 2016/07/11 | [
"https://wordpress.stackexchange.com/questions/231942",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/25506/"
] | I am trying to access a single value from my database through my `functions.php`. I have tried three different ways to get a result using a dynamic ID and none have worked. I always get NULL as the response. Using a WP\_query is not possibility here, so I need to solve this using SQL.
**Attempt #1:**
```
global $post;
global $wpdb;
$post_ID = $post->ID;
$result = $wpdb->get_var($wpdb->prepare(
"
SELECT meta_value
FROM $wpdb->postmeta
WHERE post_id = %d
AND meta_key = 'wpcf-release-date'
",
$post_ID
) );
```
**Attempt #2:**
```
$result = $wpdb->get_var("SELECT meta_value FROM $wpdb->postmeta WHERE meta_key = 'wpcf-release-date' AND post_id = $post_ID");
```
**Attempt #3:**
```
$result = $wpdb->get_var("SELECT meta_value FROM $wpdb->postmeta WHERE meta_key = 'wpcf-release-date' AND post_id = " . $post_ID);
```
I know my query works, I tested the SQL query in Phpmyadmin with a static ID. I can also set the ID manually in my function which will yield a result, but does not help me if it is not dynamic.
**SQL Query**
```
SELECT `meta_value`
FROM `wp_postmeta`
WHERE post_id = 249
AND meta_key = 'wpcf-release-date'
```
I assume I am overlooking something simple. | Turns out all of my attempts were viable (Thanks ehsaan for also confirming). The issue was that I was trying to get data from a field that was empty at the time of the function. (I was creating a new/updated post that hadn't updated the field yet).
**Solution (delay the hook):**
```
// Time out the custom field to update AFTER the post has been created/updated
function save_custom() {
global $post;
$post_ID = $post->ID;
$result = get_post_meta( $post_ID, 'wpcf-release-date', 1 );
// Add a new key "era"
add_post_meta($post_ID, "era", $result, true);
// If there is already a key "era", then update it
if ( ! add_post_meta($post_ID, "era", $result, true) ) {
update_post_meta( $post_ID, "era", $result );
}
}
add_action('save_post', 'save_custom', 0);
add_action('save_post', 'save_custom', 10);
add_action('save_post', 'save_custom', 999);
``` |
231,976 | <p>I want to add a new menu point to post that shows posts of a certain category. Adding a new page is easy if it is just a new post type. But I want to only show posts with a specific category and when updating posts make sure the category is checked.</p>
<p>IS there no way of doing this? I was hoping for some simple functon, like the way register_post_type() does it. As there doesn't seem to be, does anyone give me any tips about how to do this? Is it even possible? Or should I just use a custom post type?</p>
| [
{
"answer_id": 231987,
"author": "Ivijan Stefan Stipić",
"author_id": 82023,
"author_profile": "https://wordpress.stackexchange.com/users/82023",
"pm_score": 0,
"selected": false,
"text": "<p>You can loop posts by category name or ID:</p>\n\n<pre><code>$query = new WP_Query( array( 'cate... | 2016/07/11 | [
"https://wordpress.stackexchange.com/questions/231976",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/98158/"
] | I want to add a new menu point to post that shows posts of a certain category. Adding a new page is easy if it is just a new post type. But I want to only show posts with a specific category and when updating posts make sure the category is checked.
IS there no way of doing this? I was hoping for some simple functon, like the way register\_post\_type() does it. As there doesn't seem to be, does anyone give me any tips about how to do this? Is it even possible? Or should I just use a custom post type? | You can filter the posts list by appending `?category_name=xx` to the admin posts list URL, and you can add a submenu page with that URL as the target via `add_submenu_page`:
```
add_action( 'admin_menu', 'wpd_admin_menu_item' );
function wpd_admin_menu_item(){
add_submenu_page(
'edit.php',
'Page title',
'Menu item title',
'edit_posts',
'edit.php?category_name=somecat'
);
}
``` |
231,995 | <p>I have a website that displays a slideshow using custom fields and the <a href="http://kenwheeler.github.io/slick/" rel="nofollow">Slick</a> carousel, using the code below. </p>
<pre><code> <?php $entries = get_post_meta( get_the_ID(), '_mysite_homepage_slider_group', true );
foreach ( (array) $entries as $key => $entry ) {
$img = $title = $url = $desc = '';
if ( isset( $entry['_mysite_homepage_slider_title'] ) )
$title = esc_html( $entry['_mysite_homepage_slider_title'] );
if ( isset( $entry['_mysite_homepage_slider_caption'] ) )
$desc = wpautop( $entry['_mysite_homepage_slider_caption'] );
if ( isset( $entry['_mysite_homepage_slider_url'] ) )
$url = esc_html( $entry['_mysite_homepage_slider_url'] );
if ( isset( $entry['_mysite_homepage_slider_image_id'] ) ) {
$img = wp_get_attachment_image_url( $entry['_mysite_homepage_slider_image_id'], 'full');
}
} ?>
</code></pre>
<p>I'd like the user to be able to disable individual slides by clicking a checkbox in the back-end. </p>
<p>Simple enough, right?</p>
<p>So, I added a checkbox and came up with this code to drop in to my snippet. It checks to see if the checkbox is clicked. I tried placing it immediately after the <code>foreach</code> line, like this:</p>
<pre><code> foreach ( (array) $entries as $key => $entry ) {
// Display slides if checkbox is NOT clicked (e.g., is empty)
if ( empty( $entry['_mysite_homepage_slider_checkbox'] ) ) {
$img = $title = $url = $desc = '';
(...)
}
</code></pre>
<p>It kind of works — the slide doesn't show up on the page — but something's still getting through. A duplicate slide is being created.</p>
<p>For example, There are 4 slides in the back end. The 4th has a checkbox that is checked. On the front end, Slide #3 is displayed twice. It appears the code is outputting this:</p>
<ul>
<li>Slide 1 </li>
<li>Slide 2</li>
<li>Slide 3 </li>
<li>Slide 3 (again!)</li>
</ul>
<p>Where have I gone wrong? </p>
<p><strong>EDIT: <a href="https://gist.github.com/madebyelmcity/bc7061b4795c4769d4a1b9cbb3eae970" rel="nofollow">Final code snippet with answer</a></strong>, for anyone who may find this useful in the future. </p>
| [
{
"answer_id": 232002,
"author": "slashbob",
"author_id": 54908,
"author_profile": "https://wordpress.stackexchange.com/users/54908",
"pm_score": -1,
"selected": false,
"text": "<p>Are all the if-statements that output html actually <em>inside</em> the checkbox if-statement? Can't really... | 2016/07/11 | [
"https://wordpress.stackexchange.com/questions/231995",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/52548/"
] | I have a website that displays a slideshow using custom fields and the [Slick](http://kenwheeler.github.io/slick/) carousel, using the code below.
```
<?php $entries = get_post_meta( get_the_ID(), '_mysite_homepage_slider_group', true );
foreach ( (array) $entries as $key => $entry ) {
$img = $title = $url = $desc = '';
if ( isset( $entry['_mysite_homepage_slider_title'] ) )
$title = esc_html( $entry['_mysite_homepage_slider_title'] );
if ( isset( $entry['_mysite_homepage_slider_caption'] ) )
$desc = wpautop( $entry['_mysite_homepage_slider_caption'] );
if ( isset( $entry['_mysite_homepage_slider_url'] ) )
$url = esc_html( $entry['_mysite_homepage_slider_url'] );
if ( isset( $entry['_mysite_homepage_slider_image_id'] ) ) {
$img = wp_get_attachment_image_url( $entry['_mysite_homepage_slider_image_id'], 'full');
}
} ?>
```
I'd like the user to be able to disable individual slides by clicking a checkbox in the back-end.
Simple enough, right?
So, I added a checkbox and came up with this code to drop in to my snippet. It checks to see if the checkbox is clicked. I tried placing it immediately after the `foreach` line, like this:
```
foreach ( (array) $entries as $key => $entry ) {
// Display slides if checkbox is NOT clicked (e.g., is empty)
if ( empty( $entry['_mysite_homepage_slider_checkbox'] ) ) {
$img = $title = $url = $desc = '';
(...)
}
```
It kind of works — the slide doesn't show up on the page — but something's still getting through. A duplicate slide is being created.
For example, There are 4 slides in the back end. The 4th has a checkbox that is checked. On the front end, Slide #3 is displayed twice. It appears the code is outputting this:
* Slide 1
* Slide 2
* Slide 3
* Slide 3 (again!)
Where have I gone wrong?
**EDIT: [Final code snippet with answer](https://gist.github.com/madebyelmcity/bc7061b4795c4769d4a1b9cbb3eae970)**, for anyone who may find this useful in the future. | There's some code missing from your question - the code where your slides are actually output.
The `foreach` loop you've posted only sets the variables, and the actual output happens below the loop.
So, all you're doing on the fourth slide is avoiding setting the variables... hence the slide is still output, but using the third slide's variables.
Your `if` checkbox logic looks ok; you just need to include the logic on the actual code that outputs the slides too. |
232,029 | <p>I need help with my <code>query</code> that uses <code>rewind_posts</code> so that if a post is in a particular category, it moves to the top. What I would like to do is have a query that splits posts into a two-column page (left and right divs) and if a post is in a category called <code>First</code>, it's at the top of the list in the left column.</p>
<p>I was able to do this task doing two different <code>queries</code> but I'm having problems merging into one <code>query</code>. I tired to do it myself but the <code>$i++</code> confused me so I'm asking for help on how to merge two separate queries into one.</p>
<p>This is the first <code>query</code> where if any post belongs in a first or second category, they are brought to the top:</p>
<pre><code><?php $args = array(
'tax_query' => array(
array(
'taxonomy' => 'post-status',
'field' => 'slug',
'terms' => array ('post-status-published')
)
)
); $query = new WP_Query( $args ); ?>
<?php if ( $query->have_posts() ) : $duplicates = []; while ( $query->have_posts() ) : $query->the_post(); ?>
<?php if ( in_category( 'First' ) ) : ?>
<?php the_title();?><br>
<?php $duplicates[] = get_the_ID(); ?>
<?php endif; endwhile; ?>
<?php $query->rewind_posts(); ?>
<?php while ( $query->have_posts() ) : $query->the_post(); ?>
<?php if ( in_category( 'Second' ) ) : if ( in_array( get_the_ID(), $duplicates ) ) continue; ?>
<?php the_title(); ?><br>
<?php $duplicates[] = get_the_ID(); ?>
<?php endif; endwhile; ?>
<?php $query->rewind_posts(); ?>
<?php while ( $query->have_posts() ) : $query->the_post(); ?>
<?php if ( in_array( get_the_ID(), $duplicates ) ) continue; ?>
<?php the_title();?><br>
<?php endwhile; wp_reset_postdata(); endif; ?>
</code></pre>
<p>This is the <code>query</code> that splits posts into two columns:</p>
<pre><code><?php $args = array(
'tax_query' => array(
array(
'taxonomy' => 'post-status',
'field' => 'slug',
'terms' => array ('post-status-published')
))); $wp_query = new WP_Query( $args ); ?>
<div class="left">
<?php if (have_posts()) : while(have_posts()) : $i++; if(($i % 2) == 0) : $wp_query->next_post(); else : the_post(); ?>
<?php the_title(); ?><br>
<?php endif; endwhile; ?></div><?php else:?>
<?php endif; ?>
<?php $i = 0; rewind_posts(); ?>
<div id="right">
<?php if (have_posts()) : while(have_posts()) : $i++; if(($i % 2) !== 0) : $wp_query->next_post(); else : the_post(); ?>
<?php the_title(); ?><br>
<?php endif; endwhile; ?></div><?php else:?>
<?php endif; ?>
</code></pre>
<p>An example of what I'm trying to accomplish:</p>
<pre><code>Title - First | Title
Title - Second | Title
Title | Title
</code></pre>
<p>Thanks!</p>
| [
{
"answer_id": 232057,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 1,
"selected": false,
"text": "<h2>REWORKED APPROACH</h2>\n\n<p>Due to this becoming a bit of tameletjie due to styling issues, lets rewo... | 2016/07/12 | [
"https://wordpress.stackexchange.com/questions/232029",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/8049/"
] | I need help with my `query` that uses `rewind_posts` so that if a post is in a particular category, it moves to the top. What I would like to do is have a query that splits posts into a two-column page (left and right divs) and if a post is in a category called `First`, it's at the top of the list in the left column.
I was able to do this task doing two different `queries` but I'm having problems merging into one `query`. I tired to do it myself but the `$i++` confused me so I'm asking for help on how to merge two separate queries into one.
This is the first `query` where if any post belongs in a first or second category, they are brought to the top:
```
<?php $args = array(
'tax_query' => array(
array(
'taxonomy' => 'post-status',
'field' => 'slug',
'terms' => array ('post-status-published')
)
)
); $query = new WP_Query( $args ); ?>
<?php if ( $query->have_posts() ) : $duplicates = []; while ( $query->have_posts() ) : $query->the_post(); ?>
<?php if ( in_category( 'First' ) ) : ?>
<?php the_title();?><br>
<?php $duplicates[] = get_the_ID(); ?>
<?php endif; endwhile; ?>
<?php $query->rewind_posts(); ?>
<?php while ( $query->have_posts() ) : $query->the_post(); ?>
<?php if ( in_category( 'Second' ) ) : if ( in_array( get_the_ID(), $duplicates ) ) continue; ?>
<?php the_title(); ?><br>
<?php $duplicates[] = get_the_ID(); ?>
<?php endif; endwhile; ?>
<?php $query->rewind_posts(); ?>
<?php while ( $query->have_posts() ) : $query->the_post(); ?>
<?php if ( in_array( get_the_ID(), $duplicates ) ) continue; ?>
<?php the_title();?><br>
<?php endwhile; wp_reset_postdata(); endif; ?>
```
This is the `query` that splits posts into two columns:
```
<?php $args = array(
'tax_query' => array(
array(
'taxonomy' => 'post-status',
'field' => 'slug',
'terms' => array ('post-status-published')
))); $wp_query = new WP_Query( $args ); ?>
<div class="left">
<?php if (have_posts()) : while(have_posts()) : $i++; if(($i % 2) == 0) : $wp_query->next_post(); else : the_post(); ?>
<?php the_title(); ?><br>
<?php endif; endwhile; ?></div><?php else:?>
<?php endif; ?>
<?php $i = 0; rewind_posts(); ?>
<div id="right">
<?php if (have_posts()) : while(have_posts()) : $i++; if(($i % 2) !== 0) : $wp_query->next_post(); else : the_post(); ?>
<?php the_title(); ?><br>
<?php endif; endwhile; ?></div><?php else:?>
<?php endif; ?>
```
An example of what I'm trying to accomplish:
```
Title - First | Title
Title - Second | Title
Title | Title
```
Thanks! | It's complete. This is my final code:
```
// the query. Only show posts that belong to the taxonomy called "post-status" and they have a slug called "post-status-published"
<?php $args = array('tax_query' => array(array('taxonomy' => 'post-status','field' => 'slug','terms' => array ('post-status-published')))); $query = new WP_Query( $args );?>
// the loop. Also gets variables to false and enables the variable "duplicate".
<?php if ( $query->have_posts() ) : $firstonly = false; $major = false; $groupa = false; $groupb = false; $groupc = false; $groupd = false; $duplicates = []; while ( $query->have_posts() ) : $query->the_post(); ?>
// checks if any post in the loop belongs to a certain category. If any post with those category is in the loop, the variable is changed to "true". Also adds the "Post ID" in that category to the "duplicate" variable.
<?php if ( in_category('first') ) : ?>
<?php $firstonly = true; ?>
<?php $duplicates[] = get_the_ID(); ?>
<?php endif; ?>
<?php if ( in_category(array('major','major-first') ) ) : ?>
<?php $major = true; ?>
<?php $duplicates[] = get_the_ID(); ?>
<?php endif; ?>
<?php if ( in_category(array('group-a-first','group-a')) ) : ?>
<?php $groupa = true; ?>
<?php $duplicates[] = get_the_ID(); ?>
<?php endif;?>
<?php if ( in_category(array('group-b-first','group-b')) ) : ?>
<?php $groupb = true; ?>
<?php $duplicates[] = get_the_ID(); ?>
<?php endif;?>
<?php if ( in_category(array('group-c-first','group-c')) ) : ?>
<?php $groupc = true; ?>
<?php $duplicates[] = get_the_ID(); ?>
<?php endif;?>
<?php if ( in_category(array('group-d-first','group-d')) ) : ?>
<?php $groupd = true; ?>
<?php $duplicates[] = get_the_ID(); ?>
<?php endif;?>
// Close the loop and rewind the query
<?php endwhile; endif; ?>
<?php $query->rewind_posts(); ?>
// The output of the loop. Only show the output if the above is set to true.
<?php if ($major == true):?>
<div class="group-major">
<?php foreach($duplicates as $postID) { ?>
<?php $postData = get_post( $postID );?>
<?php if(esc_html(get_the_category($postID)[0]->slug) == 'major-first'):?>
<div class="major-first">
major first - <?php print $postData->post_title;?><br>
</div>
<?php endif;?>
<?php } ?>
<div class="group-sorted">
<?php foreach($duplicates as $postID) { ?>
<?php $postData = get_post( $postID );?>
<?php if(esc_html(get_the_category($postID)[0]->slug) == 'major'):?>
<div class="post">
major - <?php print $postData->post_title;?><br>
</div>
<?php endif;?>
<?php } ?>
</div></div>
<?php endif;?>
<?php if ($firstonly == true):?>
<?php foreach($duplicates as $postID) { ?>
<?php $postData = get_post( $postID );?>
first - <?php print $postData->post_title;?><br>
<?php } ?>
<?php endif;?>
<?php if (($groupa == true) or ($groupb == true) or ($groupc == true) or ($groupd == true)):?>
<?php if (($groupa == true) && ($groupb == false)):?>
group solo start<br>
<?php foreach($duplicates as $postID) { ?>
<?php $postData = get_post( $postID );?>
<?php if(esc_html(get_the_category($postID)[0]->slug) == 'group-a-first'):?>
group a first (only) - <?php print $postData->post_title;?><br>
<?php endif;?>
<?php } ?>
<?php else:?>
group multi start<br>
<?php foreach($duplicates as $postID) { ?>
<?php $postData = get_post( $postID );?>
<?php if(esc_html(get_the_category($postID)[0]->slug) == 'group-a-first'):?>
group a first (multi) - <?php print $postData->post_title;?><br>
<?php endif;?>
<?php } ?>
<?php endif;?>
<?php foreach($duplicates as $postID) { ?>
<?php $postData = get_post( $postID );?>
<?php if(esc_html(get_the_category($postID)[0]->slug) == 'group-a'):?>
group a - <?php print $postData->post_title;?><br>
<?php endif;?>
<?php } ?>
<?php foreach($duplicates as $postID) { ?>
<?php $postData = get_post( $postID );?>
<?php if(esc_html(get_the_category($postID)[0]->slug) == 'group-b-first'):?>
group b first - <?php print $postData->post_title;?><br>
<?php endif;?>
<?php } ?>
<?php foreach($duplicates as $postID) { ?>
<?php $postData = get_post( $postID );?>
<?php if(esc_html(get_the_category($postID)[0]->slug) == 'group-b'):?>
group b - <?php print $postData->post_title;?><br>
<?php endif;?>
<?php } ?>
<?php if (( true == $groupa ) && (false == $groupb) && (false == $groupc) && (false == $groupd)) :?>
solo end<br>
<?php endif;?>
<?php if (( true == $groupa ) && (true == $groupb) && (false == $groupc) && (false == $groupd)) :?>
group b multi end<br>
<?php endif;?>
<?php foreach($duplicates as $postID) { ?>
<?php $postData = get_post( $postID );?>
<?php if(esc_html(get_the_category($postID)[0]->slug) == 'group-c-first'):?>
group c first - <?php print $postData->post_title;?><br>
<?php endif;?>
<?php } ?>
<?php foreach($duplicates as $postID) { ?>
<?php $postData = get_post( $postID );?>
<?php if(esc_html(get_the_category($postID)[0]->slug) == 'group-c'):?>
group c - <?php print $postData->post_title;?><br>
<?php endif;?>
<?php } ?>
<?php if (( true == $groupa ) && (true == $groupb) && (true == $groupc) && ($groupd == false)) :?>
group c multi end<br>
<?php endif;?>
<?php foreach($duplicates as $postID) { ?>
<?php $postData = get_post( $postID );?>
<?php if(esc_html(get_the_category($postID)[0]->slug) == 'group-d-first'):?>
group d first - <?php print $postData->post_title;?><br>
<?php endif;?>
<?php } ?>
<?php foreach($duplicates as $postID) { ?>
<?php $postData = get_post( $postID );?>
<?php if(esc_html(get_the_category($postID)[0]->slug) == 'group-d'):?>
group d - <?php print $postData->post_title;?><br>
<?php endif;?>
<?php } ?>
<?php if (( true == $groupa ) && (true == $groupb) && (true == $groupc) && ($groupd == true)) :?>
group d multi end<br>
<?php endif;?>
<?php endif;?>
//the second loop. Also sets two columns
<?php $row_start = 1; while ( $query->have_posts() ) : $query->the_post();?>
// if the category "first" is set to true, split posts into columns with most posts favoring the left. I.E. if the loop has ten posts, it is evenly split. If not, the split favors the right side.
<?php if(true == $firstonly):?>
<?php if(in_array( get_the_ID(), $duplicates ) ) continue; ?>
<?php if($row_start % 2 != 0 && $row_start != ($sum_total = $wp_query->found_posts - count($duplicates))):?>
<?php $left[] = get_the_ID();?>
<?php else:?>
<?php $right[] = get_the_ID();?>
<?php endif;?>
<?php else:?>
<?php if(in_array( get_the_ID(), $duplicates ) ) continue; ?>
<?php if($row_start % 2 != 0):?>
<?php $left[] = get_the_ID();?>
<?php else:?>
<?php $right[] = get_the_ID();?>
<?php endif;?>
<?php endif;?>
// end the column, the loop, the query and reset the query.
<?php ++$row_start; endwhile; wp_reset_postdata();?>
// the output of the second loop.
<?php foreach($left as $postID) { ;?>
<?php $postData = get_post( $postID );?>
left - <?php print $postData->post_title;?><br>
<?php } ?>
<?php foreach($right as $postID) { ;?>
<?php $postData = get_post( $postID );?>
right - <?php print $postData->post_title;?><br>
<?php } ?>
```
Thanks everyone for the help! This is probably the most complex problem I've ever encountered. Thank you so much for the help! |
232,038 | <p>We are running several sub-domain sites on a WordPress Multisite environment and want to switch the primary site from the root to a sub-domain like so:</p>
<p>Current site is <code>example.com</code> with <code>ID 1</code> (cannot rename because field is set and uneditable)</p>
<p>New site is <code>new.example.com</code> with <code>ID 15</code> (tried to rename to <code>example.com</code>)</p>
<p>I followed some instructions for switching that involved renaming the sites and updating the <code>wp-config.php</code> file to give the new ID of 15 for the <code>SITE_ID_CURRENT_SITE</code> and <code>Blog_ID_CURRENT_SITE</code>. The result was the main site did not change and the admin got mucked up.</p>
<p>Is there a straight forward way to switch the main site out and replace it with the sub-domain site content without importing posts/pages and plugins?</p>
<hr>
<p>UPDATE:</p>
<p>Thanks for giving these tips. My conclusion with what I've seen in the database, read, and get from you is that the new subdomain site to replace the main site needs to have the base table names and ID of 1, updated paths etc. My only worry is that after switching these the network admin will have a problem -- so I basically need to compare the base tables (wp_options etc) to the equivalent (wp_x_options etc) to see if there is anything unique related to the network admin in those base tables.</p>
| [
{
"answer_id": 235578,
"author": "David",
"author_id": 31323,
"author_profile": "https://wordpress.stackexchange.com/users/31323",
"pm_score": 4,
"selected": false,
"text": "<p><del>Four years old and no answer? So here we go…-</del></p>\n\n<p>Let's take the following network setup as ex... | 2016/07/12 | [
"https://wordpress.stackexchange.com/questions/232038",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/98186/"
] | We are running several sub-domain sites on a WordPress Multisite environment and want to switch the primary site from the root to a sub-domain like so:
Current site is `example.com` with `ID 1` (cannot rename because field is set and uneditable)
New site is `new.example.com` with `ID 15` (tried to rename to `example.com`)
I followed some instructions for switching that involved renaming the sites and updating the `wp-config.php` file to give the new ID of 15 for the `SITE_ID_CURRENT_SITE` and `Blog_ID_CURRENT_SITE`. The result was the main site did not change and the admin got mucked up.
Is there a straight forward way to switch the main site out and replace it with the sub-domain site content without importing posts/pages and plugins?
---
UPDATE:
Thanks for giving these tips. My conclusion with what I've seen in the database, read, and get from you is that the new subdomain site to replace the main site needs to have the base table names and ID of 1, updated paths etc. My only worry is that after switching these the network admin will have a problem -- so I basically need to compare the base tables (wp\_options etc) to the equivalent (wp\_x\_options etc) to see if there is anything unique related to the network admin in those base tables. | ~~Four years old and no answer? So here we go…-~~
Let's take the following network setup as example (I'm using WP-CLI's [site list command](http://wp-cli.org/commands/site/list/)):
```
$ wp site list
+---------+--------------------+---------------------+---------------------+
| blog_id | url | last_updated | registered |
+---------+--------------------+---------------------+---------------------+
| 1 | http://wp.tmp/ | 2016-08-04 08:39:35 | 2016-07-22 09:25:42 |
| 2 | http://foo.wp.tmp/ | 2016-07-22 09:28:16 | 2016-07-22 09:28:16 |
+---------+--------------------+---------------------+---------------------+
```
The network site list would look like this:
[](https://i.stack.imgur.com/7JKuQ.png)
We want to use the site with ID `2` as the new root site with the URL `http://wp.tmp/`. This is actually the same problem as described in the question just with some other values for the ID and the URLs.
The multisite relevant part of the `wp-config.php` looks probably like this:
```
const MULTISITE = TRUE;
const DOMAIN_CURRENT_SITE = 'wp.tmp';
const PATH_CURRENT_SITE = '/';
const SITE_ID_CURRENT_SITE = 1;
const BLOG_ID_CURRENT_SITE = 1;
const SUBDOMAIN_INSTALL = TRUE;
```
Updating database site settings
-------------------------------
WordPress uses the tables `wp_*_option` and `wp_blogs` to find the matching blog for a given request URL and to build proper permalinks for this blog. So we have to change the values in the following three tables (for this example):
* In `wp_options` the keys `home` and `siteurl`
* In `wp_2_options` the keys `home` and `siteurl` (in your case this would be `wp_15_options`)
* In `wp_blogs` the column `domain` for both sites with ID `1` and `2` (respectively `15`)
I'm using Adminer for this, but any other DB management tool (PhpMyAdmin) does the job as well. (The screenshots shows the GUI in German language but I guess the idea is clear.)
[](https://i.stack.imgur.com/169Pa.png)
In `wp_options` (the options table for site ID `1`) I changed the values of both keys `home` and `siteurl` from `http://wp.tmp` to `http://foo.wp.tmp`. (The screenshot above shows the state before the update.)
I did exactly the same with the table `wp_2_options` but here I changed the value from `http://foo.wp.tmp` to `http://wp.tmp`.
Next step is to update the table `wp_blogs`:
[](https://i.stack.imgur.com/3I5AJ.png)
(Again, the screenshot shows the table before I made any change.) Here you simply switch the values from both sites in the `domain` column:
* `wp.tmp` becomes `foo.wp.tmp` and
* `foo.wp.tmp` becomes `wp.tmp`
Now you have to update the `wp-config.php` to deal correctly with the new settings data:
```
const MULTISITE = TRUE;
const DOMAIN_CURRENT_SITE = 'wp.tmp';
const PATH_CURRENT_SITE = '/';
const SITE_ID_CURRENT_SITE = 1;
const BLOG_ID_CURRENT_SITE = 2; // This is the new root site ID
const SUBDOMAIN_INSTALL = TRUE;
```
At this point you have again a working WordPress multisite but with a new root site:
```
$ wp site list
+---------+--------------------+---------------------+---------------------+
| blog_id | url | last_updated | registered |
+---------+--------------------+---------------------+---------------------+
| 1 | http://foo.wp.tmp/ | 2016-08-04 08:39:35 | 2016-07-22 09:25:42 |
| 2 | http://wp.tmp/ | 2016-07-22 09:28:16 | 2016-07-22 09:28:16 |
+---------+--------------------+---------------------+---------------------+
```
[](https://i.stack.imgur.com/f9VwJ.png)
Remember: during this process, your site will be not available and requests will end up in some nasty errors so you might want to arrange a `503 Service Unavailable` response in front of your WordPress installation. This could be done [using `.htaccess`](http://www.electrictoolbox.com/503-header-apache-htaccess/).
Updating database content
-------------------------
Now comes the tricky part. At the moment, all URLs in the *content tables* are still pointing to the resources of the old sites. But replacing them is not that easy: Replacing every `http://foo.wp.tmp` with `http://wp.tmp` in the first step and every `http://wp.tmp` with `http://foo.wp.tmp` in the next step will end up in having all former URLs pointing to site ID 1 (`http://foo.wp.tmp`).
The best way would be to insert an intermediate step:
* Search for `http://foo.wp.tmp` and replace it with a preferably unique slug: `http://3a4b522a.wp.tmp`
* Search for `http://wp.tmp` and replace it with `http://foo.wp.tmp`
* Search for `http://3a4b522a.wp.tmp` and replace it with `http://wp.tmp`
All these search and replace commands should ignore the three tables (`*_options` `*_blogs`) we updated before, otherwise they would break the configuration. You might also have a manual look for URLs in `wp_*_options` table outside of the `home` and `siteurl` keys.
I would suggest to use WP-CLI's [search-replace command](http://wp-cli.org/) for this as it can deal with serialized data and has no limitations that HTTP might have. |
232,051 | <p>Many users do not compress or resize their images before uploading them into a post, so source images can often be a lot larger than the settings in /wp-admin/options-media.php.</p>
<p>Many theme and plugin authors do not respect the default settings in /wp-admin/options-media.php and often do not create custom sizes for things like gallery sliders.</p>
<p>The result is huge-ass images on pages and a slower internet.</p>
<p>WordPress provides 3 default image sizes and allows theme authors to create custom sizes as needed. </p>
<p>Does anyone know how to force WordPress, themes and plugins into using defined sizes in /wp-admin/options-media.php and/ or custom sizes created with add_image_size?</p>
<p>I've seen a few posts on here about deleting original source files, but it seems to me that leaving the original images on the server is nice a reference and fallback for re-cutting with <a href="https://wordpress.org/plugins/regenerate-thumbnails/" rel="nofollow">Regenerate Thumbnails</a> later if you need to change themes at a later date.</p>
| [
{
"answer_id": 235578,
"author": "David",
"author_id": 31323,
"author_profile": "https://wordpress.stackexchange.com/users/31323",
"pm_score": 4,
"selected": false,
"text": "<p><del>Four years old and no answer? So here we go…-</del></p>\n\n<p>Let's take the following network setup as ex... | 2016/07/12 | [
"https://wordpress.stackexchange.com/questions/232051",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/1341/"
] | Many users do not compress or resize their images before uploading them into a post, so source images can often be a lot larger than the settings in /wp-admin/options-media.php.
Many theme and plugin authors do not respect the default settings in /wp-admin/options-media.php and often do not create custom sizes for things like gallery sliders.
The result is huge-ass images on pages and a slower internet.
WordPress provides 3 default image sizes and allows theme authors to create custom sizes as needed.
Does anyone know how to force WordPress, themes and plugins into using defined sizes in /wp-admin/options-media.php and/ or custom sizes created with add\_image\_size?
I've seen a few posts on here about deleting original source files, but it seems to me that leaving the original images on the server is nice a reference and fallback for re-cutting with [Regenerate Thumbnails](https://wordpress.org/plugins/regenerate-thumbnails/) later if you need to change themes at a later date. | ~~Four years old and no answer? So here we go…-~~
Let's take the following network setup as example (I'm using WP-CLI's [site list command](http://wp-cli.org/commands/site/list/)):
```
$ wp site list
+---------+--------------------+---------------------+---------------------+
| blog_id | url | last_updated | registered |
+---------+--------------------+---------------------+---------------------+
| 1 | http://wp.tmp/ | 2016-08-04 08:39:35 | 2016-07-22 09:25:42 |
| 2 | http://foo.wp.tmp/ | 2016-07-22 09:28:16 | 2016-07-22 09:28:16 |
+---------+--------------------+---------------------+---------------------+
```
The network site list would look like this:
[](https://i.stack.imgur.com/7JKuQ.png)
We want to use the site with ID `2` as the new root site with the URL `http://wp.tmp/`. This is actually the same problem as described in the question just with some other values for the ID and the URLs.
The multisite relevant part of the `wp-config.php` looks probably like this:
```
const MULTISITE = TRUE;
const DOMAIN_CURRENT_SITE = 'wp.tmp';
const PATH_CURRENT_SITE = '/';
const SITE_ID_CURRENT_SITE = 1;
const BLOG_ID_CURRENT_SITE = 1;
const SUBDOMAIN_INSTALL = TRUE;
```
Updating database site settings
-------------------------------
WordPress uses the tables `wp_*_option` and `wp_blogs` to find the matching blog for a given request URL and to build proper permalinks for this blog. So we have to change the values in the following three tables (for this example):
* In `wp_options` the keys `home` and `siteurl`
* In `wp_2_options` the keys `home` and `siteurl` (in your case this would be `wp_15_options`)
* In `wp_blogs` the column `domain` for both sites with ID `1` and `2` (respectively `15`)
I'm using Adminer for this, but any other DB management tool (PhpMyAdmin) does the job as well. (The screenshots shows the GUI in German language but I guess the idea is clear.)
[](https://i.stack.imgur.com/169Pa.png)
In `wp_options` (the options table for site ID `1`) I changed the values of both keys `home` and `siteurl` from `http://wp.tmp` to `http://foo.wp.tmp`. (The screenshot above shows the state before the update.)
I did exactly the same with the table `wp_2_options` but here I changed the value from `http://foo.wp.tmp` to `http://wp.tmp`.
Next step is to update the table `wp_blogs`:
[](https://i.stack.imgur.com/3I5AJ.png)
(Again, the screenshot shows the table before I made any change.) Here you simply switch the values from both sites in the `domain` column:
* `wp.tmp` becomes `foo.wp.tmp` and
* `foo.wp.tmp` becomes `wp.tmp`
Now you have to update the `wp-config.php` to deal correctly with the new settings data:
```
const MULTISITE = TRUE;
const DOMAIN_CURRENT_SITE = 'wp.tmp';
const PATH_CURRENT_SITE = '/';
const SITE_ID_CURRENT_SITE = 1;
const BLOG_ID_CURRENT_SITE = 2; // This is the new root site ID
const SUBDOMAIN_INSTALL = TRUE;
```
At this point you have again a working WordPress multisite but with a new root site:
```
$ wp site list
+---------+--------------------+---------------------+---------------------+
| blog_id | url | last_updated | registered |
+---------+--------------------+---------------------+---------------------+
| 1 | http://foo.wp.tmp/ | 2016-08-04 08:39:35 | 2016-07-22 09:25:42 |
| 2 | http://wp.tmp/ | 2016-07-22 09:28:16 | 2016-07-22 09:28:16 |
+---------+--------------------+---------------------+---------------------+
```
[](https://i.stack.imgur.com/f9VwJ.png)
Remember: during this process, your site will be not available and requests will end up in some nasty errors so you might want to arrange a `503 Service Unavailable` response in front of your WordPress installation. This could be done [using `.htaccess`](http://www.electrictoolbox.com/503-header-apache-htaccess/).
Updating database content
-------------------------
Now comes the tricky part. At the moment, all URLs in the *content tables* are still pointing to the resources of the old sites. But replacing them is not that easy: Replacing every `http://foo.wp.tmp` with `http://wp.tmp` in the first step and every `http://wp.tmp` with `http://foo.wp.tmp` in the next step will end up in having all former URLs pointing to site ID 1 (`http://foo.wp.tmp`).
The best way would be to insert an intermediate step:
* Search for `http://foo.wp.tmp` and replace it with a preferably unique slug: `http://3a4b522a.wp.tmp`
* Search for `http://wp.tmp` and replace it with `http://foo.wp.tmp`
* Search for `http://3a4b522a.wp.tmp` and replace it with `http://wp.tmp`
All these search and replace commands should ignore the three tables (`*_options` `*_blogs`) we updated before, otherwise they would break the configuration. You might also have a manual look for URLs in `wp_*_options` table outside of the `home` and `siteurl` keys.
I would suggest to use WP-CLI's [search-replace command](http://wp-cli.org/) for this as it can deal with serialized data and has no limitations that HTTP might have. |
232,055 | <p>I want to get the list of all available hooks from active theme / from a specific plugin.</p>
<p>I was tried to get it from global variables <code>$wp_actions & $wp_filter</code> But, They are showing all registered hooks.</p>
<p>E.g.</p>
<pre><code>global $wp_actions, $wp_filter;
echo '<pre>';
print_r($wp_filter);
</code></pre>
<p>E.g. If theme or plugin register the action in <code>after_setup_theme</code> then it'll list in <code>[after_setup_theme]</code> key from <code>global $wp_filter</code>.</p>
<p>I was tried one of the best plugin <code>Simply Show Hooks</code>. But, It'll also, show all the registered hooks.</p>
<p>Is there any way to get the specific hooks from theme / plugin?</p>
| [
{
"answer_id": 240532,
"author": "tivnet",
"author_id": 28961,
"author_profile": "https://wordpress.stackexchange.com/users/28961",
"pm_score": 3,
"selected": true,
"text": "<p>As of 2016-09-25, there is no ideal solution.</p>\n\n<p>The WP-Parser does the job, but you need to set up a sp... | 2016/07/12 | [
"https://wordpress.stackexchange.com/questions/232055",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/52167/"
] | I want to get the list of all available hooks from active theme / from a specific plugin.
I was tried to get it from global variables `$wp_actions & $wp_filter` But, They are showing all registered hooks.
E.g.
```
global $wp_actions, $wp_filter;
echo '<pre>';
print_r($wp_filter);
```
E.g. If theme or plugin register the action in `after_setup_theme` then it'll list in `[after_setup_theme]` key from `global $wp_filter`.
I was tried one of the best plugin `Simply Show Hooks`. But, It'll also, show all the registered hooks.
Is there any way to get the specific hooks from theme / plugin? | As of 2016-09-25, there is no ideal solution.
The WP-Parser does the job, but you need to set up a special WP site to run it.
WooCommerce's `Hook-docs` is something much simpler, and can be easily tweaked.
I just wrote a long comment on the topic here:
<https://github.com/ApiGen/ApiGen/issues/307#issuecomment-249349187> |
232,056 | <p>In the attached image, the posts are displayed in a slider style. When I click on post in the slider, suppose CArd5, then the details should of that post eg: the thumbnail, excerpt etc should be displayed in the pop-up, the pop-up html code has been included in the end as " "</p>
<pre><code>Function addcards()
{
$the_query = new WP_Query( array( 'post_type' => 'cards', 'post_status' => 'publish' ));
?>
<body>
<div id="demo">
<div class="container">
<div class="row">
<div class="row">
<div class="span12">
<div id="owl-demo" class="owl-carousel">
<?php
while ($the_query->have_posts())
{
$the_query->the_post();
?>
<div class="item orange">
<!-- <a href = "#modal"> -->
<!-- href = "#modal" -->
<form action="" method = "post">
<a href = "#modal" id="<?php echo get_the_title();?>" onClick="reply_click(this.id)"
class="lbp-inline-link-1 cboxElement" style="text-decoration:none">
<!-- <div style="display: none;">
<div id="lbp-inline-href-1" style="padding:10px; background: #fff;">
<p>This content will be in a popup.</p>
</div>
</div> -->
<div class="squarebox">
<div class="innersquare">
<div>
<table>
<tr>
<td align="left"><p><?php echo get_the_author();?></p></td>
<td align="left"><p><?php echo get_the_date();?></p></td>
</tr>
</table>
</div>
<div>
<h3><?php echo get_the_title();?></h3>
</div>
<div>
<img src="<?php echo the_post_thumbnail_url();?>">
</div>
<div>
<p><?php the_excerpt(); ?></p>
</div>
<div class="fb-share-button" data-href="https://www.facebook.com/Techmatters-125167747841183/" data-layout="button" data-mobile-iframe="true"><a class="fb-xfbml-parse-ignore" target="_blank" href="https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Fwww.facebook.com%2FTechmatters-125167747841183%2F&amp;src=sdkpreparse">Share</a></div>
<script src="//platform.linkedin.com/in.js" type="text/javascript"> lang: en_US</script>
<script type="IN/Share" data-url="https://www.facebook.com/Techmatters-125167747841183/"></script>
</div>
</div>
</a>
</form>
<?php $postid = get_the_title(); ?>
</div>
<?php
}
?>
</div>
</div>
</div>
</div>
</div>
</div>
<script type="text/javascript">
function reply_click(clicked_id)
{
var userID = clicked_id;
alert(userID);
}
</script>
<!-- popup html -->
<div class="remodal" data-remodal-id="modal" role="dialog" aria-labelledby="modal1Title" aria-describedby="modal1Desc">
<button data-remodal-action="close" class="remodal-close" aria-label="Close"></button>
<div>
<h2 id="modal1Title" class="results">
</h2>
<p id="modal1Desc">
Responsive, lightweight, fast, synchronized with CSS animations, fully customizable modal window plugin
with declarative state notation and hash tracking.
</p>
</div>
<br>
<button data-remodal-action="cancel" class="remodal-cancel">Cancel</button>
<button data-remodal-action="confirm" class="remodal-confirm">OK</button>
</div>
<?php
}
add_shortcode('cards','addcards');
?>
</code></pre>
<p><a href="https://i.stack.imgur.com/jkPjp.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/jkPjp.png" alt="enter image description here"></a></p>
| [
{
"answer_id": 232065,
"author": "Neeraj Kumar",
"author_id": 98147,
"author_profile": "https://wordpress.stackexchange.com/users/98147",
"pm_score": -1,
"selected": false,
"text": "<p>there are many ways to this but i suggest ajax for it. When you click on any post get the post_id and p... | 2016/07/12 | [
"https://wordpress.stackexchange.com/questions/232056",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/97552/"
] | In the attached image, the posts are displayed in a slider style. When I click on post in the slider, suppose CArd5, then the details should of that post eg: the thumbnail, excerpt etc should be displayed in the pop-up, the pop-up html code has been included in the end as " "
```
Function addcards()
{
$the_query = new WP_Query( array( 'post_type' => 'cards', 'post_status' => 'publish' ));
?>
<body>
<div id="demo">
<div class="container">
<div class="row">
<div class="row">
<div class="span12">
<div id="owl-demo" class="owl-carousel">
<?php
while ($the_query->have_posts())
{
$the_query->the_post();
?>
<div class="item orange">
<!-- <a href = "#modal"> -->
<!-- href = "#modal" -->
<form action="" method = "post">
<a href = "#modal" id="<?php echo get_the_title();?>" onClick="reply_click(this.id)"
class="lbp-inline-link-1 cboxElement" style="text-decoration:none">
<!-- <div style="display: none;">
<div id="lbp-inline-href-1" style="padding:10px; background: #fff;">
<p>This content will be in a popup.</p>
</div>
</div> -->
<div class="squarebox">
<div class="innersquare">
<div>
<table>
<tr>
<td align="left"><p><?php echo get_the_author();?></p></td>
<td align="left"><p><?php echo get_the_date();?></p></td>
</tr>
</table>
</div>
<div>
<h3><?php echo get_the_title();?></h3>
</div>
<div>
<img src="<?php echo the_post_thumbnail_url();?>">
</div>
<div>
<p><?php the_excerpt(); ?></p>
</div>
<div class="fb-share-button" data-href="https://www.facebook.com/Techmatters-125167747841183/" data-layout="button" data-mobile-iframe="true"><a class="fb-xfbml-parse-ignore" target="_blank" href="https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Fwww.facebook.com%2FTechmatters-125167747841183%2F&src=sdkpreparse">Share</a></div>
<script src="//platform.linkedin.com/in.js" type="text/javascript"> lang: en_US</script>
<script type="IN/Share" data-url="https://www.facebook.com/Techmatters-125167747841183/"></script>
</div>
</div>
</a>
</form>
<?php $postid = get_the_title(); ?>
</div>
<?php
}
?>
</div>
</div>
</div>
</div>
</div>
</div>
<script type="text/javascript">
function reply_click(clicked_id)
{
var userID = clicked_id;
alert(userID);
}
</script>
<!-- popup html -->
<div class="remodal" data-remodal-id="modal" role="dialog" aria-labelledby="modal1Title" aria-describedby="modal1Desc">
<button data-remodal-action="close" class="remodal-close" aria-label="Close"></button>
<div>
<h2 id="modal1Title" class="results">
</h2>
<p id="modal1Desc">
Responsive, lightweight, fast, synchronized with CSS animations, fully customizable modal window plugin
with declarative state notation and hash tracking.
</p>
</div>
<br>
<button data-remodal-action="cancel" class="remodal-cancel">Cancel</button>
<button data-remodal-action="confirm" class="remodal-confirm">OK</button>
</div>
<?php
}
add_shortcode('cards','addcards');
?>
```
[](https://i.stack.imgur.com/jkPjp.png) | I am giving you an idea for this, you have to use jQuery for the popup and the below syntax will give you the current post data in a HTML popup.
```
while ($the_query->have_posts()): $the_query->the_post();
echo '<div class="non-popup">';
echo '<div class="card-title" id="card-'.get_the_title.'">'.get_the_title().'</div>';
write you front end code + html (http://screenshotlink.ru/eff3d7431f4fbcd6a03ca5fcbbc41cdd.png)
echo '</div>';
echo '<div class="popup" style="display:none;">';
echo '<div class="popup-title">'.get_the_title().'</div>';
write your popup html + code
echo '</div>';
endwhile;
```
Here is the jQuery:
```
$(document).ready(function(){
$(".card-title").on('click',function(){
$(this).siblings().css('display','block');
});
});
``` |
232,080 | <p>We have user profile page in frontend. We need to add functionality to user add their profile image from profile page in frontend. </p>
<p>Is any plugin or custom functions available for that ? </p>
| [
{
"answer_id": 232065,
"author": "Neeraj Kumar",
"author_id": 98147,
"author_profile": "https://wordpress.stackexchange.com/users/98147",
"pm_score": -1,
"selected": false,
"text": "<p>there are many ways to this but i suggest ajax for it. When you click on any post get the post_id and p... | 2016/07/12 | [
"https://wordpress.stackexchange.com/questions/232080",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/98209/"
] | We have user profile page in frontend. We need to add functionality to user add their profile image from profile page in frontend.
Is any plugin or custom functions available for that ? | I am giving you an idea for this, you have to use jQuery for the popup and the below syntax will give you the current post data in a HTML popup.
```
while ($the_query->have_posts()): $the_query->the_post();
echo '<div class="non-popup">';
echo '<div class="card-title" id="card-'.get_the_title.'">'.get_the_title().'</div>';
write you front end code + html (http://screenshotlink.ru/eff3d7431f4fbcd6a03ca5fcbbc41cdd.png)
echo '</div>';
echo '<div class="popup" style="display:none;">';
echo '<div class="popup-title">'.get_the_title().'</div>';
write your popup html + code
echo '</div>';
endwhile;
```
Here is the jQuery:
```
$(document).ready(function(){
$(".card-title").on('click',function(){
$(this).siblings().css('display','block');
});
});
``` |
232,091 | <p>I recently started wp development and am trying to make a website on the Wonderflux framework. </p>
<p>Currently, I set the homepage as a static page from the WP admin dashboard. Now I am currently editing said page inside wp.</p>
<p><a href="https://i.stack.imgur.com/O9yza.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/O9yza.png" alt="wp edit"></a></p>
<p>Is this the correct way to do this? Is there a way to simply redirect to <code>custom-home.php</code> on page load? Where that file would load the header, page content and the footer. </p>
<p>I am going to be having multiple pages with each their own looks so I think this should be accomplished using functions.php in my child theme but I'm not sure where to start. I just want WP to mainly handle pages with posts/blog content.</p>
<p>I apologize if I sound a bit scattered, I don't think using a framework for my first WP project was a good idea. I'm used to bootstrap and was looking for a similar environment to build a responsive website. I feel like the only way I can properly learn everything is to build a theme from the ground up using the codex, but I don't have that much time unfortunately.</p>
<p>Any guidance would greatly be appreciated. </p>
| [
{
"answer_id": 232065,
"author": "Neeraj Kumar",
"author_id": 98147,
"author_profile": "https://wordpress.stackexchange.com/users/98147",
"pm_score": -1,
"selected": false,
"text": "<p>there are many ways to this but i suggest ajax for it. When you click on any post get the post_id and p... | 2016/07/12 | [
"https://wordpress.stackexchange.com/questions/232091",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/98213/"
] | I recently started wp development and am trying to make a website on the Wonderflux framework.
Currently, I set the homepage as a static page from the WP admin dashboard. Now I am currently editing said page inside wp.
[](https://i.stack.imgur.com/O9yza.png)
Is this the correct way to do this? Is there a way to simply redirect to `custom-home.php` on page load? Where that file would load the header, page content and the footer.
I am going to be having multiple pages with each their own looks so I think this should be accomplished using functions.php in my child theme but I'm not sure where to start. I just want WP to mainly handle pages with posts/blog content.
I apologize if I sound a bit scattered, I don't think using a framework for my first WP project was a good idea. I'm used to bootstrap and was looking for a similar environment to build a responsive website. I feel like the only way I can properly learn everything is to build a theme from the ground up using the codex, but I don't have that much time unfortunately.
Any guidance would greatly be appreciated. | I am giving you an idea for this, you have to use jQuery for the popup and the below syntax will give you the current post data in a HTML popup.
```
while ($the_query->have_posts()): $the_query->the_post();
echo '<div class="non-popup">';
echo '<div class="card-title" id="card-'.get_the_title.'">'.get_the_title().'</div>';
write you front end code + html (http://screenshotlink.ru/eff3d7431f4fbcd6a03ca5fcbbc41cdd.png)
echo '</div>';
echo '<div class="popup" style="display:none;">';
echo '<div class="popup-title">'.get_the_title().'</div>';
write your popup html + code
echo '</div>';
endwhile;
```
Here is the jQuery:
```
$(document).ready(function(){
$(".card-title").on('click',function(){
$(this).siblings().css('display','block');
});
});
``` |
232,104 | <p>so I am hoping to retrieve a custom field that is already displayed on the "front-page.php" template on an another page.php template of my website. I know how to do that with the post-id way, but what I'm hoping to do is get it so that it automatically retrieves them from the front page template... the reason why I want to do it that way is because it's a mult-site and I want to re-use the theme installed on sub sites.</p>
<p>So, instead of:</p>
<pre><code> <img src="<?php the_field('image1', 31); ?>" />
</code></pre>
<p>have it be something like:</p>
<pre><code> <img src="<?php the_field('image1', Front Page identifier here); ?>" />
</code></pre>
<p>Can someone please let me know if that's possible? I would really appreciate it!</p>
| [
{
"answer_id": 232105,
"author": "user319940",
"author_id": 24044,
"author_profile": "https://wordpress.stackexchange.com/users/24044",
"pm_score": 1,
"selected": false,
"text": "<pre><code>$val = get_post_meta( get_the_ID(), 'meta_data_name', true );\necho $val;\n</code></pre>\n\n<p>You... | 2016/07/12 | [
"https://wordpress.stackexchange.com/questions/232104",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/58060/"
] | so I am hoping to retrieve a custom field that is already displayed on the "front-page.php" template on an another page.php template of my website. I know how to do that with the post-id way, but what I'm hoping to do is get it so that it automatically retrieves them from the front page template... the reason why I want to do it that way is because it's a mult-site and I want to re-use the theme installed on sub sites.
So, instead of:
```
<img src="<?php the_field('image1', 31); ?>" />
```
have it be something like:
```
<img src="<?php the_field('image1', Front Page identifier here); ?>" />
```
Can someone please let me know if that's possible? I would really appreciate it! | ```
$val = get_post_meta( get_the_ID(), 'meta_data_name', true );
echo $val;
```
You can replace get\_the\_ID() with the ID of the post you are getting the meta from.
You could possible team this with:
```
$frontpage_id = get_option('page_on_front');
```
to get the homepage ID. Not sure if this would be friendly with multisite though.
`the_field()` is an Advanced Custom Fields function, this can take a second parameter. You can also achieve the same as the above:
```
<?php the_field($field_name, $post_id); ?>
```
replacing post ID with the ID of the post you are retrieving the data from. |
232,115 | <p>I am in the process of rewriting a lot of my code and restructuring a lot of my theme files to use template parts (i.e. using <code>get_template_part()</code>). I've come upon a situation where I want to use the same template parts whether I'm using the main query or a secondary custom query (using <code>WP_Query</code>). The template parts also use core functions that rely on the main query (such as conditionals).</p>
<p>I can get around the problem by overwriting the main query (or overwriting the <code>$wp_query</code> global which holds the main query, the main query still exists) with my custom query and resetting the main query once I'm done. This also means I can use the same loop for the main query and my custom queries. For example:</p>
<pre><code>// Query
if ( $i_need_a_custom_query ) {
$wp_query = new WP_Query($custom_query_args);
}
// The Loop
if ( have_posts() ) : while ( have_posts() ) : the_post();
// Do some loop stuff
// and call some functions that rely on the main query
// End the loop
endwhile; endif;
// I'm done so reset the query
wp_reset_query();
</code></pre>
<p>This works. No problem at all, but it seems a bit of a hack to me. So my question is:</p>
<ul>
<li>Am I right to be weary of overwriting the main query like this?</li>
<li>Are there any side effects I'm missing?</li>
<li>And am I correct in assuming that calling <code>wp_reset_query()</code> isn't costly (i.e. it isn't actually re-running the query but simply resetting the globals which are still around somewhere)?</li>
</ul>
<p>Edit to clarify:</p>
<p>I am only using the custom queries in question as secondary queries, that's the whole point of the question. I want to use the same template wether I am using a custom <em>secondary</em> query or using the main query. I understand that what I am doing is essentially the same as using <code>query_posts()</code>, which is a bad idea. As far as I'm aware and broadly speaking, the 2 drawbacks to using <code>query_posts()</code> are 1. Performance, which isn't an issue because I am only doing this when running a secondary custom query anyway and 2. Unintended consequences from changing the global $wp_query, which is exactly what I <em>do</em> want to happen (and as I said is actually working perfectly).</p>
| [
{
"answer_id": 232117,
"author": "Howdy_McGee",
"author_id": 7355,
"author_profile": "https://wordpress.stackexchange.com/users/7355",
"pm_score": 1,
"selected": false,
"text": "<p>I feel like you should be using <code>get_template_part()</code> for markup. Let's say you have a Custom Te... | 2016/07/12 | [
"https://wordpress.stackexchange.com/questions/232115",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/81652/"
] | I am in the process of rewriting a lot of my code and restructuring a lot of my theme files to use template parts (i.e. using `get_template_part()`). I've come upon a situation where I want to use the same template parts whether I'm using the main query or a secondary custom query (using `WP_Query`). The template parts also use core functions that rely on the main query (such as conditionals).
I can get around the problem by overwriting the main query (or overwriting the `$wp_query` global which holds the main query, the main query still exists) with my custom query and resetting the main query once I'm done. This also means I can use the same loop for the main query and my custom queries. For example:
```
// Query
if ( $i_need_a_custom_query ) {
$wp_query = new WP_Query($custom_query_args);
}
// The Loop
if ( have_posts() ) : while ( have_posts() ) : the_post();
// Do some loop stuff
// and call some functions that rely on the main query
// End the loop
endwhile; endif;
// I'm done so reset the query
wp_reset_query();
```
This works. No problem at all, but it seems a bit of a hack to me. So my question is:
* Am I right to be weary of overwriting the main query like this?
* Are there any side effects I'm missing?
* And am I correct in assuming that calling `wp_reset_query()` isn't costly (i.e. it isn't actually re-running the query but simply resetting the globals which are still around somewhere)?
Edit to clarify:
I am only using the custom queries in question as secondary queries, that's the whole point of the question. I want to use the same template wether I am using a custom *secondary* query or using the main query. I understand that what I am doing is essentially the same as using `query_posts()`, which is a bad idea. As far as I'm aware and broadly speaking, the 2 drawbacks to using `query_posts()` are 1. Performance, which isn't an issue because I am only doing this when running a secondary custom query anyway and 2. Unintended consequences from changing the global $wp\_query, which is exactly what I *do* want to happen (and as I said is actually working perfectly). | In general, I agree with Howdy\_McGee that one should avoid overwriting the main query unless absolutely necessary - more often than not, modifying the main query with something like a `'pre_get_posts'` hook is a better solution to such scenarios.
Manually overwriting the global `$wp_query` can cause all sorts of unintended behaviors if you are not exceedingly careful, including breaking pagination, among other things. It is, in essence, an even more simplistic equivalent to the often criticized `query_posts()` function, which [the WordPress Code Reference notes](https://developer.wordpress.org/reference/functions/query_posts/):
>
> This function will completely override the main query and isn’t intended for use by plugins or themes. Its overly-simplistic approach to modifying the main query can be problematic and should be avoided wherever possible. In most cases, there are better, more performant options for modifying the main query such as via the ‘pre\_get\_posts’ action within WP\_Query.
>
>
>
In this instance however, where you require either:
* Simultaneous access to both the main query as well as a secondary query for their distinct content and/or [conditional tags](https://codex.wordpress.org/Conditional_Tags)
* A generic implementation in something like a reusable template part that can be applied to either the main query or any custom query
then one solution is to store the "contextual" `WP_Query` instance in a local variable, and invoke `WP_Query`'s conditional methods on that variable instead of using their globally-available conditional tag function counterparts (which always explicitly reference the main query, `global $wp_query`).
For instance, if you wanted your "contextual query variable" to refer to a custom secondary query in single and archive templates for your custom post type, `my-custom-post-type`, but refer to the main query in every other case, you could do the following:
**Theme's `functions.php` file, or a plugin file:**
```
function wpse_232115_get_contextual_query() {
global $wp_query;
static $contextual_query;
// A convenient means to check numerous conditionals without a bunch of '||' operations,
// i.e "if( $i_need_a_custom_query )"
if( in_array( true,
[
is_singular( 'my-custom-post-type' ),
is_post_type_archive( 'my-custom-post-type' )
]
) ) {
// Create the contextual query instance, if it doesn't yet exist
if( ! isset( $contextual_query ) ) {
$query_args = [
//...
];
$contextual_query = new WP_Query( $query_args );
}
return $contextual_query;
}
return $wp_query;
}
```
**"Generic" template-part files:**
```
$query = wpse_232115_get_contextual_query();
// Contextual Query loop (loops through your custom query when 'my-custom-post-type's
// are being displayed, the main $wp_query otherwise.
if ( $query->have_posts() ) : while ( $query->have_posts() ) : $query->the_post();
// Tags dependent on The Loop will refer to the contextual query if The Loop
// was set up with the "$query->" prefix, as above. Without it, they always
// refer to the main query.
the_title();
// The global conditional tags always refer to the main query
if( is_singular() ) {
//... Do stuff is the main query result is_singular();
}
// Conditional methods on the $query object reference describe either
// the main query, or a custom query depending on the context.
if( $query->is_archive() ) {
//... Do stuff if the $query query result is an archive
}
// End the loop
endwhile; endif;
```
I'm not sure if this is the best solution, but it's how I would think to approach the problem. |
232,127 | <p>I have been trying to make a sign-out plugin that allows users to sign out from military training activities that they should be at. After they fill out a form explaining why they are not going to be at an activity, they submit it, and it puts all the data into a mysql database. I am trying to save the user's id to their other data so we can tell who is signing out, but everything I have tried breaks the plugin, and gives me the white screen of death.</p>
<p>Thanks for your help. Here is my code to get the users id:</p>
<pre><code>function f2user() {
// Get the current user's info
$current_user = wp_get_current_user();
if ( !($current_user instanceof WP_User) )
return;
return $current_user->ID;
}
$usersid = f2user();
$activity = $_POST['activity'];
$reason = $_POST['reason'];
$explanation = $_POST['explanation'];
</code></pre>
| [
{
"answer_id": 232128,
"author": "Ehsaan",
"author_id": 54782,
"author_profile": "https://wordpress.stackexchange.com/users/54782",
"pm_score": 0,
"selected": false,
"text": "<p>You can get current user ID easily using <code>get_current_user_id()</code>.</p>\n\n<pre><code>$usersid = get_... | 2016/07/13 | [
"https://wordpress.stackexchange.com/questions/232127",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/98239/"
] | I have been trying to make a sign-out plugin that allows users to sign out from military training activities that they should be at. After they fill out a form explaining why they are not going to be at an activity, they submit it, and it puts all the data into a mysql database. I am trying to save the user's id to their other data so we can tell who is signing out, but everything I have tried breaks the plugin, and gives me the white screen of death.
Thanks for your help. Here is my code to get the users id:
```
function f2user() {
// Get the current user's info
$current_user = wp_get_current_user();
if ( !($current_user instanceof WP_User) )
return;
return $current_user->ID;
}
$usersid = f2user();
$activity = $_POST['activity'];
$reason = $_POST['reason'];
$explanation = $_POST['explanation'];
``` | Try this.
If no user are signed in then wp\_get\_current\_user get fatal error so your plugin breaks. But if you want only user id then use get\_current\_user\_id.
If no user signed in then it will return 0. So your plugin will not break.
Thanks
```
function f2user() {
// Get the current user's info
$current_user = get_current_user_id();
return $current_user;
}
$usersid = f2user();
``` |
232,135 | <p>I am new to word press but know all the required PHP skills.
I am using a form to create session in one page and then accessing those sessions in another page. I have done this already without word press. What i need is someone tells me how to do this in word press. what files i have to change in word press, which code i should enter in which file ?</p>
<p><strong>The main part is i am using google-map-api to calculate the distance between two locations</strong></p>
<p>here is my code so far:<br>
<strong>22.php file :</strong> </p>
<pre><code><?php
session_start();
$pickup = '';
$pickupadd = '';
$dropoff = '';
$dropoffadd = '';
$km = '';
$_SESSION['pickup'] = $pickup;
$_SESSION['pickupadd'] = $pickupadd;
$_SESSION['dropoff'] = $dropoff;
$_SESSION['dropoffadd'] = $dropoffadd;
$_SESSION['km'] = $km;
?>
<form class="uk-form" action="1111.php" method="get"><label style="color:
#0095da;"> Pick UP</label>
<input id="pickup" name="pickup" class="controls" style="width: 100%;
border-bottom: 1px solid #0095da; border-left: 1px solid #0095da; height:
30px;" type="text" placeholder="Enter a Pick UP location" />
<input id="pickup_address" name="pickupadd" class="controls" style="width:
100%; border-bottom: 1px solid #0095da; border-left: 1px solid #0095da;
height: 30px; margin-top: 10px;" type="text" placeholder="House#, Street,
etc." /><label style="color: #0095da;"> Drop OFF</label>
<input id="dropoff" name="dropoff" class="controls" style="width: 100%;
border-bottom: 1px solid #0095da; border-left: 1px solid #0095da; height:
30px;" type="text" placeholder="Enter a Drop OFF location" />
<input id="dropoff_address" name="dropoffadd" class="controls" style="width:
100%; border-bottom: 1px solid #0095da; border-left: 1px solid #0095da;
height: 30px; margin-top: 10px;" type="text" placeholder="House#, Street,
etc." /><label style="color: #0095da;"> Pickup Time</label>
<input id="km" name="km" class="controls" type="hidden" value="" />
<input type="submit" />
</form>
</code></pre>
<p><strong>1111.php file :</strong> </p>
<pre><code> <?php
session_start();
$pickup = $_SESSION['pickup'] ;
$pickupadd = $_SESSION['pickupadd'] ;
$dropoff = $_SESSION['dropoff'] ;
$dropoffadd = $_SESSION['dropoffadd'] ;
$km = $_SESSION['km'] ;
if (isset($_GET["pickup"]) || isset($_GET["pickupadd"]) ||
isset($_GET["dropoff"]) || isset($_GET["dropoffadd"]) || isset($_GET["km"])
) {
$_SESSION["pickup"] = $_GET["pickup"];
$_SESSION["pickupadd"] = $_GET["pickupadd"];
$_SESSION["dropoff"] = $_GET["dropoff"];
$_SESSION["dropoffadd"] = $_GET["dropoffadd"];
$_SESSION["km"] = $_GET["km"];
}
?>
<body>
<?php
echo $_SESSION["pickup"];
echo $_SESSION["pickupadd"];
echo $_SESSION["dropoff"];
echo $_SESSION["dropoffadd"];
echo $_SESSION["km"];
?>
</body>
</code></pre>
| [
{
"answer_id": 232137,
"author": "TomC",
"author_id": 36980,
"author_profile": "https://wordpress.stackexchange.com/users/36980",
"pm_score": 1,
"selected": false,
"text": "<p>You want to use the init hook to start the session such as:</p>\n\n<pre><code>function start_session() {\n if... | 2016/07/13 | [
"https://wordpress.stackexchange.com/questions/232135",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/98132/"
] | I am new to word press but know all the required PHP skills.
I am using a form to create session in one page and then accessing those sessions in another page. I have done this already without word press. What i need is someone tells me how to do this in word press. what files i have to change in word press, which code i should enter in which file ?
**The main part is i am using google-map-api to calculate the distance between two locations**
here is my code so far:
**22.php file :**
```
<?php
session_start();
$pickup = '';
$pickupadd = '';
$dropoff = '';
$dropoffadd = '';
$km = '';
$_SESSION['pickup'] = $pickup;
$_SESSION['pickupadd'] = $pickupadd;
$_SESSION['dropoff'] = $dropoff;
$_SESSION['dropoffadd'] = $dropoffadd;
$_SESSION['km'] = $km;
?>
<form class="uk-form" action="1111.php" method="get"><label style="color:
#0095da;"> Pick UP</label>
<input id="pickup" name="pickup" class="controls" style="width: 100%;
border-bottom: 1px solid #0095da; border-left: 1px solid #0095da; height:
30px;" type="text" placeholder="Enter a Pick UP location" />
<input id="pickup_address" name="pickupadd" class="controls" style="width:
100%; border-bottom: 1px solid #0095da; border-left: 1px solid #0095da;
height: 30px; margin-top: 10px;" type="text" placeholder="House#, Street,
etc." /><label style="color: #0095da;"> Drop OFF</label>
<input id="dropoff" name="dropoff" class="controls" style="width: 100%;
border-bottom: 1px solid #0095da; border-left: 1px solid #0095da; height:
30px;" type="text" placeholder="Enter a Drop OFF location" />
<input id="dropoff_address" name="dropoffadd" class="controls" style="width:
100%; border-bottom: 1px solid #0095da; border-left: 1px solid #0095da;
height: 30px; margin-top: 10px;" type="text" placeholder="House#, Street,
etc." /><label style="color: #0095da;"> Pickup Time</label>
<input id="km" name="km" class="controls" type="hidden" value="" />
<input type="submit" />
</form>
```
**1111.php file :**
```
<?php
session_start();
$pickup = $_SESSION['pickup'] ;
$pickupadd = $_SESSION['pickupadd'] ;
$dropoff = $_SESSION['dropoff'] ;
$dropoffadd = $_SESSION['dropoffadd'] ;
$km = $_SESSION['km'] ;
if (isset($_GET["pickup"]) || isset($_GET["pickupadd"]) ||
isset($_GET["dropoff"]) || isset($_GET["dropoffadd"]) || isset($_GET["km"])
) {
$_SESSION["pickup"] = $_GET["pickup"];
$_SESSION["pickupadd"] = $_GET["pickupadd"];
$_SESSION["dropoff"] = $_GET["dropoff"];
$_SESSION["dropoffadd"] = $_GET["dropoffadd"];
$_SESSION["km"] = $_GET["km"];
}
?>
<body>
<?php
echo $_SESSION["pickup"];
echo $_SESSION["pickupadd"];
echo $_SESSION["dropoff"];
echo $_SESSION["dropoffadd"];
echo $_SESSION["km"];
?>
</body>
``` | TomC is right, but to build on that here's what I do. Mainly I use this with a global object which I serialise into the session to save and unserialise from the session to use. Here I've just used an array of your variables. This way you don't need to worry about saving into the session as you go and the session use is easily expanded for other data.
My main use is for shopping baskets and orders, so **proper sanitisation, validation and nonces are important**, but they are left out here to keep the examples clean. See <https://developer.wordpress.org/plugins/security/nonces/> and <https://codex.wordpress.org/Validating_Sanitizing_and_Escaping_User_Data>
Assuming this is all going into your theme, you have init code similar to TomC's in `functions.php`
```
add_action( 'init', 'setup_session' );
function setup_session() {
session_start();
global $map_data;
if (isset($_SESSION['map_data'])) {
$map_data = unserialize($_SESSION['map_data']);
} else {
$map_data = array();
}
process_get();
/* chain it after session setup, but could also hook into
init with a lower priority so that $_GET always writes
over older session data, or put your own action here to
give multiple functions access to your sessions
*/
}
add_action( 'shutdown', 'save_session' );
function save_session() {
global $map_data;
if (isset($map_data)) {
$_SESSION['map_data'] = serialize($map_data);
}
}
function process_get() {
// do modify this to:
// check nonce
// sanitise
// validate
` global $map_data;
if ( isset($_GET["pickup"]) || isset($_GET["pickupadd"]) || isset($_GET["dropoff"]) || isset($_GET["dropoffadd"]) || isset($_GET["km"])
) {
$map_data["pickup"] = $_GET["pickup"];
$map_data["pickupadd"] = $_GET["pickupadd"];
$map_data["dropoff"] = $_GET["dropoff"];
$map_data["dropoffadd"] = $_GET["dropoffadd"];
$map_data["km"] = $_GET["km"];
}
// if any of these $_GET vars is set, replace the whole array
}
```
You're also right that this could go into your template files as long as you start your session before PHP sends out the headers. In a well written theme (and assuming you aren't running any poorly written plugins) anywhere before your HTML tag will work. Hooking into WP actions is a bit more robust in this regard, but putting the $\_GET processing into a template would let you easily keep it to one page instead of running it on all of them.
You can go a step further, though this may be more effort than you need in your case, and use custom session code: <https://pippinsplugins.com/storing-session-data-in-wordpress-without-_session/> |
232,152 | <p>I have marked the option - " Users must be registered and logged in to comment " in Admin panel Setting -> Discussion section but i want only subscriber role user can comment not other roles type user.</p>
<p>Thanks,</p>
| [
{
"answer_id": 232154,
"author": "pallavi",
"author_id": 96726,
"author_profile": "https://wordpress.stackexchange.com/users/96726",
"pm_score": 0,
"selected": false,
"text": "<p>The below code check if user is not subscriber then comment form will not display. Comment form only show whe... | 2016/07/13 | [
"https://wordpress.stackexchange.com/questions/232152",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/89896/"
] | I have marked the option - " Users must be registered and logged in to comment " in Admin panel Setting -> Discussion section but i want only subscriber role user can comment not other roles type user.
Thanks, | I suggest adding a snippet to the theme file where the comments form is loaded that checks to make sure there is a logged in user and then, if that user a Subscriber, then show the comments form to them. The examples below use the Twenty Sixteen theme:
In comments.php:
```
// First, get the current user and check their role
$user = wp_get_current_user();
if ( in_array( 'subscriber', (array) $user->roles ) ) {
// The current user has the subscriber role, show the form
comment_form( array(
'title_reply_before' => '<h2 id="reply-title" class="comment-reply-title">',
'title_reply_after' => '</h2>',
) );
}
```
This way, only those users with the subscriber role will see the comments form. |
232,164 | <p>I have created custom fields on my registration form, such as 'telephone', using <a href="https://wordpress.org/plugins/theme-my-login/" rel="nofollow">Theme My Login</a>. I have found a way to make them appear in the backend (on the User page) but I can't update those fields.</p>
<p>What do I need to do in order to be able to update them?</p>
<p>Register-form.php:</p>
<pre><code><label for="telephone<?php $template->the_instance(); ?>"><?php _e( 'Telephone', 'theme-my-login' ) ?></label>
<input type="text" name="telephone" id="pays<?php $template->the_instance(); ?>" class="input" value="<?php $template->the_posted_value( 'telephone' ); ?>"/>
</code></pre>
<p>Functions.php:</p>
<pre><code><?php
function custom_user_profile_fields($user) {
?>
<table class="form-table">
<tr>
<th>
<label for="telephone"><?php _e('Téléphone'); ?></label>
</th>
<td>
<input type="text" name="telephone" id="telephone" value="<?php echo esc_attr( get_the_author_meta( 'telephone', $user->ID ) ); ?>" class="regular-text" />
</td>
</tr>
</table>
<?php
}
add_action('show_user_profile', 'custom_user_profile_fields');
add_action('edit_user_profile', 'custom_user_profile_fields');
?>
</code></pre>
| [
{
"answer_id": 232166,
"author": "shubham jain",
"author_id": 89896,
"author_profile": "https://wordpress.stackexchange.com/users/89896",
"pm_score": 0,
"selected": false,
"text": "<p>You can use the following function to update custom field value for user </p>\n\n<pre><code> update_u... | 2016/07/13 | [
"https://wordpress.stackexchange.com/questions/232164",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/97014/"
] | I have created custom fields on my registration form, such as 'telephone', using [Theme My Login](https://wordpress.org/plugins/theme-my-login/). I have found a way to make them appear in the backend (on the User page) but I can't update those fields.
What do I need to do in order to be able to update them?
Register-form.php:
```
<label for="telephone<?php $template->the_instance(); ?>"><?php _e( 'Telephone', 'theme-my-login' ) ?></label>
<input type="text" name="telephone" id="pays<?php $template->the_instance(); ?>" class="input" value="<?php $template->the_posted_value( 'telephone' ); ?>"/>
```
Functions.php:
```
<?php
function custom_user_profile_fields($user) {
?>
<table class="form-table">
<tr>
<th>
<label for="telephone"><?php _e('Téléphone'); ?></label>
</th>
<td>
<input type="text" name="telephone" id="telephone" value="<?php echo esc_attr( get_the_author_meta( 'telephone', $user->ID ) ); ?>" class="regular-text" />
</td>
</tr>
</table>
<?php
}
add_action('show_user_profile', 'custom_user_profile_fields');
add_action('edit_user_profile', 'custom_user_profile_fields');
?>
``` | I use [update\_user\_meta](https://codex.wordpress.org/Function_Reference/update_user_meta) to update the fields. You can add this in functions.php of your child theme.
```
function save_extra_user_profile_fields( $user_id ) {
if ( !current_user_can( 'edit_user', $user_id ) ) {
return false;
}
update_user_meta( $user_id, 'telephone', $_POST['telephone'] );
}
add_action( 'personal_options_update', 'save_extra_user_profile_fields' );
add_action( 'edit_user_profile_update', 'save_extra_user_profile_fields' );
``` |
232,174 | <p>I need to change default WordPress <code>get_custom_logo()</code> generated url because I need to link to the main multi-site site instead of single site. Is there any filter to change this function?</p>
| [
{
"answer_id": 232175,
"author": "Davide De Maestri",
"author_id": 8741,
"author_profile": "https://wordpress.stackexchange.com/users/8741",
"pm_score": 3,
"selected": false,
"text": "<p>I solved using this filter:</p>\n\n<pre><code>add_filter( 'get_custom_logo', 'custom_logo_url' );\nf... | 2016/07/13 | [
"https://wordpress.stackexchange.com/questions/232174",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/8741/"
] | I need to change default WordPress `get_custom_logo()` generated url because I need to link to the main multi-site site instead of single site. Is there any filter to change this function? | I solved using this filter:
```
add_filter( 'get_custom_logo', 'custom_logo_url' );
function custom_logo_url ( $html ) {
$custom_logo_id = get_theme_mod( 'custom_logo' );
$url = network_site_url();
$html = sprintf( '<a href="%1$s" class="custom-logo-link" rel="home" itemprop="url">%2$s</a>',
esc_url( $url ),
wp_get_attachment_image( $custom_logo_id, 'full', false, array(
'class' => 'custom-logo',
) )
);
return $html;
}
``` |
232,185 | <p>I have a fairly simple AJAX request for my WordPress site. My PHP function is a switch statement and all the other switch statements work except for the recent one I added (change_due_date).</p>
<p>I commented out the majority of the code in my new 'case' to better try to find the problem. </p>
<p>AJAX (at bottom of page, under my other AJAX request (which works)):
</p>
<pre><code> function my_ajax() {
var newDate = <?php echo $new_date; ?>;
var data_string = 'action=do_ajax&fn=change_due_date&newDate=' + newDate;
jQuery.ajax({
type: "POST",
url: '/wp-admin/admin-ajax.php',
data: data_string,
dataType: 'JSON',
success: function(data){
// alert(data);
console.log("success!");
},
error: function(errorThrown){
console.log("error!");
}
});
} // end of my_ajax function
jQuery('a.test').click(function(){
my_ajax();
});
</script>
</code></pre>
<p>I tried, at first, just sending 'newDate' as my 'data' value - and that did work (as in AJAX returned 'success!'). In that case my PHP function still didn't run, since it wasn't being called. I suspect something is wrong with my formatting on the AJAX side of things... </p>
<p>Now, when I send 'data_string' as my data I get an AJAX error... </p>
<p>PHP Function: </p>
<pre><code>switch($_POST['fn']){ ...
/* AUTOMATE DUE DATE CREATION - made by Alex */
case 'change_due_date' :
/*$field_key = "field_515b2428887d7"; // Key ID for field
$new_date = $_POST['newDate']; // new date
$new_due_date = DateTime::createFromFormat('Ymd', $new_date);
$new_due_date->format('Ymd'); // formatting */
echo ('<h1>functioning</h1>'); // testing purposes
/*$parent_field = get_field($field_key); // Select parent field
foreach($parent_field as $sub_row) :
// Change value of sub-fields
$sub_row['date_due'] = $new_due_date;
$new_values[] = $sub_row; // Load new values into array
endforeach;
update_field( $field_key, $new_values ); // Update ACF*/
$output = "Successfully updated due dates."; // testing
break;
... }
</code></pre>
<p>I've been working on this code for a couple days - I admit I am not the best at AJAX... but I can't seem to find what's wrong? I have looked at the WP Codex for guidance on how to structure my AJAX.</p>
| [
{
"answer_id": 232219,
"author": "scott",
"author_id": 93587,
"author_profile": "https://wordpress.stackexchange.com/users/93587",
"pm_score": 0,
"selected": false,
"text": "<p>I think you may have a problem in the way you establish your data. If you read the WP Codex on AJAX, you will s... | 2016/07/13 | [
"https://wordpress.stackexchange.com/questions/232185",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/97928/"
] | I have a fairly simple AJAX request for my WordPress site. My PHP function is a switch statement and all the other switch statements work except for the recent one I added (change\_due\_date).
I commented out the majority of the code in my new 'case' to better try to find the problem.
AJAX (at bottom of page, under my other AJAX request (which works)):
```
function my_ajax() {
var newDate = <?php echo $new_date; ?>;
var data_string = 'action=do_ajax&fn=change_due_date&newDate=' + newDate;
jQuery.ajax({
type: "POST",
url: '/wp-admin/admin-ajax.php',
data: data_string,
dataType: 'JSON',
success: function(data){
// alert(data);
console.log("success!");
},
error: function(errorThrown){
console.log("error!");
}
});
} // end of my_ajax function
jQuery('a.test').click(function(){
my_ajax();
});
</script>
```
I tried, at first, just sending 'newDate' as my 'data' value - and that did work (as in AJAX returned 'success!'). In that case my PHP function still didn't run, since it wasn't being called. I suspect something is wrong with my formatting on the AJAX side of things...
Now, when I send 'data\_string' as my data I get an AJAX error...
PHP Function:
```
switch($_POST['fn']){ ...
/* AUTOMATE DUE DATE CREATION - made by Alex */
case 'change_due_date' :
/*$field_key = "field_515b2428887d7"; // Key ID for field
$new_date = $_POST['newDate']; // new date
$new_due_date = DateTime::createFromFormat('Ymd', $new_date);
$new_due_date->format('Ymd'); // formatting */
echo ('<h1>functioning</h1>'); // testing purposes
/*$parent_field = get_field($field_key); // Select parent field
foreach($parent_field as $sub_row) :
// Change value of sub-fields
$sub_row['date_due'] = $new_due_date;
$new_values[] = $sub_row; // Load new values into array
endforeach;
update_field( $field_key, $new_values ); // Update ACF*/
$output = "Successfully updated due dates."; // testing
break;
... }
```
I've been working on this code for a couple days - I admit I am not the best at AJAX... but I can't seem to find what's wrong? I have looked at the WP Codex for guidance on how to structure my AJAX. | A simple answer to your question is that you have the data type as JSON in your ajax request and you are passing a string in it. You need to pass a json object in the ajax request when you chose dataType equals to JSON. A JSON object is typically a key pair value inside curly braces. Here is a reference where you can see how ajax requests can be implemented in WordPress.
<https://www.smashingmagazine.com/2011/10/how-to-use-ajax-in-wordpress/>
<https://stackoverflow.com/questions/14185582/creating-an-ajax-call-in-wordpress-what-do-i-have-to-include-to-access-wordpres>
Check the data inside the ajax function. You will need to verify your json before sending it to the server so that there wont be any issues further. Also you will need to decode the json on the PHP server side. Then only you will be able to manipulate the data in your PHP code. May be an alternative way for you is that you can make a request without datatype json and you will get the post values in your PHP code making it easy to use. Check the below link for reference.
<http://www.makeuseof.com/tag/tutorial-ajax-wordpress/> |
232,193 | <p>I have a custom post type called location. I would like to be able to use 2 different templates for this custom post type and select it via the page attributes box. I have a template set up and can select it when I'm editing a Page, but not when I am editing a custom post type. I can't find any information on how to enable this. I want to enable the dropdown select for all the custom post types, not just one.</p>
| [
{
"answer_id": 232238,
"author": "MrFox",
"author_id": 69240,
"author_profile": "https://wordpress.stackexchange.com/users/69240",
"pm_score": 0,
"selected": false,
"text": "<p>Ok as mmm has pointed out that I can't do the dropdown select of templates on custom post types I have put this... | 2016/07/13 | [
"https://wordpress.stackexchange.com/questions/232193",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/69240/"
] | I have a custom post type called location. I would like to be able to use 2 different templates for this custom post type and select it via the page attributes box. I have a template set up and can select it when I'm editing a Page, but not when I am editing a custom post type. I can't find any information on how to enable this. I want to enable the dropdown select for all the custom post types, not just one. | Since WordPress version 4.7 **Post-Type-Templates are enabled** in the WordPress core.
That means that you can **create multiple templates for the single post-type view** as for pages.
For this you just need to edit the single post/type template, and add something like this to the top of the file:
```
/*
Template Name: Custom Type Template
Template Post Type: post, product, custom-type
*/
```
On the line `Template Post Type` you just add your custom post type slug.
So this template will be available on the `post`, `product` and `custom-type` post type.
I already answered this [here](https://wordpress.stackexchange.com/a/255021/88895).
Read more about post-type-templates of WP 4.7 [here](https://make.wordpress.org/core/2016/11/03/post-type-templates-in-4-7/). |
232,201 | <p>We are developing WordPress with multiple site. We need to share some posts to more than one site. We need to save post in more than one sites with a single click. </p>
<p>I have searched in Google, but I can't get any tutorial for that. </p>
| [
{
"answer_id": 232238,
"author": "MrFox",
"author_id": 69240,
"author_profile": "https://wordpress.stackexchange.com/users/69240",
"pm_score": 0,
"selected": false,
"text": "<p>Ok as mmm has pointed out that I can't do the dropdown select of templates on custom post types I have put this... | 2016/07/13 | [
"https://wordpress.stackexchange.com/questions/232201",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/98283/"
] | We are developing WordPress with multiple site. We need to share some posts to more than one site. We need to save post in more than one sites with a single click.
I have searched in Google, but I can't get any tutorial for that. | Since WordPress version 4.7 **Post-Type-Templates are enabled** in the WordPress core.
That means that you can **create multiple templates for the single post-type view** as for pages.
For this you just need to edit the single post/type template, and add something like this to the top of the file:
```
/*
Template Name: Custom Type Template
Template Post Type: post, product, custom-type
*/
```
On the line `Template Post Type` you just add your custom post type slug.
So this template will be available on the `post`, `product` and `custom-type` post type.
I already answered this [here](https://wordpress.stackexchange.com/a/255021/88895).
Read more about post-type-templates of WP 4.7 [here](https://make.wordpress.org/core/2016/11/03/post-type-templates-in-4-7/). |
232,246 | <p>Clicking the <strong>Update Profile</strong> button in the</p>
<pre><code>[wordpress]/wp-admin/profile.php
</code></pre>
<p>admin screen will allow the user to update his/her profile including the password.</p>
<p>What is the right action hook to use if you want to capture the new password during this password change?</p>
| [
{
"answer_id": 232300,
"author": "Ismail",
"author_id": 70833,
"author_profile": "https://wordpress.stackexchange.com/users/70833",
"pm_score": 1,
"selected": false,
"text": "<p>I have been looking around the core files searching for hooks, there were very few when it comes to hooking in... | 2016/07/14 | [
"https://wordpress.stackexchange.com/questions/232246",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/58915/"
] | Clicking the **Update Profile** button in the
```
[wordpress]/wp-admin/profile.php
```
admin screen will allow the user to update his/her profile including the password.
What is the right action hook to use if you want to capture the new password during this password change? | I have been looking around the core files searching for hooks, there were very few when it comes to hooking into `edit_user()` function which updates the user data in `profile.php` page, so I have finished with some workarounds:
My workaround is to save the user's password in a custom option before the password was updated, and match later with this user's password to see if it has changed:
```
add_action("check_passwords", function( $user_login, $pass1, $pass2 ) {
if ( !is_admin() || !defined('IS_PROFILE_PAGE') || !IS_PROFILE_PAGE )
return; // not profile.php page, let's mind our business
update_option( "_se_debug_user_submitted_pass", wp_get_current_user()->user_pass );
return;
}, 10, 3);
add_action("admin_init", function() {
global $pagenow;
if ( "profile.php" !== $pagenow ) return;
global $current_user;
if ( get_option( $opt_name = "_se_debug_user_submitted_pass" ) && (string) get_option( $opt_name ) !== (string) $current_user->user_pass ) {
// the password has changed.
echo "Password has changed!";
/* do things here */
delete_option( $opt_name ); // do only once
}
});
```
That should work and as long as in `profile.php` page (updating own profile).
To capture the password, after this line:
`update_option( "_se_debug_user_submitted_pass", wp_get_current_user()->user_pass );`
update a custom option with the new password value `$pass2` which is the password confirmation, and call this option within `// the password has changed.` wrap. THIS IS NOT GOOD AT ALL to get user's plain text passwords, I would never recommend such thing but it's your call and on your own risk. Unless you are capturing the hashed pass then that's totally fine.
One thing is, if the user updates the password but still with the same old pass, this condition will still be fired because the WordPress password hashing system uses randomly-generated salts and therefore the return will be different (powerful security, and I would like to invite you to quit using md5 if you use it for hashing in your projects).
Hope that helps somehow. |
232,249 | <p>I am new to Wordpress but I have some knowledge of PHP. I am creating a bilingual site (with Polylang) which has many forms. Some of them are handled by Contact Form 7 but some others have to be custom made.</p>
<p>So, the first form I made was quite a disaster - it works but under certain circumstances. </p>
<p>In the archives page of a custom post I insert</p>
<pre><code><form method="post" action="<?php echo esc_url( home_url( '/' ) ); ?>">
<input type="hidden" name="post_type" value="myvalue">
<select class="form-control" name="k" id="k">
<?php
for($i=0;$i<2;$i++){?>
<option value="<?php echo $array3[$i]?>"><?php echo $array3[$i];?></option>
<?php }?>
</select>
<span class="input-group-btn">
<button class="btn btn-search" type="submit"><i class="fa fa-search"> </i></button>
</span>
</form>
</code></pre>
<p>I created a template file named mysearchresults.php In there I inserted the essential (between them)</p>
<pre><code> echo $_POST['k'];
echo "Hello world";
</code></pre>
<p>I created a page having as template mysearchresults.php in one language (named mysearchresults) and another in the other language (same template) named mysearchresults-2.</p>
<p>Loading the two pages gives a page with the Hello world printed.</p>
<p>Adding</p>
<pre><code><form method="post" action="<?php echo esc_url( home_url( '/' ) ); ?>mysearchresults-2">
</code></pre>
<p>gives 404 (when I press the submit button - having made a selsction) - the same as instead of -2 I put mysearchresults. Putting mysearchresults.php gives the same error.</p>
<p>So I tried another approach, instead of </p>
<pre><code><select class="form-control" name="k" id="k">
</code></pre>
<p>I put </p>
<pre><code><select class="form-control" name="s" id="s">
</code></pre>
<p>and for action I left</p>
<pre><code>action="<?php echo esc_url( home_url( '/' ) ); ?>">
</code></pre>
<p>In the search page I put echo $_POST['s'] and it loads the search results page printing the value of my selection.</p>
<p>What am I doing wrong? How can I have a custom form, pass the values in my action file and make operations on them? Why leaving like this the action label it loads the search results page?</p>
| [
{
"answer_id": 232300,
"author": "Ismail",
"author_id": 70833,
"author_profile": "https://wordpress.stackexchange.com/users/70833",
"pm_score": 1,
"selected": false,
"text": "<p>I have been looking around the core files searching for hooks, there were very few when it comes to hooking in... | 2016/07/14 | [
"https://wordpress.stackexchange.com/questions/232249",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/98314/"
] | I am new to Wordpress but I have some knowledge of PHP. I am creating a bilingual site (with Polylang) which has many forms. Some of them are handled by Contact Form 7 but some others have to be custom made.
So, the first form I made was quite a disaster - it works but under certain circumstances.
In the archives page of a custom post I insert
```
<form method="post" action="<?php echo esc_url( home_url( '/' ) ); ?>">
<input type="hidden" name="post_type" value="myvalue">
<select class="form-control" name="k" id="k">
<?php
for($i=0;$i<2;$i++){?>
<option value="<?php echo $array3[$i]?>"><?php echo $array3[$i];?></option>
<?php }?>
</select>
<span class="input-group-btn">
<button class="btn btn-search" type="submit"><i class="fa fa-search"> </i></button>
</span>
</form>
```
I created a template file named mysearchresults.php In there I inserted the essential (between them)
```
echo $_POST['k'];
echo "Hello world";
```
I created a page having as template mysearchresults.php in one language (named mysearchresults) and another in the other language (same template) named mysearchresults-2.
Loading the two pages gives a page with the Hello world printed.
Adding
```
<form method="post" action="<?php echo esc_url( home_url( '/' ) ); ?>mysearchresults-2">
```
gives 404 (when I press the submit button - having made a selsction) - the same as instead of -2 I put mysearchresults. Putting mysearchresults.php gives the same error.
So I tried another approach, instead of
```
<select class="form-control" name="k" id="k">
```
I put
```
<select class="form-control" name="s" id="s">
```
and for action I left
```
action="<?php echo esc_url( home_url( '/' ) ); ?>">
```
In the search page I put echo $\_POST['s'] and it loads the search results page printing the value of my selection.
What am I doing wrong? How can I have a custom form, pass the values in my action file and make operations on them? Why leaving like this the action label it loads the search results page? | I have been looking around the core files searching for hooks, there were very few when it comes to hooking into `edit_user()` function which updates the user data in `profile.php` page, so I have finished with some workarounds:
My workaround is to save the user's password in a custom option before the password was updated, and match later with this user's password to see if it has changed:
```
add_action("check_passwords", function( $user_login, $pass1, $pass2 ) {
if ( !is_admin() || !defined('IS_PROFILE_PAGE') || !IS_PROFILE_PAGE )
return; // not profile.php page, let's mind our business
update_option( "_se_debug_user_submitted_pass", wp_get_current_user()->user_pass );
return;
}, 10, 3);
add_action("admin_init", function() {
global $pagenow;
if ( "profile.php" !== $pagenow ) return;
global $current_user;
if ( get_option( $opt_name = "_se_debug_user_submitted_pass" ) && (string) get_option( $opt_name ) !== (string) $current_user->user_pass ) {
// the password has changed.
echo "Password has changed!";
/* do things here */
delete_option( $opt_name ); // do only once
}
});
```
That should work and as long as in `profile.php` page (updating own profile).
To capture the password, after this line:
`update_option( "_se_debug_user_submitted_pass", wp_get_current_user()->user_pass );`
update a custom option with the new password value `$pass2` which is the password confirmation, and call this option within `// the password has changed.` wrap. THIS IS NOT GOOD AT ALL to get user's plain text passwords, I would never recommend such thing but it's your call and on your own risk. Unless you are capturing the hashed pass then that's totally fine.
One thing is, if the user updates the password but still with the same old pass, this condition will still be fired because the WordPress password hashing system uses randomly-generated salts and therefore the return will be different (powerful security, and I would like to invite you to quit using md5 if you use it for hashing in your projects).
Hope that helps somehow. |
232,254 | <p><br/>
Is there a way to check that comment was successfully submitted? I want to display some text or hide a comment form for example if comment was succesfully submitted. </p>
| [
{
"answer_id": 232300,
"author": "Ismail",
"author_id": 70833,
"author_profile": "https://wordpress.stackexchange.com/users/70833",
"pm_score": 1,
"selected": false,
"text": "<p>I have been looking around the core files searching for hooks, there were very few when it comes to hooking in... | 2016/07/14 | [
"https://wordpress.stackexchange.com/questions/232254",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/97934/"
] | Is there a way to check that comment was successfully submitted? I want to display some text or hide a comment form for example if comment was succesfully submitted. | I have been looking around the core files searching for hooks, there were very few when it comes to hooking into `edit_user()` function which updates the user data in `profile.php` page, so I have finished with some workarounds:
My workaround is to save the user's password in a custom option before the password was updated, and match later with this user's password to see if it has changed:
```
add_action("check_passwords", function( $user_login, $pass1, $pass2 ) {
if ( !is_admin() || !defined('IS_PROFILE_PAGE') || !IS_PROFILE_PAGE )
return; // not profile.php page, let's mind our business
update_option( "_se_debug_user_submitted_pass", wp_get_current_user()->user_pass );
return;
}, 10, 3);
add_action("admin_init", function() {
global $pagenow;
if ( "profile.php" !== $pagenow ) return;
global $current_user;
if ( get_option( $opt_name = "_se_debug_user_submitted_pass" ) && (string) get_option( $opt_name ) !== (string) $current_user->user_pass ) {
// the password has changed.
echo "Password has changed!";
/* do things here */
delete_option( $opt_name ); // do only once
}
});
```
That should work and as long as in `profile.php` page (updating own profile).
To capture the password, after this line:
`update_option( "_se_debug_user_submitted_pass", wp_get_current_user()->user_pass );`
update a custom option with the new password value `$pass2` which is the password confirmation, and call this option within `// the password has changed.` wrap. THIS IS NOT GOOD AT ALL to get user's plain text passwords, I would never recommend such thing but it's your call and on your own risk. Unless you are capturing the hashed pass then that's totally fine.
One thing is, if the user updates the password but still with the same old pass, this condition will still be fired because the WordPress password hashing system uses randomly-generated salts and therefore the return will be different (powerful security, and I would like to invite you to quit using md5 if you use it for hashing in your projects).
Hope that helps somehow. |
232,269 | <p>I've spent a day or so on this now and I'm turning to the community for assistance.</p>
<p>Firstly, I am trying to achieve something like this post:</p>
<p><a href="https://wordpress.stackexchange.com/questions/27158/wordpress-multiple-category-search">Wordpress Multiple Category Search</a></p>
<p>In my theme template, I have a custom search form:</p>
<pre><code><form id="searchform" method="get" action="<?php bloginfo('url'); ?>">
<fieldset>
<input type="text" name="s" value="" placeholder="Search..."></input>
<button type="submit">Search</button>
<div class="clear"></div>
<div class="search_category_section">
<?php
$args = array('parent' => 0);
$categories = get_categories($args);
echo '<div class="search_category_section">';
foreach ($categories as $category) {
$thecatid = $category->cat_ID;
echo '<div class="categorylist"><div class="parent_category_list_item"><input id="', $thecatid, '" type="checkbox" name="category_name" value="', $category->slug, '"><label for="', $thecatid, '">', $category->name, '</label></input></div>';
$childcats=get_categories(array('parent' => $thecatid));
foreach($childcats as $c) {
echo '<div class="child_category_list_item"><input id="', $c->cat_ID, '" type="checkbox" name="category_name" value="', $c->slug, '"><label for="', $c->cat_ID, '">', $c->name, '</label></input></div>';
}
echo '</div>';
}
?>
</div>
</fieldset>
</code></pre>
<p></p>
<p>So, let's say for example I search for "keyword", and I select two checkboxes, "category A" and "category B". I have two posts, one in each category. Each of those two posts has that keyword in it. After hitting the submit button it generates the following URL:</p>
<p>mydomain.com/?s=keyword&category_name=category-a&category_name=category-b</p>
<p>What this is currently doing is presenting me with one result - that is, one post from category B with that keyword in it.</p>
<p>What I'm actually looking for is this result:</p>
<p>mydomain.com/?s=keyword&category_name=category-a,category-b</p>
<p>Whereby I get all posts in all categories, with that keyword in it.</p>
<p>I've looked high and low, and while I've found results where others were trying to achieve a similar thing, none of their solutions worked for me.</p>
<p>This is all part of a learning curve for me. I have found <a href="https://wordpress.org/plugins/search-filter/" rel="nofollow noreferrer">this plugin</a> which looks like it will do what I want, but as you've all probably been in this situation whereby "I wish I could do this myself so that I understand better how the mechanics behind Wordpress" work I hope you'll appreciate the question.</p>
<p>Thanks in advance, if anything isn't clear or I've left vital info out let me know.</p>
| [
{
"answer_id": 232270,
"author": "Preethi Sasankan",
"author_id": 92003,
"author_profile": "https://wordpress.stackexchange.com/users/92003",
"pm_score": 2,
"selected": false,
"text": "<p><strong>let’s start by defining an HTML search form:</strong></p>\n\n<pre><code><form method=\"ge... | 2016/07/14 | [
"https://wordpress.stackexchange.com/questions/232269",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/98327/"
] | I've spent a day or so on this now and I'm turning to the community for assistance.
Firstly, I am trying to achieve something like this post:
[Wordpress Multiple Category Search](https://wordpress.stackexchange.com/questions/27158/wordpress-multiple-category-search)
In my theme template, I have a custom search form:
```
<form id="searchform" method="get" action="<?php bloginfo('url'); ?>">
<fieldset>
<input type="text" name="s" value="" placeholder="Search..."></input>
<button type="submit">Search</button>
<div class="clear"></div>
<div class="search_category_section">
<?php
$args = array('parent' => 0);
$categories = get_categories($args);
echo '<div class="search_category_section">';
foreach ($categories as $category) {
$thecatid = $category->cat_ID;
echo '<div class="categorylist"><div class="parent_category_list_item"><input id="', $thecatid, '" type="checkbox" name="category_name" value="', $category->slug, '"><label for="', $thecatid, '">', $category->name, '</label></input></div>';
$childcats=get_categories(array('parent' => $thecatid));
foreach($childcats as $c) {
echo '<div class="child_category_list_item"><input id="', $c->cat_ID, '" type="checkbox" name="category_name" value="', $c->slug, '"><label for="', $c->cat_ID, '">', $c->name, '</label></input></div>';
}
echo '</div>';
}
?>
</div>
</fieldset>
```
So, let's say for example I search for "keyword", and I select two checkboxes, "category A" and "category B". I have two posts, one in each category. Each of those two posts has that keyword in it. After hitting the submit button it generates the following URL:
mydomain.com/?s=keyword&category\_name=category-a&category\_name=category-b
What this is currently doing is presenting me with one result - that is, one post from category B with that keyword in it.
What I'm actually looking for is this result:
mydomain.com/?s=keyword&category\_name=category-a,category-b
Whereby I get all posts in all categories, with that keyword in it.
I've looked high and low, and while I've found results where others were trying to achieve a similar thing, none of their solutions worked for me.
This is all part of a learning curve for me. I have found [this plugin](https://wordpress.org/plugins/search-filter/) which looks like it will do what I want, but as you've all probably been in this situation whereby "I wish I could do this myself so that I understand better how the mechanics behind Wordpress" work I hope you'll appreciate the question.
Thanks in advance, if anything isn't clear or I've left vital info out let me know. | Here is what worked for me.
Preethis answer almost got there, but no data was getting set. I needed to find a way of accessing the data in the array, and I used implode to do it.
So here is my final code that enabled me to create a search form that loops and displays categories, allows the user to do a keyword search via any number of categories, and display results IF the keyword exists in any of the categories selected:
I created a **searchform.php** file in my theme file and included the following HTML:
```
<form id="searchform" method="get" action="<?php bloginfo('url'); ?>">
<fieldset>
<input type="text" name="s" value="" placeholder="Search..."></input>
<button type="submit">Search</button>
<div class="clear"></div>
<div class="search_category_section">
<?php
$args = array('parent' => 0);
$categories = get_categories($args);
echo '<div class="search_category_section">';
foreach ($categories as $category) {
$thecatid = $category->cat_ID;
echo '<div class="categorylist"><div class="parent_category_list_item"><input id="', $thecatid, '" type="checkbox" name="category_name[]" value="', $category->slug, '"><label for="', $thecatid, '">', $category->name, '</label></input></div>';
$childcats=get_categories(array('parent' => $thecatid));
foreach($childcats as $c) {
echo '<div class="child_category_list_item"><input id="', $c->cat_ID, '" type="checkbox" name="category_name[]" value="', $c->slug, '"><label for="', $c->cat_ID, '">', $c->name, '</label></input></div>';
}
echo '</div>';
}
?>
</div>
</fieldset>
```
and then, my **functions.php** has the following code:
```
<?php
function advanced_search_query($query) {
if($query->is_search()) {
$get_the_category_name = $_GET['category_name'];
if (isset($get_the_category_name) && is_array($get_the_category_name)) {
$catnames = implode(",",$get_the_category_name);
$query->set('category_name', $catnames);
return $query;
}
}
}
add_action('pre_get_posts', 'advanced_search_query');
?>
```
if you do:
```
var_dump($get_the_category_name);
```
You'll get:
```
array(2) { [0]=> string(22) "category-a" [1]=> string(25) "category-b" }
```
Run implode() on that
```
string(48) "human-element-analysis,latent-defects-check-list"
```
Stick that string in a variable, set it in query as category\_name, win.
Thanks again Preethi for putting me in the right direction, and hope the above helps anyone looking to do the same! |
232,278 | <p>I have a plugin that reads data from an uploaded file and runs queries on the wp database. These inserts are into a table created by my plugin, so they aren't the post type.</p>
<p>This is how I got it working: </p>
<pre><code>$connection = mysqli_connect($db_host, $db_user, $db_pass, $db_name);
mysqli_query($connection, $query);
</code></pre>
<p>The problem with this is that I have to declare these variables (<strong><em>$db_host, $db_user, $db_pass, $db_name</em></strong>) inside the plugin source code. </p>
<p>Is there a way I can insert data into my custom tables with the wp api? Or is there a way I can pull these variables from an external file that I can ignore in a version control setup?</p>
| [
{
"answer_id": 232284,
"author": "Sabbir Hasan",
"author_id": 76587,
"author_profile": "https://wordpress.stackexchange.com/users/76587",
"pm_score": 3,
"selected": false,
"text": "<p>Why not study about how <strong>$wpdb</strong> works. Visit <a href=\"https://codex.wordpress.org/Class_... | 2016/07/14 | [
"https://wordpress.stackexchange.com/questions/232278",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/98214/"
] | I have a plugin that reads data from an uploaded file and runs queries on the wp database. These inserts are into a table created by my plugin, so they aren't the post type.
This is how I got it working:
```
$connection = mysqli_connect($db_host, $db_user, $db_pass, $db_name);
mysqli_query($connection, $query);
```
The problem with this is that I have to declare these variables (***$db\_host, $db\_user, $db\_pass, $db\_name***) inside the plugin source code.
Is there a way I can insert data into my custom tables with the wp api? Or is there a way I can pull these variables from an external file that I can ignore in a version control setup? | That's not a good practice trying to connect the DB by your own methods while WP does it for you initially.
---
>
> The problem with this is that I have to declare these variables
> ($db\_host, $db\_user, $db\_pass, $db\_name) inside the plugin source
> code.
>
>
>
All these properties are defined in `wp-config.php` file, located in the root area.
If you were to get these constants then, just include the file and call the constants, or use REGEX (better use REGEX, because there might be other callbacks that require loading WordPress)
```
// loading the config file to pull the DB_* constants
$dirname = dirname(__FILE__);
$root = false !== mb_strpos( $dirname, 'wp-content' ) ? mb_substr( $dirname, 0, mb_strpos( $dirname, 'wp-content' ) ) : $dirname;
// if $root is not correct, provide a static path then, $root = '/path/to/root/dir'
// assuming constants are ready (wp is configured), let's get them.
require_once( $root . "wp-config.php" );
echo var_dump(
'DB name', DB_NAME,
'DB user', DB_USER,
'DB password', DB_PASSWORD,
'DB host', DB_HOST
);
```
---
Here's a better solution:
**Load WordPress**
`require( '/wp-blog-header.php' );` You should provide a working path to that file!
To test if you have loaded WordPress successfully, dump out something:
```
add_action("wp", function() {
echo sprintf( "Yes! I am creating with WordPress v. %s!\n", get_bloginfo("version") );
exit("I exits\n");
});
```
**Now use WordPress DB API**
To insert data, there's this [`wpdb::insert`](https://codex.wordpress.org/Class_Reference/wpdb#INSERT_row) you should use. Here the syntax
`$wpdb->insert( $table, $data, $format );` and example use:
```
$wpdb->insert(
'messages',
array(
'PM_ID' => (int) $pm_id,
'sender' => $current_user->ID,
'recipient' => (int) $recipient,
'message' => "Hello!\n",
'date' => time()
)
);
$record_id = $wpdb->insert_id;
```
In the example, the array in `$wpdb->insert`'s 2nd param is an array with indexes as columns names, and values to be inserted for these cols in an independent record that you can get its ID with `$wpdb->insert_id` which gets last record insert ID in that table.
Hope that helps, if at least you stay away from SQL injection using `$wpdb::insert` or prepared statements instead of direct queries. |
232,308 | <p>I made a plugin that adds a shortcode with optional content. If there's no content, WordPress still tries looking for a closing tag. This is clearer with an example:</p>
<pre><code>[span class="foo"]
[span class="bar"]
[span class="baz"]stuff[/span]
</code></pre>
<p>Wanted:</p>
<pre><code><span class="foo"></span>
<span class="bar"></span>
<span class="baz">stuff</span>
</code></pre>
<p>Actual:</p>
<pre><code><span class="foo">
[span class="bar"]
[span class="baz"]stuff
</span>
</code></pre>
<p>Is there a way to make WordPress produce the first output? I'm expecting many of the plugin's users to be confused by this behavior. One way is to modify <code>the_content</code> before <code>do_shortcode</code> runs, but it's pretty hacky. Is there a clean or existing way to change this behavior?</p>
<p>Edit: I'm not asking why this behavior occurs, I'm asking for a good way to change this behavior.</p>
| [
{
"answer_id": 232332,
"author": "webHasan",
"author_id": 44137,
"author_profile": "https://wordpress.stackexchange.com/users/44137",
"pm_score": 3,
"selected": false,
"text": "<p>Wordpress interpreted your shortcode like this:</p>\n\n<p><a href=\"https://i.stack.imgur.com/4S0P0.png\" re... | 2016/07/15 | [
"https://wordpress.stackexchange.com/questions/232308",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/23538/"
] | I made a plugin that adds a shortcode with optional content. If there's no content, WordPress still tries looking for a closing tag. This is clearer with an example:
```
[span class="foo"]
[span class="bar"]
[span class="baz"]stuff[/span]
```
Wanted:
```
<span class="foo"></span>
<span class="bar"></span>
<span class="baz">stuff</span>
```
Actual:
```
<span class="foo">
[span class="bar"]
[span class="baz"]stuff
</span>
```
Is there a way to make WordPress produce the first output? I'm expecting many of the plugin's users to be confused by this behavior. One way is to modify `the_content` before `do_shortcode` runs, but it's pretty hacky. Is there a clean or existing way to change this behavior?
Edit: I'm not asking why this behavior occurs, I'm asking for a good way to change this behavior. | Wordpress interpreted your shortcode like this:
[](https://i.stack.imgur.com/4S0P0.png)
The main issue being, that you have a unclosed shortcode of the same tag in front of an enclosing shortcode of the same tag, which won't be parsed correctly. The documentation states that you might run into problems with [unclosed shortcodes](https://codex.wordpress.org/Shortcode_API#Unclosed_Shortcodes).
When you call your shortcode like this:
```
[span class="foo" /]
[span class="bar" /]
[span class="baz"]stuff[/span]
```
You will get your expected result.
Because the [self-closing marker](https://codex.wordpress.org/Shortcode_API#Self-Closing) `/` is needed in your use-case, although it generally is considered optional, but as it forces the parser to ignore following closing tags it gets you your expected result.
The above solution is the correct usage of shortcodes according to the [WordPress Shortcode API](https://codex.wordpress.org/Shortcode_API). If you want to to pre-process your shortcode in one way or another you can do that, but generally just make your users use the correct syntax in the first place. |
232,345 | <p>I have PHP code</p>
<pre><code><?php if ($_SESSION['logged_in'] == 1) {
echo '<script type="text/javascript">var logged_in=true;</script>';
} else {
echo '<script type="text/javascript">var logged_in=false;</script>';
}?>
</code></pre>
<p>It always returns <code>var logged_in=false;</code>. Where is mistake?</p>
| [
{
"answer_id": 232346,
"author": "Александр",
"author_id": 88709,
"author_profile": "https://wordpress.stackexchange.com/users/88709",
"pm_score": 2,
"selected": false,
"text": "<pre><code><?php\nif ( is_user_logged_in() ) {\n echo '<script type=\"text/javascript\">var logged_i... | 2016/07/15 | [
"https://wordpress.stackexchange.com/questions/232345",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/88709/"
] | I have PHP code
```
<?php if ($_SESSION['logged_in'] == 1) {
echo '<script type="text/javascript">var logged_in=true;</script>';
} else {
echo '<script type="text/javascript">var logged_in=false;</script>';
}?>
```
It always returns `var logged_in=false;`. Where is mistake? | ```
<?php
if ( is_user_logged_in() ) {
echo '<script type="text/javascript">var logged_in=true;</script>';
} else {
echo '<script type="text/javascript">var logged_in=false;</script>';
}
?>
``` |
232,409 | <p>There is a major problem with most new templates for WordPress that want you to set your homepage to <strong><code>Your Latest Posts</code></strong>. </p>
<p>This is to enable many of the great theme features to work.</p>
<p>The problem with this is that the front page (even though not a blog page) is seen as a paged entity by the wordpress core and yoast seo too.</p>
<p>So what does this mean?</p>
<p>You have a homepage <code>www.mysite.com</code> if you visit your page and look inside the source code you see <strong><code>rel="next" href="hxxps://www.mysite.com/page/2/"</code></strong></p>
<p>If you actually click that /page/2 link you will see it takes you right back to your front page except this time if you look in the source code it now has <strong><code>rel="prev" href="hxxps://www.mysite.com/"</code></strong> and <strong><code>rel="next" href="hxxps://www.mysite.com/page/3/"</code></strong></p>
<p>If you click the link to <strong><code>/page/3/</code></strong> now and once again inspect the source code you will see <strong><code>rel="prev" href="hxxps://www.mysite.com/page/2/"</code></strong> and <strong><code>rel="next" href="hxxps://www.mysite.com/page/4/"</code></strong></p>
<p>This goes on and on and is not something an end user will ever see but is very bad for search engines especially Google who will possibly see this as duplicate content.</p>
<p>I have been in support talks with Yoast for several weeks on this issue and they are adamant it's a theme problem and blames theme developers not using wp_enqueue correctly. For the most part I believe it is but it also means that a great majority of the most popular wordpress themes out there have this very same problem.</p>
<p>The only current way around this is to go into reading settings in wordpress and set your front page to a <code>static page</code> and your posts page to <code>your posts page</code>. Easy but you lose all the nice functionality of a really great template you just spent a week customizing or even paid good money for.</p>
<p>So while that may be a solution, it's not really a solution and it seems most theme developers do not know how to get around this.</p>
<p>I have had this problem with my past theme Tempera, I switched to a few new themes from <code>GraphPaperPress</code> and then also tried out one of the most popular themes <code>Zerif</code> and they all have this problem. </p>
<p>I have tried all sorts of code snippets in functions.php and I can get the rel=next and rel=prev to not display on the front page but then it also does not work on every other page like the /blog/ page where do you want these meta links and also on all the category pages which also need the rel=next and rel=prev links in order to tell search engines to keep crawling deeper.</p>
<p>I can do this switch to a static front page and get a decent looking front page, similar to the themes dynamic front page but there is so much functionality lost and its rather depressing to have to settle for less, especially with all the wonderful ajaxy and parallaxy things that are available today.</p>
<p>So is there actually a simple function to remove it from the home page only but to have it appear on pages like /blog/ /category1/ /category2/</p>
<p>Here are some I have tried but I am just not getting the conditional statements right or I am doing something else wrong but its been too long diagnosing this now and I think I am losing my mind for sure.</p>
<pre><code>function wpseo_disable_rel_next_home( $link ) {
if ( is_home() ) {
return false;
}
}
add_filter( 'wpseo_next_rel_link', 'wpseo_disable_rel_next_home' );
</code></pre>
<p>and </p>
<pre><code>function genesis () {
if ( !is_home() || !function_exists( 'genesis' ) )
$this->adjacent_rel_links();
}
</code></pre>
<p>and</p>
<pre><code>if ( is_front_page() && is_home() )
{
remove_action( 'wp_head', 'adjacent_posts_rel_link_wp_head', 10, 0 );
remove_action(‘wp_head’, ‘cor_rel_next_prev_pagination’);
}
</code></pre>
<p>Hope someone can solve this riddle. Anyone wanting to test this out can download the Zerif theme and make sure Yoast is installed too. Use their dynamic front page system and then create a blog page for a separate blog listing page.</p>
| [
{
"answer_id": 232410,
"author": "mlimon",
"author_id": 64458,
"author_profile": "https://wordpress.stackexchange.com/users/64458",
"pm_score": 0,
"selected": false,
"text": "<p>I see you already tried with wpseo_next_rel_link can try with this one more time.</p>\n\n<pre><code>function w... | 2016/07/16 | [
"https://wordpress.stackexchange.com/questions/232409",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/98424/"
] | There is a major problem with most new templates for WordPress that want you to set your homepage to **`Your Latest Posts`**.
This is to enable many of the great theme features to work.
The problem with this is that the front page (even though not a blog page) is seen as a paged entity by the wordpress core and yoast seo too.
So what does this mean?
You have a homepage `www.mysite.com` if you visit your page and look inside the source code you see **`rel="next" href="hxxps://www.mysite.com/page/2/"`**
If you actually click that /page/2 link you will see it takes you right back to your front page except this time if you look in the source code it now has **`rel="prev" href="hxxps://www.mysite.com/"`** and **`rel="next" href="hxxps://www.mysite.com/page/3/"`**
If you click the link to **`/page/3/`** now and once again inspect the source code you will see **`rel="prev" href="hxxps://www.mysite.com/page/2/"`** and **`rel="next" href="hxxps://www.mysite.com/page/4/"`**
This goes on and on and is not something an end user will ever see but is very bad for search engines especially Google who will possibly see this as duplicate content.
I have been in support talks with Yoast for several weeks on this issue and they are adamant it's a theme problem and blames theme developers not using wp\_enqueue correctly. For the most part I believe it is but it also means that a great majority of the most popular wordpress themes out there have this very same problem.
The only current way around this is to go into reading settings in wordpress and set your front page to a `static page` and your posts page to `your posts page`. Easy but you lose all the nice functionality of a really great template you just spent a week customizing or even paid good money for.
So while that may be a solution, it's not really a solution and it seems most theme developers do not know how to get around this.
I have had this problem with my past theme Tempera, I switched to a few new themes from `GraphPaperPress` and then also tried out one of the most popular themes `Zerif` and they all have this problem.
I have tried all sorts of code snippets in functions.php and I can get the rel=next and rel=prev to not display on the front page but then it also does not work on every other page like the /blog/ page where do you want these meta links and also on all the category pages which also need the rel=next and rel=prev links in order to tell search engines to keep crawling deeper.
I can do this switch to a static front page and get a decent looking front page, similar to the themes dynamic front page but there is so much functionality lost and its rather depressing to have to settle for less, especially with all the wonderful ajaxy and parallaxy things that are available today.
So is there actually a simple function to remove it from the home page only but to have it appear on pages like /blog/ /category1/ /category2/
Here are some I have tried but I am just not getting the conditional statements right or I am doing something else wrong but its been too long diagnosing this now and I think I am losing my mind for sure.
```
function wpseo_disable_rel_next_home( $link ) {
if ( is_home() ) {
return false;
}
}
add_filter( 'wpseo_next_rel_link', 'wpseo_disable_rel_next_home' );
```
and
```
function genesis () {
if ( !is_home() || !function_exists( 'genesis' ) )
$this->adjacent_rel_links();
}
```
and
```
if ( is_front_page() && is_home() )
{
remove_action( 'wp_head', 'adjacent_posts_rel_link_wp_head', 10, 0 );
remove_action(‘wp_head’, ‘cor_rel_next_prev_pagination’);
}
```
Hope someone can solve this riddle. Anyone wanting to test this out can download the Zerif theme and make sure Yoast is installed too. Use their dynamic front page system and then create a blog page for a separate blog listing page. | Here is the answer:
```
function bg_disable_front_page_wpseo_next_rel_link( $link ) {
if ( is_front_page() ) {
return false;
}
return $link;
}
add_filter( 'wpseo_next_rel_link', 'bg_disable_front_page_wpseo_next_rel_link' );
```
You have to return the $link, if you return nothing it will disable it for every single page... |
232,435 | <p>I need some customization of WORDPRESS comment area, so I've used this code in my child theme :</p>
<pre><code> <div id="comments" class="x-comments-area">
<?php if ( have_comments() ) : ?>
<?php
//The author of current post
$author_ID = get_the_author_meta("ID");
//The current post ID
$p_ID = get_the_ID();
?>
<h2 class="h-comments-title"><span><?php _e( 'Comments' , '__x__' ); ?> <small>
<?php
//Number of guest comments
echo ztjalali_persian_num(number_format_i18n(count(get_comments(array('post_id' => $p_ID,'author__not_in' => array($author_ID))))));
?></small></span></h2>
<ol class="x-comments-list">
<?php
wp_list_comments( array(
'callback' => 'x_icon_comment',
'style' => 'ol'
) );
?>
</ol>
<?php if ( get_comment_pages_count() > 1 && get_option( 'page_comments' ) ) : ?>
<nav id="comment-nav-below" class="navigation" role="navigation">
<h1 class="visually-hidden"><?php _e( 'Comment navigation', '__x__' ); ?></h1>
<div class="nav-previous"><?php previous_comments_link( __( '&larr; Older Comments', '__x__' ) ); ?></div>
<div class="nav-next"><?php next_comments_link( __( 'Newer Comments &rarr;', '__x__' ) ); ?></div>
</nav>
<?php endif; ?>
<?php if ( ! comments_open() && get_comments_number() ) : ?>
<p class="nocomments"><?php _e( 'Comments are closed.' , '__x__' ); ?></p>
<?php endif; ?>
<?php endif; ?>
<?php
//Loading of smilies
ob_start(); cs_print_smilies(); $cs_print_smilies = ob_get_clean();
//Comment form re-arrangement
comment_form( array(
'comment_notes_before' => '',
'comment_notes_after' => '',
'id_submit' => 'entry-comment-submit',
'label_submit' => __( 'Submit' , '__x__' ),
'title_reply' => __( '<span>Leave a Comment</span>' , '__x__' ),
'fields' => array(
'author' =>
'<p class="comment-form-author">' .
'<input id="author" name="author" type="text" value="' . get_comment_author() . '" placeholder="' . __( 'Name *', '__x__' ) . ' ' . '" size="30"/>' .
'</p>',
'email' =>
'<p class="comment-form-email">' .
'<input id="email" name="email" type="email" aria-required="true" aria-invalid="false" value="' .get_comment_author_email() . '" placeholder="' . __( 'Email *', '__x__' ) . ' ' . '" size="30"/>' .
'</p>',
'url' =>
'<p class="comment-form-url">' .
'<input id="url" name="url" type="text" value="' . get_comment_author_url() . '" placeholder="' . __( 'URL', '__x__' ) . '" size="30" />' .
'</p>'
),
'comment_field' => '<p class="comment-form-comment">' .
'</br>'.
$cs_print_smilies .
'<textarea id="comment" name="comment" cols="45" rows="4" placeholder="' . _x( 'Comment *', 'noun', '__x__' ) . '" aria-required="true"></textarea>' .
'</p>'
) );
?>
</div>
</code></pre>
<p>But with using above code I will have these PHP notices in my published posts, above the comments area:</p>
<blockquote>
<pre><code>Notice: Trying to get property of non-object in /home/foo/public_html/wp-includes/comment-template.php on line 28
Notice: Trying to get property of non-object in /home/foo/public_html/wp-includes/comment-template.php on line 46
Notice: Trying to get property of non-object in /home/foo/public_html/wp-includes/comment-template.php on line 97
Notice: Trying to get property of non-object in /home/foo/public_html/wp-includes/comment-template.php on line 97
Notice: Trying to get property of non-object in /home/foo/public_html/wp-includes/comment-template.php on line 296
Notice: Trying to get property of non-object in /home/foo/public_html/wp-includes/comment-template.php on line 296
Notice: Trying to get property of non-object in /home/foo/public_html/wp-includes/comment-template.php on line 309
</code></pre>
</blockquote>
<p>While I know the problem is not inside of comment-template.php file.</p>
<p>How may I get rid of them?</p>
| [
{
"answer_id": 232460,
"author": "JMau",
"author_id": 31376,
"author_profile": "https://wordpress.stackexchange.com/users/31376",
"pm_score": 1,
"selected": false,
"text": "<p>This notice comes because object <code>$comments</code> is null. So the <code>have_comments()</code> must wrap a... | 2016/07/17 | [
"https://wordpress.stackexchange.com/questions/232435",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/62437/"
] | I need some customization of WORDPRESS comment area, so I've used this code in my child theme :
```
<div id="comments" class="x-comments-area">
<?php if ( have_comments() ) : ?>
<?php
//The author of current post
$author_ID = get_the_author_meta("ID");
//The current post ID
$p_ID = get_the_ID();
?>
<h2 class="h-comments-title"><span><?php _e( 'Comments' , '__x__' ); ?> <small>
<?php
//Number of guest comments
echo ztjalali_persian_num(number_format_i18n(count(get_comments(array('post_id' => $p_ID,'author__not_in' => array($author_ID))))));
?></small></span></h2>
<ol class="x-comments-list">
<?php
wp_list_comments( array(
'callback' => 'x_icon_comment',
'style' => 'ol'
) );
?>
</ol>
<?php if ( get_comment_pages_count() > 1 && get_option( 'page_comments' ) ) : ?>
<nav id="comment-nav-below" class="navigation" role="navigation">
<h1 class="visually-hidden"><?php _e( 'Comment navigation', '__x__' ); ?></h1>
<div class="nav-previous"><?php previous_comments_link( __( '← Older Comments', '__x__' ) ); ?></div>
<div class="nav-next"><?php next_comments_link( __( 'Newer Comments →', '__x__' ) ); ?></div>
</nav>
<?php endif; ?>
<?php if ( ! comments_open() && get_comments_number() ) : ?>
<p class="nocomments"><?php _e( 'Comments are closed.' , '__x__' ); ?></p>
<?php endif; ?>
<?php endif; ?>
<?php
//Loading of smilies
ob_start(); cs_print_smilies(); $cs_print_smilies = ob_get_clean();
//Comment form re-arrangement
comment_form( array(
'comment_notes_before' => '',
'comment_notes_after' => '',
'id_submit' => 'entry-comment-submit',
'label_submit' => __( 'Submit' , '__x__' ),
'title_reply' => __( '<span>Leave a Comment</span>' , '__x__' ),
'fields' => array(
'author' =>
'<p class="comment-form-author">' .
'<input id="author" name="author" type="text" value="' . get_comment_author() . '" placeholder="' . __( 'Name *', '__x__' ) . ' ' . '" size="30"/>' .
'</p>',
'email' =>
'<p class="comment-form-email">' .
'<input id="email" name="email" type="email" aria-required="true" aria-invalid="false" value="' .get_comment_author_email() . '" placeholder="' . __( 'Email *', '__x__' ) . ' ' . '" size="30"/>' .
'</p>',
'url' =>
'<p class="comment-form-url">' .
'<input id="url" name="url" type="text" value="' . get_comment_author_url() . '" placeholder="' . __( 'URL', '__x__' ) . '" size="30" />' .
'</p>'
),
'comment_field' => '<p class="comment-form-comment">' .
'</br>'.
$cs_print_smilies .
'<textarea id="comment" name="comment" cols="45" rows="4" placeholder="' . _x( 'Comment *', 'noun', '__x__' ) . '" aria-required="true"></textarea>' .
'</p>'
) );
?>
</div>
```
But with using above code I will have these PHP notices in my published posts, above the comments area:
>
>
> ```
> Notice: Trying to get property of non-object in /home/foo/public_html/wp-includes/comment-template.php on line 28
>
> Notice: Trying to get property of non-object in /home/foo/public_html/wp-includes/comment-template.php on line 46
>
> Notice: Trying to get property of non-object in /home/foo/public_html/wp-includes/comment-template.php on line 97
>
> Notice: Trying to get property of non-object in /home/foo/public_html/wp-includes/comment-template.php on line 97
>
> Notice: Trying to get property of non-object in /home/foo/public_html/wp-includes/comment-template.php on line 296
>
> Notice: Trying to get property of non-object in /home/foo/public_html/wp-includes/comment-template.php on line 296
>
> Notice: Trying to get property of non-object in /home/foo/public_html/wp-includes/comment-template.php on line 309
>
> ```
>
>
While I know the problem is not inside of comment-template.php file.
How may I get rid of them? | This notice comes because object `$comments` is null. So the `have_comments()` must wrap all the thing to be sure there are comments before using any property.
in your case :
```
<?php if ( have_comments() ) :
/* the code */
endif; ?>
``` |
232,436 | <p>So recently I moved a client from Blogger to Wordpress.</p>
<p>When the posts imported from blogger, it saved the blogger "labels" as "tags" in Wordpress. Since I'd like to have these as categories instead, I used a plugin to convert all tags to categories.</p>
<p>This worked fine and dandy, but it left Uncategorized on all of my posts. So now I have around 900 posts that all have their correct categories attached, as well as "Uncategorized".</p>
<p>So my goal is to remove "Uncategorized" from all 900 posts, but I'm struggling to find a speedy method to do this.</p>
<p>Does anyone know how I could accomplish this in a bulk method? </p>
| [
{
"answer_id": 232441,
"author": "Simon Cossar",
"author_id": 59349,
"author_profile": "https://wordpress.stackexchange.com/users/59349",
"pm_score": 3,
"selected": false,
"text": "<p>With <a href=\"https://wp-cli.org/\">wp-cli</a> installed you can run a bash script like this to remove ... | 2016/07/17 | [
"https://wordpress.stackexchange.com/questions/232436",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/75134/"
] | So recently I moved a client from Blogger to Wordpress.
When the posts imported from blogger, it saved the blogger "labels" as "tags" in Wordpress. Since I'd like to have these as categories instead, I used a plugin to convert all tags to categories.
This worked fine and dandy, but it left Uncategorized on all of my posts. So now I have around 900 posts that all have their correct categories attached, as well as "Uncategorized".
So my goal is to remove "Uncategorized" from all 900 posts, but I'm struggling to find a speedy method to do this.
Does anyone know how I could accomplish this in a bulk method? | With [wp-cli](https://wp-cli.org/) installed you can run a bash script like this to remove the 'uncategorized' category from all posts with more than one category
```
#!/bin/bash
for post in $(wp post list --field=ID)
do
count=$(wp post term list $post 'category' --fields='name' --format="count")
if [ "$count" -gt "1" ]
then
wp post term remove $post category 'uncategorized'
fi
done
```
Save this as something like `delete_uncategorized.bash` and then run `bash delete_uncategorized.bash` from the command line. |
232,462 | <p>I'm trying to return only pages in search results.</p>
<p>This is working:</p>
<p><code>/?s=term&post_type=post</code></p>
<p>It returns only posts, no pages.</p>
<p>But the opposite is not working:</p>
<p><code>/?s=term&post_type=page</code></p>
<p>This is returning pages and posts.</p>
<p>How do I return only pages?</p>
<p><strong>Edit</strong></p>
<p>Forgot to mention, so I'm trying to allow the ability for the user to click two links at the top of the search results page.</p>
<pre><code><a href="/?s=term&post_type=post">Search Only Posts</a>
<a href="/?s=term&post_type=page">Search Only Pages</a>
</code></pre>
<p>So, I can't just globally set all search results to only be one or the other.</p>
| [
{
"answer_id": 232467,
"author": "fuxia",
"author_id": 73,
"author_profile": "https://wordpress.stackexchange.com/users/73",
"pm_score": 3,
"selected": true,
"text": "<p>You can enforce a post type per callback on <code>pre_get_posts</code>:</p>\n\n<pre><code>is_admin() || add_action( 'p... | 2016/07/17 | [
"https://wordpress.stackexchange.com/questions/232462",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/75134/"
] | I'm trying to return only pages in search results.
This is working:
`/?s=term&post_type=post`
It returns only posts, no pages.
But the opposite is not working:
`/?s=term&post_type=page`
This is returning pages and posts.
How do I return only pages?
**Edit**
Forgot to mention, so I'm trying to allow the ability for the user to click two links at the top of the search results page.
```
<a href="/?s=term&post_type=post">Search Only Posts</a>
<a href="/?s=term&post_type=page">Search Only Pages</a>
```
So, I can't just globally set all search results to only be one or the other. | You can enforce a post type per callback on `pre_get_posts`:
```
is_admin() || add_action( 'pre_get_posts', function( \WP_Query $query ) {
$post_type = filter_input( INPUT_GET, 'post_type', FILTER_SANITIZE_STRING );
if ( $post_type && $query->is_main_query() && $query->is_search() )
$query->set( 'post_type', [ $post_type ] );
});
```
If that still includes other post types, you have a second callback registered on that hook. Try to find it; it might be a theme or plugin. |
232,465 | <p>I am trying to write a function to upload and delete images on frontend with dropzonejs uploader, and so far i managed to make everything work.</p>
<p>But the problem is that i need to secure it that the image that is deleting is actually uploaded by the user who is deleting image.</p>
<p>In wordpress admin area in media library when i click on image, in attachments details there is a <code>Uploaded by</code> with username who uploaded specific image.</p>
<p>But on searching all over the net and wordpress codex i didn't find any info how to retrieve user id who uploaded the image.</p>
<p>So id i have image id and try to delete with <code>wp_delete_attachment</code> is there a way to check who is the uploader of that image and compare logged in user id with image uploader id and if those two match delete the image.</p>
| [
{
"answer_id": 232467,
"author": "fuxia",
"author_id": 73,
"author_profile": "https://wordpress.stackexchange.com/users/73",
"pm_score": 3,
"selected": true,
"text": "<p>You can enforce a post type per callback on <code>pre_get_posts</code>:</p>\n\n<pre><code>is_admin() || add_action( 'p... | 2016/07/17 | [
"https://wordpress.stackexchange.com/questions/232465",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/21135/"
] | I am trying to write a function to upload and delete images on frontend with dropzonejs uploader, and so far i managed to make everything work.
But the problem is that i need to secure it that the image that is deleting is actually uploaded by the user who is deleting image.
In wordpress admin area in media library when i click on image, in attachments details there is a `Uploaded by` with username who uploaded specific image.
But on searching all over the net and wordpress codex i didn't find any info how to retrieve user id who uploaded the image.
So id i have image id and try to delete with `wp_delete_attachment` is there a way to check who is the uploader of that image and compare logged in user id with image uploader id and if those two match delete the image. | You can enforce a post type per callback on `pre_get_posts`:
```
is_admin() || add_action( 'pre_get_posts', function( \WP_Query $query ) {
$post_type = filter_input( INPUT_GET, 'post_type', FILTER_SANITIZE_STRING );
if ( $post_type && $query->is_main_query() && $query->is_search() )
$query->set( 'post_type', [ $post_type ] );
});
```
If that still includes other post types, you have a second callback registered on that hook. Try to find it; it might be a theme or plugin. |
232,471 | <p>In content I can have multiple shortcodes like <code>[book id="1"] [book id="14" page="243"]</code></p>
<p>Is there any help method with which I can search the content for that shortcode and get its parameters? I need to get IDs so I can call WP_Query and append the Custom Post Types titles at the end.</p>
<pre><code>function filter_books( $content ) {
// get all shortcodes IDs and other parameters if they exists
...
return $content;
}
add_filter( 'the_content', 'filter_books', 15 );
</code></pre>
<p>I tried using following code but var_dump($matches) is empty and if it would work I am not sure how would I get parameters (<a href="https://stackoverflow.com/questions/23205537/wordpress-shortcode-filtering-the-content-modifies-all-posts-in-a-list">https://stackoverflow.com/questions/23205537/wordpress-shortcode-filtering-the-content-modifies-all-posts-in-a-list</a>)</p>
<pre><code> $shortcode = 'book';
preg_match('/\['.$shortcode.'\]/s', $content, $matches);
</code></pre>
| [
{
"answer_id": 232648,
"author": "Marko",
"author_id": 47357,
"author_profile": "https://wordpress.stackexchange.com/users/47357",
"pm_score": 3,
"selected": true,
"text": "<p>This is working for me</p>\n\n<pre><code> $shortcode = 'book';\n $pattern = get_shortcode_regex();\n\n // if ... | 2016/07/17 | [
"https://wordpress.stackexchange.com/questions/232471",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/47357/"
] | In content I can have multiple shortcodes like `[book id="1"] [book id="14" page="243"]`
Is there any help method with which I can search the content for that shortcode and get its parameters? I need to get IDs so I can call WP\_Query and append the Custom Post Types titles at the end.
```
function filter_books( $content ) {
// get all shortcodes IDs and other parameters if they exists
...
return $content;
}
add_filter( 'the_content', 'filter_books', 15 );
```
I tried using following code but var\_dump($matches) is empty and if it would work I am not sure how would I get parameters (<https://stackoverflow.com/questions/23205537/wordpress-shortcode-filtering-the-content-modifies-all-posts-in-a-list>)
```
$shortcode = 'book';
preg_match('/\['.$shortcode.'\]/s', $content, $matches);
``` | This is working for me
```
$shortcode = 'book';
$pattern = get_shortcode_regex();
// if shortcode 'book' exists
if ( preg_match_all( '/'. $pattern .'/s', $post->post_content, $matches )
&& array_key_exists( 2, $matches )
&& in_array( $shortcode, $matches[2] ) ) {
$shortcode_atts = array_keys($matches[2], $shortcode);
// if shortcode has attributes
if (!empty($shortcode_atts)) {
foreach($shortcode_atts as $att) {
preg_match('/id="(\d+)"/', $matches[3][$att], $book_id);
// fill the id into main array
$book_ids[] = $book_id[1];
}
}
...
``` |
232,490 | <p>When I click on "older entries" in my home page, it goes to a second link but it shows the same posts. I think I need to modify something in the <code>index.php</code>, this is the full code section that I think I need to modify:</p>
<pre><code><div class="container">
<div class="post_content">
<div class="home_posts">
<?php
$args2 = array(
'post_type' => 'post',
'posts_per_page' => 10,
'paged' => ( get_query_var('paged') ? get_query_var('paged') : 2),
);
$query = new WP_Query( $args2 );
if ( $query->have_posts() ) :
while ( $query->have_posts() ) : $query->the_post();
echo '<div class="grid_post">
<h3><a href="'.get_permalink().'">'.get_the_title().'</a></h3>';
$type = get_post_meta($post->ID,'page_featured_type',true);
switch ($type) {
case 'youtube':
echo '<iframe width="560" height="315" src="http://www.youtube.com/embed/'.get_post_meta( get_the_ID(), 'page_video_id', true ).'?wmode=transparent" frameborder="0" allowfullscreen></iframe>';
break;
case 'vimeo':
echo '<iframe src="http://player.vimeo.com/video/'.get_post_meta( get_the_ID(), 'page_video_id', true ).'?title=0&amp;byline=0&amp;portrait=0&amp;color=03b3fc" width="500" height="338" frameborder="0" webkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe>';
break;
default:
echo '<div class="grid_post_img">
<a href="'.get_permalink().'">'.get_the_post_thumbnail().'</a>
</div>';
break;
}
echo '<div class="grid_home_posts">
<p>'.dess_get_excerpt(120).'</p>
</div>
</div>
';
endwhile;
?>
</div>
<?php
echo '<div class="load_more_content"><div class="load_more_text">';
ob_start();
next_posts_link('LOAD MORE',$query->max_num_pages);
$buffer = ob_get_contents();
ob_end_clean();
if(!empty($buffer)) echo $buffer;
echo'</div></div>';
$max_pages = $query->max_num_pages;
wp_reset_postdata();
endif;
?>
<span id="max-pages" style="display:none"><?php echo $max_pages ?></span>
</div>
<?php get_sidebar(); ?>
<div class="clear"></div>
</div>
</div>
</code></pre>
<p>Could it be here: </p>
<pre><code><?php
$args2 = array(
'post_type' => 'post',
'posts_per_page' => 6,
'paged' => ( get_query_var('paged') ? get_query_var('paged') : 1),
);
$query = new WP_Query( $args2 );
if ( $query->have_posts() ) :
while ( $query->have_posts() ) : $query->the_post();
echo '<div class="grid_post">
</code></pre>
<p>This is the URL to "Older entries": <a href="http://www.wha2wear.com/page/2/" rel="nofollow">http://www.wha2wear.com/page/2/</a> that shows the same content as the homepage. Also, I don't really see that "Older entries" is written somewhere in the code..</p>
<p>Also, in the actual page, Front Page page, there is this code</p>
<pre><code>[posts-for-page order_by ='date' hide_images='false' num='11' read_more='
Read More »' show_full_posts='false' use_wp_excerpt='true' strip_html='true' hide_post_content='false' show_meta='false' force_image_height='200' force_image_width='250']
</code></pre>
<p><strong>I have the feeling that this code has higher priority than the php, so the homepage does what it says there?</strong></p>
| [
{
"answer_id": 232922,
"author": "majick",
"author_id": 76440,
"author_profile": "https://wordpress.stackexchange.com/users/76440",
"pm_score": 0,
"selected": false,
"text": "<p>If the posts are being displayed via a static front page (they seem to be?) then you need to use the query par... | 2016/07/18 | [
"https://wordpress.stackexchange.com/questions/232490",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/91761/"
] | When I click on "older entries" in my home page, it goes to a second link but it shows the same posts. I think I need to modify something in the `index.php`, this is the full code section that I think I need to modify:
```
<div class="container">
<div class="post_content">
<div class="home_posts">
<?php
$args2 = array(
'post_type' => 'post',
'posts_per_page' => 10,
'paged' => ( get_query_var('paged') ? get_query_var('paged') : 2),
);
$query = new WP_Query( $args2 );
if ( $query->have_posts() ) :
while ( $query->have_posts() ) : $query->the_post();
echo '<div class="grid_post">
<h3><a href="'.get_permalink().'">'.get_the_title().'</a></h3>';
$type = get_post_meta($post->ID,'page_featured_type',true);
switch ($type) {
case 'youtube':
echo '<iframe width="560" height="315" src="http://www.youtube.com/embed/'.get_post_meta( get_the_ID(), 'page_video_id', true ).'?wmode=transparent" frameborder="0" allowfullscreen></iframe>';
break;
case 'vimeo':
echo '<iframe src="http://player.vimeo.com/video/'.get_post_meta( get_the_ID(), 'page_video_id', true ).'?title=0&byline=0&portrait=0&color=03b3fc" width="500" height="338" frameborder="0" webkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe>';
break;
default:
echo '<div class="grid_post_img">
<a href="'.get_permalink().'">'.get_the_post_thumbnail().'</a>
</div>';
break;
}
echo '<div class="grid_home_posts">
<p>'.dess_get_excerpt(120).'</p>
</div>
</div>
';
endwhile;
?>
</div>
<?php
echo '<div class="load_more_content"><div class="load_more_text">';
ob_start();
next_posts_link('LOAD MORE',$query->max_num_pages);
$buffer = ob_get_contents();
ob_end_clean();
if(!empty($buffer)) echo $buffer;
echo'</div></div>';
$max_pages = $query->max_num_pages;
wp_reset_postdata();
endif;
?>
<span id="max-pages" style="display:none"><?php echo $max_pages ?></span>
</div>
<?php get_sidebar(); ?>
<div class="clear"></div>
</div>
</div>
```
Could it be here:
```
<?php
$args2 = array(
'post_type' => 'post',
'posts_per_page' => 6,
'paged' => ( get_query_var('paged') ? get_query_var('paged') : 1),
);
$query = new WP_Query( $args2 );
if ( $query->have_posts() ) :
while ( $query->have_posts() ) : $query->the_post();
echo '<div class="grid_post">
```
This is the URL to "Older entries": <http://www.wha2wear.com/page/2/> that shows the same content as the homepage. Also, I don't really see that "Older entries" is written somewhere in the code..
Also, in the actual page, Front Page page, there is this code
```
[posts-for-page order_by ='date' hide_images='false' num='11' read_more='
Read More »' show_full_posts='false' use_wp_excerpt='true' strip_html='true' hide_post_content='false' show_meta='false' force_image_height='200' force_image_width='250']
```
**I have the feeling that this code has higher priority than the php, so the homepage does what it says there?** | Why don't you try with default query and use like this
```
if ( get_query_var('paged') ) { $paged = get_query_var('paged'); }
elseif ( get_query_var('page') ) { $paged = get_query_var('page'); }
else { $paged = 1; }
$args = array(
'post_type' => 'post',
'posts_per_page' => 6,
'paged' => $paged,
);
query_posts($args); while (have_posts()): the_post();
// do something
endwhile;
```
See here more details about Adding the "paged" parameter to a query
<https://codex.wordpress.org/Pagination#Adding_the_.22paged.22_parameter_to_a_query> |
232,498 | <p>I am currently working on <a href="http://www.highereg.com/member-list/starr-mazer" rel="nofollow noreferrer">this website</a> which uses a Wordpress theme designed by one Themeforest author. As can be seen via the link and the following screenshot from the same page, the theme's Portfolio (Custom Post Type) utilises 8 columns for textual and any other data -- with 4 other other columns to its right used in rendering a meta-box.</p>
<p><a href="https://i.stack.imgur.com/vJORp.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vJORp.png" alt="The space bordered in Orange is empty and unused."></a></p>
<p>My issue is largely with the blank space under the meta-box. The page's design is such that while only a portion of those 4 columns are used for the box, the rest of that space beneath it goes unused.</p>
<p>I am looking to amend this design; I'd like to fit in other plugins (a Newsletter sign up box, for instance) below the meta-box in the space bordered in Orange and am unsure on what would be the best way to go about it.</p>
<p>The theme author is also unresponsive which rules out asking them about the same. The code used in the design of the pictured portion of the page is as follows -- </p>
<pre><code><div class="large-12 medium-12 columns">
<h2 class="portfolio-detail-title"><?php the_title(); ?></h2>
</div>
<div class="portfolio-detail-left large-8 medium-8 columns">
<div class="portfolio-detail-text">
<?php while ( have_posts() ) : the_post(); ?>
<?php the_content(); ?>
<?php endwhile; // end of the loop. ?>
</div>
</div>
<div class="portfolio-detail-right large-4 medium-4 columns ">
<div class="portfolio-detail-inner">
<div class="portfolio-detail">
<div class="portfolio-detail-content"><i class="fa fa-tag"></i> <span><?php the_terms( get_the_ID(), 'portfolio_categories' ); ?></span></div>
<div class="portfolio-detail-content"><i class="fa fa-user"></i> <span><?php echo esc_attr( $portfolio_client ) ?></span></div>
<div class="portfolio-detail-content"><i class="fa fa-home"></i> <span><?php echo esc_attr( $portfolio_location ) ?></span></div>
<div class="portfolio-detail-content"><i class="fa fa-bookmark-o"></i> <span><?php echo esc_attr( $portfolio_skills ) ?></span></div>
<div class="portfolio-detail-content"><i class="fa fa-cogs gears"></i> <span><?php echo esc_attr( $portfolio_rates ) ?></span></div>
<div class="portfolio-detail-url"><i class="fa fa-chain"></i> <a href="<?php echo esc_url( $portfolio_url ) ?>"><span><?php echo esc_url( $portfolio_url ) ?></span></a></div>
<div class="portfolio-detail-content"><i class="fa fa-facebook"></i> <span><?php echo '<a href="esc_attr( $portfolio_rates )"></a>' ?></span></div>
</div>
</div>
</div>
</div>
</code></pre>
<p>Is there any plausible way to render that blank space usable?</p>
<p>Thank you.</p>
| [
{
"answer_id": 232499,
"author": "tillinberlin",
"author_id": 26059,
"author_profile": "https://wordpress.stackexchange.com/users/26059",
"pm_score": 0,
"selected": false,
"text": "<p>Short answer: most probably there is.</p>\n\n<p>I would recommend you use a child theme to achieve this.... | 2016/07/18 | [
"https://wordpress.stackexchange.com/questions/232498",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/98478/"
] | I am currently working on [this website](http://www.highereg.com/member-list/starr-mazer) which uses a Wordpress theme designed by one Themeforest author. As can be seen via the link and the following screenshot from the same page, the theme's Portfolio (Custom Post Type) utilises 8 columns for textual and any other data -- with 4 other other columns to its right used in rendering a meta-box.
[](https://i.stack.imgur.com/vJORp.png)
My issue is largely with the blank space under the meta-box. The page's design is such that while only a portion of those 4 columns are used for the box, the rest of that space beneath it goes unused.
I am looking to amend this design; I'd like to fit in other plugins (a Newsletter sign up box, for instance) below the meta-box in the space bordered in Orange and am unsure on what would be the best way to go about it.
The theme author is also unresponsive which rules out asking them about the same. The code used in the design of the pictured portion of the page is as follows --
```
<div class="large-12 medium-12 columns">
<h2 class="portfolio-detail-title"><?php the_title(); ?></h2>
</div>
<div class="portfolio-detail-left large-8 medium-8 columns">
<div class="portfolio-detail-text">
<?php while ( have_posts() ) : the_post(); ?>
<?php the_content(); ?>
<?php endwhile; // end of the loop. ?>
</div>
</div>
<div class="portfolio-detail-right large-4 medium-4 columns ">
<div class="portfolio-detail-inner">
<div class="portfolio-detail">
<div class="portfolio-detail-content"><i class="fa fa-tag"></i> <span><?php the_terms( get_the_ID(), 'portfolio_categories' ); ?></span></div>
<div class="portfolio-detail-content"><i class="fa fa-user"></i> <span><?php echo esc_attr( $portfolio_client ) ?></span></div>
<div class="portfolio-detail-content"><i class="fa fa-home"></i> <span><?php echo esc_attr( $portfolio_location ) ?></span></div>
<div class="portfolio-detail-content"><i class="fa fa-bookmark-o"></i> <span><?php echo esc_attr( $portfolio_skills ) ?></span></div>
<div class="portfolio-detail-content"><i class="fa fa-cogs gears"></i> <span><?php echo esc_attr( $portfolio_rates ) ?></span></div>
<div class="portfolio-detail-url"><i class="fa fa-chain"></i> <a href="<?php echo esc_url( $portfolio_url ) ?>"><span><?php echo esc_url( $portfolio_url ) ?></span></a></div>
<div class="portfolio-detail-content"><i class="fa fa-facebook"></i> <span><?php echo '<a href="esc_attr( $portfolio_rates )"></a>' ?></span></div>
</div>
</div>
</div>
</div>
```
Is there any plausible way to render that blank space usable?
Thank you. | Why don't you create a [shortcode](https://codex.wordpress.org/Shortcode_API) for this , it's much easier, standard and flexible. |
232,513 | <p>I want to use Pagination using ajax for custom post taxonomy.
Many of codes are tried by me but at the last I was failed. So,how can i use pagination using ajax without plugin?</p>
<p>When i am clicking on load more button then the post will load on the same page.</p>
<p><strong>post name:- project</strong></p>
<p><strong>taxonomy name:- framework</strong></p>
<p><strong><code>functions.php</code></strong></p>
<pre class="lang-php prettyprint-override"><code> function wp_pagination() {
global $wp_query;
$big = 12345678;
$page_format = paginate_links(array(
'base' => str_replace($big, '%#%', esc_url(get_pagenum_link($big))),
'format' => '?paged=%#%',
'current' => max(1, get_query_var('paged')),
'total' => $wp_query->max_num_pages,
'type' => 'array'
));
if (is_array($page_format)) {
$paged = ( get_query_var('paged') == 0 ) ? 1 :
get_query_var('paged');
// echo '<div><ul>';
// echo '<li><span>'. $paged . ' of ' . $wp_query->max_num_pages.'</span></li>';
echo "<center>";
foreach ($page_format as $page) {
echo " " . $page;
}
echo "</center>";
echo '</div>';
}
}
</code></pre>
| [
{
"answer_id": 232711,
"author": "jayesh",
"author_id": 98495,
"author_profile": "https://wordpress.stackexchange.com/users/98495",
"pm_score": 4,
"selected": true,
"text": "<p>I had got the ans.</p>\n\n<p>First you have to add following code in your function.php to call ajax in your tem... | 2016/07/18 | [
"https://wordpress.stackexchange.com/questions/232513",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/98495/"
] | I want to use Pagination using ajax for custom post taxonomy.
Many of codes are tried by me but at the last I was failed. So,how can i use pagination using ajax without plugin?
When i am clicking on load more button then the post will load on the same page.
**post name:- project**
**taxonomy name:- framework**
**`functions.php`**
```php
function wp_pagination() {
global $wp_query;
$big = 12345678;
$page_format = paginate_links(array(
'base' => str_replace($big, '%#%', esc_url(get_pagenum_link($big))),
'format' => '?paged=%#%',
'current' => max(1, get_query_var('paged')),
'total' => $wp_query->max_num_pages,
'type' => 'array'
));
if (is_array($page_format)) {
$paged = ( get_query_var('paged') == 0 ) ? 1 :
get_query_var('paged');
// echo '<div><ul>';
// echo '<li><span>'. $paged . ' of ' . $wp_query->max_num_pages.'</span></li>';
echo "<center>";
foreach ($page_format as $page) {
echo " " . $page;
}
echo "</center>";
echo '</div>';
}
}
``` | I had got the ans.
First you have to add following code in your function.php to call ajax in your template\*\*
```
add_action( 'wp_ajax_demo-pagination-load-posts', 'cvf_demo_pagination_load_posts' );
add_action( 'wp_ajax_nopriv_demo-pagination-load-posts', 'cvf_demo_pagination_load_posts' );
function cvf_demo_pagination_load_posts() {
global $wpdb;
// Set default variables
$msg = '';
if(isset($_POST['page'])){
// Sanitize the received page
$page = sanitize_text_field($_POST['page']);
$cur_page = $page;
$page -= 1;
// Set the number of results to display
$per_page = 3;
$previous_btn = true;
$next_btn = true;
$first_btn = true;
$last_btn = true;
$start = $page * $per_page;
// Set the table where we will be querying data
$table_name = $wpdb->prefix . "posts";
// Query the necessary posts
$all_blog_posts = $wpdb->get_results($wpdb->prepare("
SELECT * FROM " . $table_name . " WHERE post_type = 'post' AND post_status = 'publish' ORDER BY post_date DESC LIMIT %d, %d", $start, $per_page ) );
// At the same time, count the number of queried posts
$count = $wpdb->get_var($wpdb->prepare("
SELECT COUNT(ID) FROM " . $table_name . " WHERE post_type = 'post' AND post_status = 'publish'", array() ) );
/**
* Use WP_Query:
*
$all_blog_posts = new WP_Query(
array(
'post_type' => 'post',
'post_status ' => 'publish',
'orderby' => 'post_date',
'order' => 'DESC',
'posts_per_page' => $per_page,
'offset' => $start
)
);
$count = new WP_Query(
array(
'post_type' => 'post',
'post_status ' => 'publish',
'posts_per_page' => -1
)
);
*/
// Loop into all the posts
foreach($all_blog_posts as $key => $post):
// Set the desired output into a variable
$msg .= '
<div class = "col-md-12">
<h2><a href="' . get_permalink($post->ID) . '">' . $post->post_title . '</a></h2>
<p>' . $post->post_excerpt . '</p>
<p>' . $post->post_content . '</p>
</div>';
endforeach;
// Optional, wrap the output into a container
$msg = "<div class='cvf-universal-content'>" . $msg . "</div><br class = 'clear' />";
// This is where the magic happens
$no_of_paginations = ceil($count / $per_page);
if ($cur_page >= 7) {
$start_loop = $cur_page - 3;
if ($no_of_paginations > $cur_page + 3)
$end_loop = $cur_page + 3;
else if ($cur_page <= $no_of_paginations && $cur_page > $no_of_paginations - 6) {
$start_loop = $no_of_paginations - 6;
$end_loop = $no_of_paginations;
} else {
$end_loop = $no_of_paginations;
}
} else {
$start_loop = 1;
if ($no_of_paginations > 7)
$end_loop = 7;
else
$end_loop = $no_of_paginations;
}
// Pagination Buttons logic
$pag_container .= "
<div class='cvf-universal-pagination'>
<ul>";
if ($first_btn && $cur_page > 1) {
$pag_container .= "<li p='1' class='active'>First</li>";
} else if ($first_btn) {
$pag_container .= "<li p='1' class='inactive'>First</li>";
}
if ($previous_btn && $cur_page > 1) {
$pre = $cur_page - 1;
$pag_container .= "<li p='$pre' class='active'>Previous</li>";
} else if ($previous_btn) {
$pag_container .= "<li class='inactive'>Previous</li>";
}
for ($i = $start_loop; $i <= $end_loop; $i++) {
if ($cur_page == $i)
$pag_container .= "<li p='$i' class = 'selected' >{$i}</li>";
else
$pag_container .= "<li p='$i' class='active'>{$i}</li>";
}
if ($next_btn && $cur_page < $no_of_paginations) {
$nex = $cur_page + 1;
$pag_container .= "<li p='$nex' class='active'>Next</li>";
} else if ($next_btn) {
$pag_container .= "<li class='inactive'>Next</li>";
}
if ($last_btn && $cur_page < $no_of_paginations) {
$pag_container .= "<li p='$no_of_paginations' class='active'>Last</li>";
} else if ($last_btn) {
$pag_container .= "<li p='$no_of_paginations' class='inactive'>Last</li>";
}
$pag_container = $pag_container . "
</ul>
</div>";
// We echo the final output
echo
'<div class = "cvf-pagination-content">' . $msg . '</div>' .
'<div class = "cvf-pagination-nav">' . $pag_container . '</div>';
}
// Always exit to avoid further execution
exit();}
```
Now add this following code where you want to display your post.(like,index.php,home.php,etc..)
```
<div class="col-md-12 content">
<div class = "inner-box content no-right-margin darkviolet">
<script type="text/javascript">
jQuery(document).ready(function($) {
// This is required for AJAX to work on our page
var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
function cvf_load_all_posts(page){
// Start the transition
$(".cvf_pag_loading").fadeIn().css('background','#ccc');
// Data to receive from our server
// the value in 'action' is the key that will be identified by the 'wp_ajax_' hook
var data = {
page: page,
action: "demo-pagination-load-posts"
};
// Send the data
$.post(ajaxurl, data, function(response) {
// If successful Append the data into our html container
$(".cvf_universal_container").append(response);
// End the transition
$(".cvf_pag_loading").css({'background':'none', 'transition':'all 1s ease-out'});
});
}
// Load page 1 as the default
cvf_load_all_posts(1);
// Handle the clicks
$('.cvf_universal_container .cvf-universal-pagination li.active').live('click',function(){
var page = $(this).attr('p');
cvf_load_all_posts(page);
});
});
</script>
<div class = "cvf_pag_loading">
<div class = "cvf_universal_container">
<div class="cvf-universal-content"></div>
</div>
</div>
</div>
</div>
```
And at the last put this code into your style.css
```
.cvf_pag_loading {padding: 20px;}
.cvf-universal-pagination ul {margin: 0; padding: 0;}
.cvf-universal-pagination ul li {display: inline; margin: 3px; padding: 4px 8px; background: #FFF; color: black; }
.cvf-universal-pagination ul li.active:hover {cursor: pointer; background: #1E8CBE; color: white; }
.cvf-universal-pagination ul li.inactive {background: #7E7E7E;}
.cvf-universal-pagination ul li.selected {background: #1E8CBE; color: white;}
```
At the last you will see like this.
[](https://i.stack.imgur.com/eFu2O.png) |
232,527 | <p>I have set up a fresh installation of WordPress 4.5.3 and activated the Multisite feature, following all the instructions required to activate it.</p>
<p>I added a second site, and once it was created I tried clicking on the dashboard for the second site but it directs me to the first site dashboard, everytime!</p>
<p>I tried to visit the second link I made - for instance <code>www.example.com/ar</code> - and it shows the website without the theme and with the wrong links. Again I try to go back and edit it; again it redirects me to the main site.</p>
<p>What can I do to resolve this?</p>
<p>My domain is registered through GoDaddy.</p>
| [
{
"answer_id": 232571,
"author": "Pat J",
"author_id": 16121,
"author_profile": "https://wordpress.stackexchange.com/users/16121",
"pm_score": 1,
"selected": false,
"text": "<p>Make sure you've set up your rewrite rules in your <code>.htaccess</code> file. The Multisite rules are differe... | 2016/07/18 | [
"https://wordpress.stackexchange.com/questions/232527",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/98503/"
] | I have set up a fresh installation of WordPress 4.5.3 and activated the Multisite feature, following all the instructions required to activate it.
I added a second site, and once it was created I tried clicking on the dashboard for the second site but it directs me to the first site dashboard, everytime!
I tried to visit the second link I made - for instance `www.example.com/ar` - and it shows the website without the theme and with the wrong links. Again I try to go back and edit it; again it redirects me to the main site.
What can I do to resolve this?
My domain is registered through GoDaddy. | Make sure you've set up your rewrite rules in your `.htaccess` file. The Multisite rules are different from the default WordPress rules.
If this is an up-to-date version of WordPress, your `.htaccess` rewrite rules should look like this:
Subdirectory
------------
```
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]
```
Subdomain
---------
```
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
# add a trailing slash to /wp-admin
RewriteRule ^wp-admin$ wp-admin/ [R=301,L]
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]
RewriteRule ^(wp-(content|admin|includes).*) $1 [L]
RewriteRule ^(.*\.php)$ $1 [L]
RewriteRule . index.php [L]
```
See the [Codex page on `.htaccess`](https://codex.wordpress.org/htaccess) for more details. |
232,600 | <p>I'm trying to get the <code>current-menu-item-id</code> in any page.
I have used <a href="https://wordpress.stackexchange.com/questions/16243/how-to-get-current-menu-item-title-as-variable">this solution</a>, that brings me very close to the solution.</p>
<p>The problem I have is, that the function below is going through all the menus on the page, and not only the one specific menu, that I want it to go through:</p>
<pre><code>add_filter( 'wp_nav_menu_objects', 'wpse16243_wp_nav_menu_objects' );
function wpse16243_wp_nav_menu_objects( $sorted_menu_items )
{
foreach ( $sorted_menu_items as $menu_item ) {
if ( $menu_item->current ) {
$GLOBALS['wpse16243_title'] = $menu_item->ID;
}
}
return $sorted_menu_items;
}
</code></pre>
<p>...which means that if you link to the same page more than once in your menus, you can risk that this function returns the <code>current-menu-item-id</code> from the wrong menu.</p>
<p>Is there any way that I can limit this function to <strong>only</strong> go through a specific menu and not all menus?
I tried to pass the specific menu items in the variable/parameter <code>$sorted_menu_items</code>, but that seems not to work.</p>
| [
{
"answer_id": 232581,
"author": "ngearing",
"author_id": 50184,
"author_profile": "https://wordpress.stackexchange.com/users/50184",
"pm_score": 4,
"selected": true,
"text": "<p>Yes!</p>\n\n<ol>\n<li>Go to your Media Library </li>\n<li>Find the Image </li>\n<li>Click Edit </li>\n<li>Lo... | 2016/07/19 | [
"https://wordpress.stackexchange.com/questions/232600",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/97806/"
] | I'm trying to get the `current-menu-item-id` in any page.
I have used [this solution](https://wordpress.stackexchange.com/questions/16243/how-to-get-current-menu-item-title-as-variable), that brings me very close to the solution.
The problem I have is, that the function below is going through all the menus on the page, and not only the one specific menu, that I want it to go through:
```
add_filter( 'wp_nav_menu_objects', 'wpse16243_wp_nav_menu_objects' );
function wpse16243_wp_nav_menu_objects( $sorted_menu_items )
{
foreach ( $sorted_menu_items as $menu_item ) {
if ( $menu_item->current ) {
$GLOBALS['wpse16243_title'] = $menu_item->ID;
}
}
return $sorted_menu_items;
}
```
...which means that if you link to the same page more than once in your menus, you can risk that this function returns the `current-menu-item-id` from the wrong menu.
Is there any way that I can limit this function to **only** go through a specific menu and not all menus?
I tried to pass the specific menu items in the variable/parameter `$sorted_menu_items`, but that seems not to work. | Yes!
1. Go to your Media Library
2. Find the Image
3. Click Edit
4. Locate the Permalink under the Title
5. Click Edit
6. Change the Permalink
7. Click Update!
Edit
----
If for some reason you cannot Edit the Images' Permalink... you could:
1. Delete Image
2. Change your Pages' Permalink
3. Re-Upload Image |
232,610 | <p>I have the following code:-</p>
<pre><code><!-- News Archive -->
<div id="news-archive">
<div class="row">
<div class="col-md-12">
<?php
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$args = array(
'post_type' => 'post',
'orderby' => 'title',
'order' => 'ASC',
'cat' => '8',
'offset' => 2,
'posts_per_page' => 6,
'paged' => $paged
);
$loop = new WP_Query($args);
$post_counter = 1;
while ( $loop->have_posts() ) : $loop->the_post(); ?>
<div class="col-xs-12 col-sm-4 col-md-4">
<div id="blog-<?php echo $post_counter; ?>" class="blog-wrapper">
<?php if(get_the_post_thumbnail()) {
the_post_thumbnail();
} else {
$category = "/wp-content/themes/irongate/assets/img/" . get_field('group_category') . '-default.jpg'; ?>
<img src="<?php echo $category; ?>" />
<?php } ?>
<span class="news-archive-date"><?php echo get_the_date('d M Y'); ?></span>
<p class="news-archive-title"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></p>
<span id="<?php echo $case_category; ?>-logo" class="<?php echo get_field('group_category') == 'inone' ? 'inone-catergory' : 'news-archive-catergory';?>"></span>
<a href="<?php the_permalink(); ?>">
<div class="news-overlay blog-overlay">
<span class="news-overlay-excerpt"><?php echo substr(get_the_excerpt(), 0,240); ?>...</span>
<span id="careers-overlay-more" class="btn-white">Read more</span>
</div>
</a>
</div>
</div>
<?php if($post_counter % 3 == 0) {echo '<div class="clearfix"></div>';}
$post_counter++;
endwhile; ?><!-- News Archive -->
<div class="navigation">
<div class="alignleft"><?php previous_posts_link('&laquo; Previous') ?></div>
<div class="alignright"><?php next_posts_link('More &raquo;') ?></div>
</div>
<?php wp_reset_postdata(); ?>
</div>
</div>
</div>
</code></pre>
<p>The display of the posts is showing correctly as 6 blog posts and the 'More...' button appears but when clicked it just reloads the same content.</p>
<p>How can I add pagination to my blog posts? i.e. clicking next... will show posts 9-14 instead of 2-8 (as I'm using an offset of 2).</p>
<p>Thanks in advance!</p>
| [
{
"answer_id": 232970,
"author": "wpclevel",
"author_id": 92212,
"author_profile": "https://wordpress.stackexchange.com/users/92212",
"pm_score": 3,
"selected": true,
"text": "<p>You can calculate <code>offset</code> via <code>paged</code> and <code>posts_per_page</code>. E.g:</p>\n\n<pr... | 2016/07/19 | [
"https://wordpress.stackexchange.com/questions/232610",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/81966/"
] | I have the following code:-
```
<!-- News Archive -->
<div id="news-archive">
<div class="row">
<div class="col-md-12">
<?php
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$args = array(
'post_type' => 'post',
'orderby' => 'title',
'order' => 'ASC',
'cat' => '8',
'offset' => 2,
'posts_per_page' => 6,
'paged' => $paged
);
$loop = new WP_Query($args);
$post_counter = 1;
while ( $loop->have_posts() ) : $loop->the_post(); ?>
<div class="col-xs-12 col-sm-4 col-md-4">
<div id="blog-<?php echo $post_counter; ?>" class="blog-wrapper">
<?php if(get_the_post_thumbnail()) {
the_post_thumbnail();
} else {
$category = "/wp-content/themes/irongate/assets/img/" . get_field('group_category') . '-default.jpg'; ?>
<img src="<?php echo $category; ?>" />
<?php } ?>
<span class="news-archive-date"><?php echo get_the_date('d M Y'); ?></span>
<p class="news-archive-title"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></p>
<span id="<?php echo $case_category; ?>-logo" class="<?php echo get_field('group_category') == 'inone' ? 'inone-catergory' : 'news-archive-catergory';?>"></span>
<a href="<?php the_permalink(); ?>">
<div class="news-overlay blog-overlay">
<span class="news-overlay-excerpt"><?php echo substr(get_the_excerpt(), 0,240); ?>...</span>
<span id="careers-overlay-more" class="btn-white">Read more</span>
</div>
</a>
</div>
</div>
<?php if($post_counter % 3 == 0) {echo '<div class="clearfix"></div>';}
$post_counter++;
endwhile; ?><!-- News Archive -->
<div class="navigation">
<div class="alignleft"><?php previous_posts_link('« Previous') ?></div>
<div class="alignright"><?php next_posts_link('More »') ?></div>
</div>
<?php wp_reset_postdata(); ?>
</div>
</div>
</div>
```
The display of the posts is showing correctly as 6 blog posts and the 'More...' button appears but when clicked it just reloads the same content.
How can I add pagination to my blog posts? i.e. clicking next... will show posts 9-14 instead of 2-8 (as I'm using an offset of 2).
Thanks in advance! | You can calculate `offset` via `paged` and `posts_per_page`. E.g:
```
$per_page = 6;
$paged = get_query_var('paged') ? : 1;
$offset = (1 === $paged) ? 0 : (($paged - 1) * $per_page) + (($paged - 1) * 2);
$args = array(
'order' => 'ASC',
'paged' => $paged,
'offset' => $offset,
'orderby' => 'ID',
'post_type' => 'post',
'post_status' => 'publish',
'posts_per_page' => $per_page,
'ignore_sticky_posts' => 1
);
$query = new WP_Query($args);
while ( $query->have_posts() ) : $query->the_post();
echo get_the_title() . '<br>';
endwhile;
previous_posts_link('« Previous', $query->max_num_pages);
if ($paged > 1) echo ' | ';
next_posts_link('More »', $query->max_num_pages);
echo '<br> Showing ' . $offset . '-' . ($offset + 6) . ' of ' . $query->found_posts . ' posts.';
wp_reset_postdata();
```
Note that the loop start at index 0, so if we ignore sticky posts and only display 6 posts per page, the result on page 2 should be 8-14 instead 9-14 as you expected. |
232,663 | <p>I am trying to post to WordPress using the REST API. The aim is to have a form that accepts The following information:</p>
<ul>
<li>Title</li>
<li>Content</li>
<li>ACF Custom Field 1 (possibly repeater field)</li>
<li>ACF Custom Field 2 (possibly repeater field)</li>
<li>Featured Image</li>
</ul>
<p>I am new to the WP API and am having some difficulty finding some solid documentation on how I could post to a WP site from an external page/site that is not WordPress. </p>
<p>The idea is that users of website 'a' can fill out a form and this create a post on website 'b'. </p>
<p>I am not sure on user authentication as of yet so will either post annonymously or with a single user account.</p>
<p>Is anyone able to show me a simple method showing a basic outline of the above using Javascript or point me in the right direction atleast as I have found the docs a little confusing.</p>
| [
{
"answer_id": 232664,
"author": "whakawaehere",
"author_id": 78660,
"author_profile": "https://wordpress.stackexchange.com/users/78660",
"pm_score": -1,
"selected": false,
"text": "<p>I think the simplest solution, without having more details about site A or site B, would be to use a se... | 2016/07/19 | [
"https://wordpress.stackexchange.com/questions/232663",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/64567/"
] | I am trying to post to WordPress using the REST API. The aim is to have a form that accepts The following information:
* Title
* Content
* ACF Custom Field 1 (possibly repeater field)
* ACF Custom Field 2 (possibly repeater field)
* Featured Image
I am new to the WP API and am having some difficulty finding some solid documentation on how I could post to a WP site from an external page/site that is not WordPress.
The idea is that users of website 'a' can fill out a form and this create a post on website 'b'.
I am not sure on user authentication as of yet so will either post annonymously or with a single user account.
Is anyone able to show me a simple method showing a basic outline of the above using Javascript or point me in the right direction atleast as I have found the docs a little confusing. | To answer your broader question about resources - while there are many articles out there, I would always recommend checking out the official [WordPress API Handbook](https://developer.wordpress.org/rest-api/reference/posts/) first.
You first have to decide which JavaScript library you want to use to make HTTP requests to access the REST API. Axios is one example.
To set the featured image, you first have to uploaded it as media (which you can do via the REST API) and then include the media id in the post request (more details below).
Then to create the post via the REST API, you would make a `POST` HTTP request to `https:/<your-site>/wp-json/wp/v2/posts` with a body like:
```
{
content: 'My post content here',
title: 'Post Title',
featured_media: [image-media-id],
status: 'publish' // or 'draft'
}
```
To get the ACF Custom Fields accessible/editable via the REST API, check out this plugin: <https://github.com/airesvsg/acf-to-rest-api/>. I haven't used it yet, but it seems like what you're looking for.
Also be aware that if site 'a' is on a different domain than site 'b', you may have [CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS) issues to deal with as well. WordPress has good guides for dealing with that. |
232,675 | <p>I am trying to figure out how to add user information and specific meta data to a separate table through PHP. I would prefer to do this when a user posted to the <code>wp_users</code> and <code>wp_usermeta</code> table. I am using the WooCommerce Auction plugin and the Salient theme.</p>
<p>Also if I made a PHP file that ran a query to pull the data and then insert, where is a good place I can call that function to ensure the table is up to date?</p>
<p>This is the function I've created.</p>
<pre><code>add_action('user_register', 'save_to_donors',10,1);
function save_to_donors( $user_id ) {
$single = true;
$user_email = get_userdata($user_id);
$fn= get_user_meta($user_id, 'first_ name', $single );
$ln= get_user_meta($user_id, 'last_name', $single );
$em= $user_email->user_email;
$ph= get_user_meta($user_id, 'billing_phone', $single );
$ad= get_user_meta($user_id, 'billing_address_1', $single );
$ci= get_user_meta($user_id, 'billing_city', $single );
$st= get_user_meta($user_id, 'billing_state', $single );
$zi= get_user_meta($user_id, 'billing_postcode',$single );
$do= get_user_meta($user_id, '_money_spent', $single );
$sql = "INSERT INTO donors (user_id,first_name,last_name,email," .
"phone,address,city,state,zip,amount_donated)".
"VALUES('$user_id','$fn','$ln','$em','$ph','$ad','$ci','$st','$zi','$do')";
$result = mysqli_query($wpdb, $sql) or die('Write Error!');
}
</code></pre>
| [
{
"answer_id": 232685,
"author": "stoi2m1",
"author_id": 10907,
"author_profile": "https://wordpress.stackexchange.com/users/10907",
"pm_score": 0,
"selected": false,
"text": "<p><strong>NOTE:</strong> This answer looks irrelevant to the OP's question after further analysis of the added/... | 2016/07/20 | [
"https://wordpress.stackexchange.com/questions/232675",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/98590/"
] | I am trying to figure out how to add user information and specific meta data to a separate table through PHP. I would prefer to do this when a user posted to the `wp_users` and `wp_usermeta` table. I am using the WooCommerce Auction plugin and the Salient theme.
Also if I made a PHP file that ran a query to pull the data and then insert, where is a good place I can call that function to ensure the table is up to date?
This is the function I've created.
```
add_action('user_register', 'save_to_donors',10,1);
function save_to_donors( $user_id ) {
$single = true;
$user_email = get_userdata($user_id);
$fn= get_user_meta($user_id, 'first_ name', $single );
$ln= get_user_meta($user_id, 'last_name', $single );
$em= $user_email->user_email;
$ph= get_user_meta($user_id, 'billing_phone', $single );
$ad= get_user_meta($user_id, 'billing_address_1', $single );
$ci= get_user_meta($user_id, 'billing_city', $single );
$st= get_user_meta($user_id, 'billing_state', $single );
$zi= get_user_meta($user_id, 'billing_postcode',$single );
$do= get_user_meta($user_id, '_money_spent', $single );
$sql = "INSERT INTO donors (user_id,first_name,last_name,email," .
"phone,address,city,state,zip,amount_donated)".
"VALUES('$user_id','$fn','$ln','$em','$ph','$ad','$ci','$st','$zi','$do')";
$result = mysqli_query($wpdb, $sql) or die('Write Error!');
}
``` | Looks to me you should be seeking a woocommerce purchase completion hook. This would be when you could add that a donation has been made and at what amount, then you could grab any user information, amounted donated and other info you need and save it to your donor table.
use this:
```
add_action('woocommerce_order_status_completed', 'save_to_donors',10,1);
```
instead of this:
```
add_action('user_register', 'save_to_donors',10,1);
```
also change `$user_id` to `$order_id` as the parameter being passed into your function.
You will need to make some changes to your function since now `$order_id` will be passed into your function instead of `$user_id`. You can use some of the following code to get the `$order` object and `$user_id` I also found some other code that will get you info from the order vs from the users meta, not sure if they are going to be different.
```
$order = new WC_Order( $order_id );
$user_id = $order->user_id;
$billing_address = $order->get_billing_address();
$billing_address_html = $order->get_formatted_billing_address(); // for printing or displaying on web page
$shipping_address = $order->get_shipping_address();
$shipping_address_html = $order->get_formatted_shipping_address(); // for printing or displaying on web page
```
Info on the use of this hook [woocommerce\_order\_status\_completed](http://squelchdesign.com/web-design-newbury/woocommerce-detecting-order-complete-on-order-completion/)
Info on how to [get user id from order id](https://stackoverflow.com/questions/22843504/how-to-get-customer-details-from-order-in-woocommerce) |
232,692 | <p>I have to make several changes to a website, and I'm willing to setup a copy of the current one on a subdirectory, on the same server.</p>
<p>I.E. if my site is <code>www.example.com</code>, what I'm trying to do is to fully copy it to <code>www.example.com/new/</code>, make all the necessary modifications, then, once it is done, copy it back to the main directory.</p>
<p>I know that it is not a simple matter of moving files, I guess that this is a complex matter involving different file paths and database entries. I'd like to know how can I safely do it and it the whole process has to be done manually or if there are some automatic tools (i.e. plugins) that can help me doing it without mistakes.</p>
| [
{
"answer_id": 232685,
"author": "stoi2m1",
"author_id": 10907,
"author_profile": "https://wordpress.stackexchange.com/users/10907",
"pm_score": 0,
"selected": false,
"text": "<p><strong>NOTE:</strong> This answer looks irrelevant to the OP's question after further analysis of the added/... | 2016/07/20 | [
"https://wordpress.stackexchange.com/questions/232692",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/98169/"
] | I have to make several changes to a website, and I'm willing to setup a copy of the current one on a subdirectory, on the same server.
I.E. if my site is `www.example.com`, what I'm trying to do is to fully copy it to `www.example.com/new/`, make all the necessary modifications, then, once it is done, copy it back to the main directory.
I know that it is not a simple matter of moving files, I guess that this is a complex matter involving different file paths and database entries. I'd like to know how can I safely do it and it the whole process has to be done manually or if there are some automatic tools (i.e. plugins) that can help me doing it without mistakes. | Looks to me you should be seeking a woocommerce purchase completion hook. This would be when you could add that a donation has been made and at what amount, then you could grab any user information, amounted donated and other info you need and save it to your donor table.
use this:
```
add_action('woocommerce_order_status_completed', 'save_to_donors',10,1);
```
instead of this:
```
add_action('user_register', 'save_to_donors',10,1);
```
also change `$user_id` to `$order_id` as the parameter being passed into your function.
You will need to make some changes to your function since now `$order_id` will be passed into your function instead of `$user_id`. You can use some of the following code to get the `$order` object and `$user_id` I also found some other code that will get you info from the order vs from the users meta, not sure if they are going to be different.
```
$order = new WC_Order( $order_id );
$user_id = $order->user_id;
$billing_address = $order->get_billing_address();
$billing_address_html = $order->get_formatted_billing_address(); // for printing or displaying on web page
$shipping_address = $order->get_shipping_address();
$shipping_address_html = $order->get_formatted_shipping_address(); // for printing or displaying on web page
```
Info on the use of this hook [woocommerce\_order\_status\_completed](http://squelchdesign.com/web-design-newbury/woocommerce-detecting-order-complete-on-order-completion/)
Info on how to [get user id from order id](https://stackoverflow.com/questions/22843504/how-to-get-customer-details-from-order-in-woocommerce) |
232,752 | <p>I'm trying to write a little script within my <code>footer.php</code> (which I'll later transform into a plugin) that send two form fields to a custom table (<code>wp_newsletter</code>). I'm already sending the form and writing to the table correctly, but I don't know how I can send a success or fail message back to the user. My current code is as follows:</p>
<pre><code><form method="post">
<input type="text" name="user_name">Name
<input type="text" name="user_email">Email
<input type="submit">
<?php echo $message; ?>
</form>
<?php
global $wpdb;
$table = $wpdb->prefix . "newsletter";
$name = sanitize_text_field( $_POST["user_name"] );
$email = sanitize_email( $_POST["user_email"] );
$message = "";
if( isset($_POST["submit"]) ) {
if ( is_email($email) && isset($name)) {
if ( $wpdb->insert( $table, array("name" => $name, "email" => $email)) != false ) {
$message = "Your subscription was sent.";
}
}
else {
if ( !is_email($email) ) {
$message = "Invalid email address.";
} elseif ( !isset($name) ) {
$message = "The field name is mandatory.";
} else {
$message = "Both name and email fields are mandatory.";
}
}
} else {
$message = "Please, try again later.";
}
?>
<?php wp_footer(); ?>
</body>
</html>
</code></pre>
<p>I (think) am testing it right, accordingly to the <a href="https://codex.wordpress.org/Class_Reference/wpdb#INSERT_row" rel="nofollow">$wpdb</a> docs which says that:</p>
<blockquote>
<p>This function returns false if the row could not be inserted.
Otherwise, it returns the number of affected rows (which will always
be 1).</p>
</blockquote>
| [
{
"answer_id": 232760,
"author": "scott",
"author_id": 93587,
"author_profile": "https://wordpress.stackexchange.com/users/93587",
"pm_score": 1,
"selected": false,
"text": "<p>When I realized that PHP is an acronym for \"PHP Hypertext Preprocessor\" -- emphasis on \"preprocessor\" -- I ... | 2016/07/20 | [
"https://wordpress.stackexchange.com/questions/232752",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/60070/"
] | I'm trying to write a little script within my `footer.php` (which I'll later transform into a plugin) that send two form fields to a custom table (`wp_newsletter`). I'm already sending the form and writing to the table correctly, but I don't know how I can send a success or fail message back to the user. My current code is as follows:
```
<form method="post">
<input type="text" name="user_name">Name
<input type="text" name="user_email">Email
<input type="submit">
<?php echo $message; ?>
</form>
<?php
global $wpdb;
$table = $wpdb->prefix . "newsletter";
$name = sanitize_text_field( $_POST["user_name"] );
$email = sanitize_email( $_POST["user_email"] );
$message = "";
if( isset($_POST["submit"]) ) {
if ( is_email($email) && isset($name)) {
if ( $wpdb->insert( $table, array("name" => $name, "email" => $email)) != false ) {
$message = "Your subscription was sent.";
}
}
else {
if ( !is_email($email) ) {
$message = "Invalid email address.";
} elseif ( !isset($name) ) {
$message = "The field name is mandatory.";
} else {
$message = "Both name and email fields are mandatory.";
}
}
} else {
$message = "Please, try again later.";
}
?>
<?php wp_footer(); ?>
</body>
</html>
```
I (think) am testing it right, accordingly to the [$wpdb](https://codex.wordpress.org/Class_Reference/wpdb#INSERT_row) docs which says that:
>
> This function returns false if the row could not be inserted.
> Otherwise, it returns the number of affected rows (which will always
> be 1).
>
>
> | It returns either the number of rows inserted or false on error.
Maybe you can get id of inserted recode or false if the insert fails:
**refer link**: <https://developer.wordpress.org/reference/classes/wpdb/insert/#return>
So you can check like below:
```
$result_check = $wpdb->insert( $table, array("name" => $name, "email" => $email));
if($result_check){
//successfully inserted.
}else{
//something gone wrong
}
``` |
232,759 | <p>I'm trying to add an incremental variable to each post that comes up in a series of queries. The purpose is to calculate a weight for each result in order to be able to order everything later.</p>
<p>This is what I've come up with so far, but I'm doing something wrong, as the weights seem to add up globally instead of for each particular post.</p>
<pre><code>// set the variables
$author_id = get_the_author_meta('ID');
$tags_id = wp_get_post_tags($post->ID); $first_tag = $tags_id[0]->term_id;
$categories_id = wp_get_post_categories($post->ID);
$weight = 0;
// loop for same tag
$by_tag = new WP_Query(array(
'tag__in' => $first_tag,
'posts_per_page' => '5'
));
// attempting to assign values to posts - unsuccessfully
if ($by_tag):
foreach ($by_tag as $post):
setup_postdata($post->ID);
$weight += 2;
endforeach;
endif;
// add ids to array
if ( $by_tag->have_posts() ) {
while ( $by_tag->have_posts() ) {
$by_tag->the_post();
$add[] = get_the_id();
}}
// loop for same category
$by_category = new WP_Query(array(
'category__in' => $categories_id,
'posts_per_page' => '5'
));
// same as before
if ($by_category):
foreach ($by_category as $post):
setup_postdata($post->ID);
$weight += 1;
endforeach;
endif;
// add ids to array
if ( $by_category->have_posts() ) {
while ( $by_category->have_posts() ) {
$by_category->the_post();
$add[] = get_the_id();
}}
// loop array of combined results
$related = new WP_Query(array(
'post__in' => $add,
'post__not_in' => array($post->ID),
'orderby' => $weight,
'order' => 'DESC',
'posts_per_page' => '10'
));
// show them
if ( $related->have_posts() ) {
while ( $related->have_posts() ) {
$related->the_post();
// [template]
}}
</code></pre>
| [
{
"answer_id": 232760,
"author": "scott",
"author_id": 93587,
"author_profile": "https://wordpress.stackexchange.com/users/93587",
"pm_score": 1,
"selected": false,
"text": "<p>When I realized that PHP is an acronym for \"PHP Hypertext Preprocessor\" -- emphasis on \"preprocessor\" -- I ... | 2016/07/20 | [
"https://wordpress.stackexchange.com/questions/232759",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/70333/"
] | I'm trying to add an incremental variable to each post that comes up in a series of queries. The purpose is to calculate a weight for each result in order to be able to order everything later.
This is what I've come up with so far, but I'm doing something wrong, as the weights seem to add up globally instead of for each particular post.
```
// set the variables
$author_id = get_the_author_meta('ID');
$tags_id = wp_get_post_tags($post->ID); $first_tag = $tags_id[0]->term_id;
$categories_id = wp_get_post_categories($post->ID);
$weight = 0;
// loop for same tag
$by_tag = new WP_Query(array(
'tag__in' => $first_tag,
'posts_per_page' => '5'
));
// attempting to assign values to posts - unsuccessfully
if ($by_tag):
foreach ($by_tag as $post):
setup_postdata($post->ID);
$weight += 2;
endforeach;
endif;
// add ids to array
if ( $by_tag->have_posts() ) {
while ( $by_tag->have_posts() ) {
$by_tag->the_post();
$add[] = get_the_id();
}}
// loop for same category
$by_category = new WP_Query(array(
'category__in' => $categories_id,
'posts_per_page' => '5'
));
// same as before
if ($by_category):
foreach ($by_category as $post):
setup_postdata($post->ID);
$weight += 1;
endforeach;
endif;
// add ids to array
if ( $by_category->have_posts() ) {
while ( $by_category->have_posts() ) {
$by_category->the_post();
$add[] = get_the_id();
}}
// loop array of combined results
$related = new WP_Query(array(
'post__in' => $add,
'post__not_in' => array($post->ID),
'orderby' => $weight,
'order' => 'DESC',
'posts_per_page' => '10'
));
// show them
if ( $related->have_posts() ) {
while ( $related->have_posts() ) {
$related->the_post();
// [template]
}}
``` | It returns either the number of rows inserted or false on error.
Maybe you can get id of inserted recode or false if the insert fails:
**refer link**: <https://developer.wordpress.org/reference/classes/wpdb/insert/#return>
So you can check like below:
```
$result_check = $wpdb->insert( $table, array("name" => $name, "email" => $email));
if($result_check){
//successfully inserted.
}else{
//something gone wrong
}
``` |
232,774 | <p>I'm displaying the current user's info on the front-end, but haven't been able to locate the correct hook for the bio, other than as an "author" hook. Help?</p>
| [
{
"answer_id": 232778,
"author": "jgraup",
"author_id": 84219,
"author_profile": "https://wordpress.stackexchange.com/users/84219",
"pm_score": 2,
"selected": false,
"text": "<p>You probably want to use <a href=\"https://codex.wordpress.org/Function_Reference/wp_get_current_user\" rel=\"... | 2016/07/21 | [
"https://wordpress.stackexchange.com/questions/232774",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/88351/"
] | I'm displaying the current user's info on the front-end, but haven't been able to locate the correct hook for the bio, other than as an "author" hook. Help? | You probably want to use [`wp_get_current_user`](https://codex.wordpress.org/Function_Reference/wp_get_current_user) to find out which user is browsing the site.
```
$current_user = wp_get_current_user();
echo 'User ID: ' . $current_user->ID . '<br />';
```
From there you'll use the `ID` to pull the user's metadata with [`get_user_meta`](https://codex.wordpress.org/Function_Reference/get_user_meta).
```
$all_meta_for_user = get_user_meta( $current_user->ID );
echo 'User Description: ' . $all_meta_for_user['description'] . '<br />';
```
The `description` key is probably what you're after.
---
As you pointed out, the [`WP_User`](https://core.trac.wordpress.org/browser/tags/4.5.3/src/wp-includes/class-wp-user.php) already includes a few fields on it which may be duplicated in the user\_meta, including `$current_user->description`.
```
/**
11 * Core class used to implement the WP_User object.
12 *
13 * @since 2.0.0
14 *
15 * @property string $nickname
16 * @property string $description
17 * @property string $user_description
18 * @property string $first_name
19 * @property string $user_firstname
20 * @property string $last_name
21 * @property string $user_lastname
22 * @property string $user_login
23 * @property string $user_pass
24 * @property string $user_nicename
25 * @property string $user_email
26 * @property string $user_url
27 * @property string $user_registered
28 * @property string $user_activation_key
29 * @property string $user_status
30 * @property string $display_name
31 * @property string $spam
32 * @property string $deleted
33 */
``` |
232,796 | <p>Having a few issues getting things to work after changing wordpress from http to https on a windows sever. The web.config file is a bit of a mare to work with and the hosting company seems to think that changing http to https in wordpress settings is the only change necessary. currently I can only get the site to load css/js files on any pages other than the homepage by using default permalinks. and when I try adding http to https redirects in the web-config it causes even more problems. I've exhausted google so any advice appreciated.</p>
| [
{
"answer_id": 232778,
"author": "jgraup",
"author_id": 84219,
"author_profile": "https://wordpress.stackexchange.com/users/84219",
"pm_score": 2,
"selected": false,
"text": "<p>You probably want to use <a href=\"https://codex.wordpress.org/Function_Reference/wp_get_current_user\" rel=\"... | 2016/07/21 | [
"https://wordpress.stackexchange.com/questions/232796",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/98674/"
] | Having a few issues getting things to work after changing wordpress from http to https on a windows sever. The web.config file is a bit of a mare to work with and the hosting company seems to think that changing http to https in wordpress settings is the only change necessary. currently I can only get the site to load css/js files on any pages other than the homepage by using default permalinks. and when I try adding http to https redirects in the web-config it causes even more problems. I've exhausted google so any advice appreciated. | You probably want to use [`wp_get_current_user`](https://codex.wordpress.org/Function_Reference/wp_get_current_user) to find out which user is browsing the site.
```
$current_user = wp_get_current_user();
echo 'User ID: ' . $current_user->ID . '<br />';
```
From there you'll use the `ID` to pull the user's metadata with [`get_user_meta`](https://codex.wordpress.org/Function_Reference/get_user_meta).
```
$all_meta_for_user = get_user_meta( $current_user->ID );
echo 'User Description: ' . $all_meta_for_user['description'] . '<br />';
```
The `description` key is probably what you're after.
---
As you pointed out, the [`WP_User`](https://core.trac.wordpress.org/browser/tags/4.5.3/src/wp-includes/class-wp-user.php) already includes a few fields on it which may be duplicated in the user\_meta, including `$current_user->description`.
```
/**
11 * Core class used to implement the WP_User object.
12 *
13 * @since 2.0.0
14 *
15 * @property string $nickname
16 * @property string $description
17 * @property string $user_description
18 * @property string $first_name
19 * @property string $user_firstname
20 * @property string $last_name
21 * @property string $user_lastname
22 * @property string $user_login
23 * @property string $user_pass
24 * @property string $user_nicename
25 * @property string $user_email
26 * @property string $user_url
27 * @property string $user_registered
28 * @property string $user_activation_key
29 * @property string $user_status
30 * @property string $display_name
31 * @property string $spam
32 * @property string $deleted
33 */
``` |
232,802 | <p>I just want to remove <strong>Comment's column</strong> in <strong>all post-types</strong> and in a <strong>single function</strong></p>
<p><a href="https://i.stack.imgur.com/xUdLd.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xUdLd.gif" alt="enter image description here"></a></p>
<p><strong>My current function , Have to do each post-type like this :</strong></p>
<pre><code>function remove_post_columns($columns) {
unset($columns['comments']);
return $columns;
}
add_filter('manage_edit-post_columns','remove_post_columns',10,1);
function remove_page_columns($columns) {
unset($columns['comments']);
return $columns;
}
add_filter('manage_edit-page_columns','remove_page_columns',10,1);
</code></pre>
<p><strong>Possible to do in a single function</strong> and for future post-types ?</p>
| [
{
"answer_id": 232803,
"author": "l2aelba",
"author_id": 6332,
"author_profile": "https://wordpress.stackexchange.com/users/6332",
"pm_score": 3,
"selected": true,
"text": "<p><strong>I got an alternative :</strong></p>\n\n<p><em>This will not just hiding but disabling also</em></p>\n\n<... | 2016/07/21 | [
"https://wordpress.stackexchange.com/questions/232802",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/6332/"
] | I just want to remove **Comment's column** in **all post-types** and in a **single function**
[](https://i.stack.imgur.com/xUdLd.gif)
**My current function , Have to do each post-type like this :**
```
function remove_post_columns($columns) {
unset($columns['comments']);
return $columns;
}
add_filter('manage_edit-post_columns','remove_post_columns',10,1);
function remove_page_columns($columns) {
unset($columns['comments']);
return $columns;
}
add_filter('manage_edit-page_columns','remove_page_columns',10,1);
```
**Possible to do in a single function** and for future post-types ? | **I got an alternative :**
*This will not just hiding but disabling also*
```
function disable_comments() {
$post_types = get_post_types();
foreach ($post_types as $post_type) {
if(post_type_supports($post_type,'comments')) {
remove_post_type_support($post_type,'comments');
remove_post_type_support($post_type,'trackbacks');
}
}
}
add_action('admin_init','disable_comments');
``` |
232,809 | <p>Hello I have code intended to get the most viewed post for last 2 days and it seems like not working or maybe my code is just incorrect. I appreciate any help. Thanks.</p>
<pre><code> $args = array(
'post_type' => 'post',
'meta_key' => 'post_views_count',
'orderby' => 'meta_value_num',
'date_query' => array(
array(
'after' => '2 days ago',
)
)
);
$the_query = new WP_Query( $args );
// The Loop
if ( $the_query->have_posts() ) {
echo '<ul class="posts-list">';
while ( $the_query->have_posts() ) {
$the_query->the_post(); ?>
<li>
<?php if ( has_post_thumbnail() ) : ?>
<a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>">
<?php the_post_thumbnail(); ?>
</a>
<?php endif; ?>
<div class="content">
<time datetime="<?php echo get_the_date(DATE_W3C); ?>"><?php the_time('d, F Y') ?></time>
<span class="comments">
<a href="<?php comments_link(); ?>" class="comments"><i class="fa fa-comments-o"></i> <?php echo get_comments_number(); ?></a>
</span>
<a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><?php the_title();?></a>
</div>
</li>
<?php }
echo '</ul>';
/* Restore original Post Data */
wp_reset_postdata();
} else {
// no posts found
}
</code></pre>
| [
{
"answer_id": 232987,
"author": "Marc",
"author_id": 71657,
"author_profile": "https://wordpress.stackexchange.com/users/71657",
"pm_score": 0,
"selected": false,
"text": "<p>Try adjusting your <code>$args</code>. You will need to get the date from two days ago and then pass the year, m... | 2016/07/21 | [
"https://wordpress.stackexchange.com/questions/232809",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/98686/"
] | Hello I have code intended to get the most viewed post for last 2 days and it seems like not working or maybe my code is just incorrect. I appreciate any help. Thanks.
```
$args = array(
'post_type' => 'post',
'meta_key' => 'post_views_count',
'orderby' => 'meta_value_num',
'date_query' => array(
array(
'after' => '2 days ago',
)
)
);
$the_query = new WP_Query( $args );
// The Loop
if ( $the_query->have_posts() ) {
echo '<ul class="posts-list">';
while ( $the_query->have_posts() ) {
$the_query->the_post(); ?>
<li>
<?php if ( has_post_thumbnail() ) : ?>
<a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>">
<?php the_post_thumbnail(); ?>
</a>
<?php endif; ?>
<div class="content">
<time datetime="<?php echo get_the_date(DATE_W3C); ?>"><?php the_time('d, F Y') ?></time>
<span class="comments">
<a href="<?php comments_link(); ?>" class="comments"><i class="fa fa-comments-o"></i> <?php echo get_comments_number(); ?></a>
</span>
<a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><?php the_title();?></a>
</div>
</li>
<?php }
echo '</ul>';
/* Restore original Post Data */
wp_reset_postdata();
} else {
// no posts found
}
``` | I had the same issue. I had searched many times for this issue. but I could not find a solution for this.
>
> get the most viewed post for the last 2 days not to get the posts for the last 2 days
>
>
>
I have a table named "wp\_popularpostssummary".
[](https://i.stack.imgur.com/pAbjS.png)
Result ll be
[](https://i.stack.imgur.com/eI1f9.png)
so from this table get result postids by using following custom query
```
$results = $wpdb->get_results($wpdb->prepare('SELECT postid,COUNT(*) AS qy FROM `wp_popularpostssummary` WHERE `view_date` BETWEEN DATE_SUB(CURRENT_DATE(), INTERVAL 1 WEEK) AND CURRENT_DATE() GROUP BY postid ORDER BY qy DESC'));
```
query result ll be the post id's of most viewed posts for the last one week.
then using following foreach loop to get post id
```
$pids = [];
$results = json_decode(json_encode($results), true);
foreach ($results as $result) {
foreach ($result as $k => $v) {
if($k == 'postid'){
array_push($pids, $v);
}
};
}
```
finally, use post id to fetch post details. code ll be following
```
$args = array(
'post_type' => 'post',
'post_status' => 'publish',
'posts_per_page' => '10',
'orderby' => 'post__in',
'post__in' => $pids
);
$query = new WP_Query( $args ); if ( $query->have_posts() ) {
// The Loop
while ( $query->have_posts() ) { //code here
}
}
```
Change date duration according to you needs.
I hope this ll help to anyone in the feature!
Let me know if have a query. |
232,818 | <p>after migrating my WP site to a different domain and making adjustments, Font Awesome stopped showing icons and shows some weird text instead, for example & # 61505; (I can't copy it as a text, looks like an automatically generated graphics).</p>
<p>Please see attached image.
<a href="https://i.stack.imgur.com/WsuFB.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WsuFB.png" alt="enter image description here"></a></p>
<p>Any help?</p>
<p>Thanks!</p>
| [
{
"answer_id": 232987,
"author": "Marc",
"author_id": 71657,
"author_profile": "https://wordpress.stackexchange.com/users/71657",
"pm_score": 0,
"selected": false,
"text": "<p>Try adjusting your <code>$args</code>. You will need to get the date from two days ago and then pass the year, m... | 2016/07/21 | [
"https://wordpress.stackexchange.com/questions/232818",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/98690/"
] | after migrating my WP site to a different domain and making adjustments, Font Awesome stopped showing icons and shows some weird text instead, for example & # 61505; (I can't copy it as a text, looks like an automatically generated graphics).
Please see attached image.
[](https://i.stack.imgur.com/WsuFB.png)
Any help?
Thanks! | I had the same issue. I had searched many times for this issue. but I could not find a solution for this.
>
> get the most viewed post for the last 2 days not to get the posts for the last 2 days
>
>
>
I have a table named "wp\_popularpostssummary".
[](https://i.stack.imgur.com/pAbjS.png)
Result ll be
[](https://i.stack.imgur.com/eI1f9.png)
so from this table get result postids by using following custom query
```
$results = $wpdb->get_results($wpdb->prepare('SELECT postid,COUNT(*) AS qy FROM `wp_popularpostssummary` WHERE `view_date` BETWEEN DATE_SUB(CURRENT_DATE(), INTERVAL 1 WEEK) AND CURRENT_DATE() GROUP BY postid ORDER BY qy DESC'));
```
query result ll be the post id's of most viewed posts for the last one week.
then using following foreach loop to get post id
```
$pids = [];
$results = json_decode(json_encode($results), true);
foreach ($results as $result) {
foreach ($result as $k => $v) {
if($k == 'postid'){
array_push($pids, $v);
}
};
}
```
finally, use post id to fetch post details. code ll be following
```
$args = array(
'post_type' => 'post',
'post_status' => 'publish',
'posts_per_page' => '10',
'orderby' => 'post__in',
'post__in' => $pids
);
$query = new WP_Query( $args ); if ( $query->have_posts() ) {
// The Loop
while ( $query->have_posts() ) { //code here
}
}
```
Change date duration according to you needs.
I hope this ll help to anyone in the feature!
Let me know if have a query. |
232,826 | <p>I have a form on a page that search property with a location field and I used the following meta query to process the search;</p>
<pre><code>$location = preg_replace('/^-|-$|[^-a-zA-Z0-9]/', '', $_GET['location']);
$meta_query = array( 'relation' => 'AND' );
if($location) {
$meta_query[] = array(
'relation' => 'OR',
array(
'key' => 'property_country',
'value' => $location,
'compare' => 'LIKE'
),
array(
'key' => 'property_city',
'value' => $location,
'compare' => 'LIKE'
),
array(
'key' => 'property_location',
'value' => $location,
'compare' => 'LIKE'
)
);
}
</code></pre>
<p>However, it works fine if I search for <em>New</em> but returns no results if I search for <em>New York</em>. How can I resolve this? Is there a way to add a wildcard before and after the <code>$location</code>? I tried adding <code>'*'.$location.'*'</code> but that did nothing.</p>
| [
{
"answer_id": 232828,
"author": "FaCE",
"author_id": 96768,
"author_profile": "https://wordpress.stackexchange.com/users/96768",
"pm_score": 2,
"selected": false,
"text": "<p>Have you <code>var_dump</code>ed <code>$location</code>?</p>\n\n<p><code>WP_Query</code>'s <code>meta_query</cod... | 2016/07/21 | [
"https://wordpress.stackexchange.com/questions/232826",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/36773/"
] | I have a form on a page that search property with a location field and I used the following meta query to process the search;
```
$location = preg_replace('/^-|-$|[^-a-zA-Z0-9]/', '', $_GET['location']);
$meta_query = array( 'relation' => 'AND' );
if($location) {
$meta_query[] = array(
'relation' => 'OR',
array(
'key' => 'property_country',
'value' => $location,
'compare' => 'LIKE'
),
array(
'key' => 'property_city',
'value' => $location,
'compare' => 'LIKE'
),
array(
'key' => 'property_location',
'value' => $location,
'compare' => 'LIKE'
)
);
}
```
However, it works fine if I search for *New* but returns no results if I search for *New York*. How can I resolve this? Is there a way to add a wildcard before and after the `$location`? I tried adding `'*'.$location.'*'` but that did nothing. | Have you `var_dump`ed `$location`?
`WP_Query`'s `meta_query` uses the class `WP_Meta_Query`, which automatically appends and prepends '%' to any *string* passed to it:
```
// From wp-includes/class-wp-meta-query.php:610
switch ( $meta_compare ) {
// ...
case 'LIKE' :
case 'NOT LIKE' :
$meta_value = '%' . $wpdb->esc_like( $meta_value ) . '%';
$where = $wpdb->prepare( '%s', $meta_value );
break;
// ...
}
```
So maybe try using `(string) $location` as the sql statement is prepared, and expecting a string -- that's what the `%s` means in the line `$where = $wpdb->prepare( '%s', $meta_value );`. You can cast your variable to a string like this:
```
$location = (string) preg_replace('/^-|-$|[^-a-zA-Z0-9]/', '', $_GET['location']);
``` |
232,873 | <p>I created a page template to list all products of a specific product line.
Now I want to list all posts from this custom post type (products) based on the taxonomy described in the shortcode for each page.</p>
<p>Example:</p>
<p>Page "List of all Prime products"</p>
<p>[products line="prime"]</p>
<p>I tried this code:</p>
<pre><code>function shortcode_mostra_produtos ( $atts ) {
$atts = shortcode_atts( array(
'default' => ''
), $atts );
$terms = get_terms('linhas');
wp_reset_query();
$args = array('post_type' => 'produtos',
'tax_query' => array(
array(
'taxonomy' => 'linhas',
'field' => 'slug',
'terms' => $atts,
),
),
);
$loop = new WP_Query($args);
if($loop->have_posts()) {
while($loop->have_posts()) : $loop->the_post();
echo ' "'.get_the_title().'" ';
endwhile;
}
}
add_shortcode( 'produtos','shortcode_mostra_produtos' );
</code></pre>
| [
{
"answer_id": 232879,
"author": "Howdy_McGee",
"author_id": 7355,
"author_profile": "https://wordpress.stackexchange.com/users/7355",
"pm_score": 4,
"selected": true,
"text": "<p>First off, it's always good to register shortcode during <code>init</code> versus just in your general <code... | 2016/07/21 | [
"https://wordpress.stackexchange.com/questions/232873",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/98722/"
] | I created a page template to list all products of a specific product line.
Now I want to list all posts from this custom post type (products) based on the taxonomy described in the shortcode for each page.
Example:
Page "List of all Prime products"
[products line="prime"]
I tried this code:
```
function shortcode_mostra_produtos ( $atts ) {
$atts = shortcode_atts( array(
'default' => ''
), $atts );
$terms = get_terms('linhas');
wp_reset_query();
$args = array('post_type' => 'produtos',
'tax_query' => array(
array(
'taxonomy' => 'linhas',
'field' => 'slug',
'terms' => $atts,
),
),
);
$loop = new WP_Query($args);
if($loop->have_posts()) {
while($loop->have_posts()) : $loop->the_post();
echo ' "'.get_the_title().'" ';
endwhile;
}
}
add_shortcode( 'produtos','shortcode_mostra_produtos' );
``` | First off, it's always good to register shortcode during `init` versus just in your general `functions.php` file. At the very least `add_shortcode()` should be in `init`. Anyway, let's begin!
Whenever you use [`add_shortcode()`](https://codex.wordpress.org/Function_Reference/add_shortcode) the first parameter is going to be the name of the shortcode and the 2nd will be the callback function. This means that:
```
[products line="prime"]
```
Should be instead:
```
[produtos line="prime"]
```
So far we have this:
```
/**
* Register all shortcodes
*
* @return null
*/
function register_shortcodes() {
add_shortcode( 'produtos', 'shortcode_mostra_produtos' );
}
add_action( 'init', 'register_shortcodes' );
/**
* Produtos Shortcode Callback
* - [produtos]
*
* @param Array $atts
*
* @return string
*/
function shortcode_mostra_produtos( $atts ) {
/** Our outline will go here
}
```
Let's take a look at processing attributes. The way [`shortcode_atts()`](https://codex.wordpress.org/Function_Reference/shortcode_atts) works is that it will try to match attributes passed to the shortcode with attributes in the passed array, left side being the key and the right side being the defaults. So we need to change `defaults` to `line` instead - if we want to default to a category, this would be the place:
```
$atts = shortcode_atts( array(
'line' => ''
), $atts );
```
IF the user adds a attribute to the shortcode `line="test"` then our array index `line` will hold `test`:
```
echo $atts['line']; // Prints 'test'
```
All other attributes will be ignored unless we add them to the `shortcode_atts()` array. Finally it's just the WP\_Query and printing what you need:
```
/**
* Register all shortcodes
*
* @return null
*/
function register_shortcodes() {
add_shortcode( 'produtos', 'shortcode_mostra_produtos' );
}
add_action( 'init', 'register_shortcodes' );
/**
* Produtos Shortcode Callback
*
* @param Array $atts
*
* @return string
*/
function shortcode_mostra_produtos( $atts ) {
global $wp_query,
$post;
$atts = shortcode_atts( array(
'line' => ''
), $atts );
$loop = new WP_Query( array(
'posts_per_page' => 200,
'post_type' => 'produtos',
'orderby' => 'menu_order title',
'order' => 'ASC',
'tax_query' => array( array(
'taxonomy' => 'linhas',
'field' => 'slug',
'terms' => array( sanitize_title( $atts['line'] ) )
) )
) );
if( ! $loop->have_posts() ) {
return false;
}
while( $loop->have_posts() ) {
$loop->the_post();
echo the_title();
}
wp_reset_postdata();
}
``` |